docker-compose / django TypeError:预期的str,字节或os.PathLike对象,而不是NoneType

时间:2019-01-23 04:09:47

标签: python django docker docker-compose

我正在尝试使用docker设置Django和postgres开发环境,因此我可以更轻松地在其他机器上运行它,以及从1个终端窗口运行所有内容(一旦我确定了,我将添加我的react前端排除此Django错误)。

我感觉自己已经接近了,但是对这个错误很挂念。看起来像是运行start.sh时的输出。在此设置中,我一直在遵循许多不同的指南,因此,也许我刚刚摆脱了麻烦。不确定该错误的出处。

我能够在容器外部成功执行runserver命令,因此似乎与容器无关。

错误:

django_server | Traceback (most recent call last):
django_server |   File "manage.py", line 15, in <module>
django_server |     execute_from_command_line(sys.argv)
django_server |   File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 371, in execute_from_command_line
django_server |     utility.execute()
django_server |   File "/usr/local/lib/python3.7/site-packages/django/core/management/__init__.py", line 365, in execute
django_server |     self.fetch_command(subcommand).run_from_argv(self.argv)
django_server |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 288, in run_from_argv
django_server |     self.execute(*args, **cmd_options)
django_server |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 335, in execute
django_server |     output = self.handle(*args, **options)
django_server |   File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/migrate.py", line 79, in handle
django_server |     executor = MigrationExecutor(connection, self.migration_progress_callback)
django_server |   File "/usr/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in __init__
django_server |     self.loader = MigrationLoader(self.connection)
django_server |   File "/usr/local/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __init__
django_server |     self.build_graph()
django_server |   File "/usr/local/lib/python3.7/site-packages/django/db/migrations/loader.py", line 200, in build_graph
django_server |     self.load_disk()
django_server |   File "/usr/local/lib/python3.7/site-packages/django/db/migrations/loader.py", line 99, in load_disk
django_server |     directory = os.path.dirname(module.__file__)
django_server |   File "/usr/local/lib/python3.7/posixpath.py", line 156, in dirname
django_server |     p = os.fspath(p)
django_server | TypeError: expected str, bytes or os.PathLike object, not NoneType
django_server | Performing system checks...
django_server | 
django_server | System check identified no issues (0 silenced).
django_server | Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x7f2d34a73b70>
django_server | Traceback (most recent call last):
django_server |   File "/usr/local/lib/python3.7/site-packages/django/utils/autoreload.py", line 225, in wrapper
django_server |     fn(*args, **kwargs)
django_server |   File "/usr/local/lib/python3.7/site-packages/django/core/management/commands/runserver.py", line 123, in inner_run
django_server |     self.check_migrations()
django_server |   File "/usr/local/lib/python3.7/site-packages/django/core/management/base.py", line 427, in check_migrations
django_server |     executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS])
django_server |   File "/usr/local/lib/python3.7/site-packages/django/db/migrations/executor.py", line 18, in __init__
django_server |     self.loader = MigrationLoader(self.connection)
django_server |   File "/usr/local/lib/python3.7/site-packages/django/db/migrations/loader.py", line 49, in __init__
django_server |     self.build_graph()
django_server |   File "/usr/local/lib/python3.7/site-packages/django/db/migrations/loader.py", line 200, in build_graph
django_server |     self.load_disk()
django_server |   File "/usr/local/lib/python3.7/site-packages/django/db/migrations/loader.py", line 99, in load_disk
django_server |     directory = os.path.dirname(module.__file__)
django_server |   File "/usr/local/lib/python3.7/posixpath.py", line 156, in dirname
django_server |     p = os.fspath(p)
django_server | TypeError: expected str, bytes or os.PathLike object, not NoneType

Dockerfile:

FROM python:3.7-alpine

ENV PYTHONUNBUFFERED 1

RUN apk add --no-cache --virtual .build-deps \
    gcc \
    python3-dev \
    musl-dev \
    postgresql-dev


# create and set work directory
RUN mkdir /code
WORKDIR /code

ADD ./requirements /requirements
# COPY ./requirements /requirements

RUN pip install --upgrade pip
RUN pip install -r /requirements/local.txt --ignore-installed

# RUN apk del --no-cache .build-deps

ADD . /code/

COPY ./docker_compose/django/development/start.sh /start.sh
COPY ./docker_compose/django/entrypoint.sh /entrypoint.sh
RUN sed -i 's/\r//' /entrypoint.sh \
    && sed -i 's/\r//' /start.sh \
    && chmod +x /entrypoint.sh \
    && chmod +x /start.sh

ENTRYPOINT ["/entrypoint.sh"]

docker-compose-dev.yml:

version: '3'

volumes:
  local_postgres_data_dev: {}
  local_postgres_backup_dev: {}

services:
  postgres:
    image: postgres:10.5
    env_file: .env
  django:
    container_name: django_server
    build:
      context: .
      dockerfile: ./docker_compose/django/development/Dockerfile
    depends_on:
      - postgres
      # - node
    volumes:
      - .:/app
    env_file: .env
    ports:
      - "8000:8000"
    command: /start.sh

entrypoint.sh:

#!/bin/sh
set -e
cmd="$@"

# the official postgres image uses 'postgres' as default user if not set explictly.
if [ -z "$POSTGRES_USER" ]; then
    export POSTGRES_USER=postgres
fi

# If not DB is set, then use USER by default
if [ -z "$POSTGRES_DB" ]; then
    export POSTGRES_DB=$POSTGRES_USER
fi

# Need to update the DATABASE_URL if using DOCKER
export DATABASE_URL=postgres://$POSTGRES_USER:$POSTGRES_PASSWORD@postgres:5432/$POSTGRES_DB



function postgres_ready(){
python << END
import sys
import psycopg2
try:
    conn = psycopg2.connect(dbname="$POSTGRES_DB", user="$POSTGRES_USER", password="$POSTGRES_PASSWORD", host="postgres")
except psycopg2.OperationalError:
    sys.exit(-1)
sys.exit(0)
END
}

until postgres_ready; do
  >&2 echo "Postgres is unavailable - sleeping"
  sleep 10
done
>&2 echo "Postgres is up - continuing..."
exec $cmd

start.sh:

#!/bin/sh
python manage.py migrate
python manage.py runserver 0.0.0.0:8000

编辑-添加结构和设置

项目结构:

.
├── api
│   ├── __init__.py
│   ├── __pycache__
│   ├── admin.py
│   ├── apps.py
│   ├── migrations
│   ├── models.py
│   ├── serializers.py
│   ├── tests.py
│   ├── urls.py
│   └── views.py
├── financeApp
│   ├── __init__.py
│   └── __pycache__
├── build
│   └── webpack-stats.json
├── config
│   ├── __init__.py
│   ├── __pycache__
│   ├── settings
│   ├── urls.py
│   └── wsgi.py
├── database20181022.json
├── datadump20190121.json
├── db.sqlite3
├── docker-compose-dev.yml
├── docker-compose.yml
├── docker_compose
│   ├── django
│   ├── nginx
│   ├── node
│   └── postgres
├── frontend
│   ├── README.md
│   ├── build
│   ├── config-overrides.js
│   ├── node_modules
│   ├── package-lock.json
│   ├── package.json
│   ├── package0.json
│   ├── public
│   └── src
├── manage.py
├── requirements
│   ├── base.txt
│   ├── local.txt
│   └── production.txt
└── templates
    └── main.html

Base.py:

"""
Django settings for Finance App project.

Generated by 'django-admin startproject' using Django 2.0.4.

For more information on this file, see
https://docs.djangoproject.com/en/2.0/topics/settings/

For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.0/ref/settings/
"""

import os
import dj_database_url

from decouple import config

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(
    os.path.dirname(os.path.abspath(__file__))))

# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.0/howto/deployment/checklist/

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = config('SECRET_KEY')

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = config('DEBUG', cast=bool)

# ALLOWED_HOSTS = []


# Application definition

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
    'api',
    'djmoney',
]

MIDDLEWARE = [
    'django.middleware.security.SecurityMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',

]

ROOT_URLCONF = 'config.urls'

TEMPLATES = [
    {
        'BACKEND': 'django.template.backends.django.DjangoTemplates',
        'DIRS': [os.path.join(BASE_DIR, "templates"), ],
        'APP_DIRS': True,
        'OPTIONS': {
            'context_processors': [
                'django.template.context_processors.debug',
                'django.template.context_processors.request',
                'django.contrib.auth.context_processors.auth',
                'django.contrib.messages.context_processors.messages',
            ],
        },
    },
]

WSGI_APPLICATION = 'config.wsgi.application'


# Database
# https://docs.djangoproject.com/en/2.0/ref/settings/#databases
DATABASES = {
    'default': dj_database_url.parse(config('DATABASE_URL')),
}
DATABASES['default']['ATOMIC_REQUESTS'] = True

# Added this to support deployment on Heroku
# https://devcenter.heroku.com/articles/django-app-configuration
db_from_env = dj_database_url.config(conn_max_age=500)
DATABASES['default'].update(db_from_env)

# DATABASES = {
#     'default': {
#         'ENGINE': 'django.db.backends.postgresql',
#         'NAME': 'finance_app',
#         'USER': 'finance_app_admin',
#         'PASSWORD': '',
#         # 'HOST': 'localhost',
#         'HOST': '127.0.0.1',
#         'PORT': '5432',
#     }
# }


# Password validation
# https://docs.djangoproject.com/en/2.0/ref/settings/#auth-password-validators

AUTH_PASSWORD_VALIDATORS = [
    {
        'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
    },
    {
        'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
    },
]


# Internationalization
# https://docs.djangoproject.com/en/2.0/topics/i18n/

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.0/howto/static-files/

STATIC_URL = '/static/'

STATICFILES_DIRS = [
    # os.path.join(os.path.join(BASE_DIR, 'frontend'), 'build', 'static')
    os.path.join(BASE_DIR, "frontend", "build", "static"),
]

# STATIC_ROOT = os.path.join(BASE_DIR, "frontend", "build", "static")

REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.LimitOffsetPagination',
    'PAGE_SIZE': 100
}

local.py:

import socket
import os

from .base import *


# Webpack Loader by Owais Lane
# ------------------------------------------------------------------------------
# https://github.com/owais/django-webpack-loader

WEBPACK_LOADER = {
    "DEFAULT": {
        "CACHE": not DEBUG,
        "BUNDLE_DIR_NAME": "frontend/build/static/",  # must end with slash
        "STATS_FILE": os.path.join(BASE_DIR, "frontend", "build", "webpack-stats.json"),
    }
}

# Django Debug Toolbar
# ------------------------------------------------------------------------------
# https://github.com/jazzband/django-debug-toolbar

MIDDLEWARE += (
    # 'debug_toolbar.middleware.DebugToolbarMiddleware',
    'corsheaders.middleware.CorsMiddleware',
)

CORS_ORIGIN_ALLOW_ALL = False
CORS_ORIGIN_WHITELIST = (
    'localhost:3000',
    '127.0.0.1:3000',
)


INSTALLED_APPS += (
    # 'debug_toolbar',
    'corsheaders',
    'webpack_loader',
)

INTERNAL_IPS = ['127.0.0.1', '10.0.2.2', ]

0 个答案:

没有答案