django 通道部署时出现 daphne 错误请求设置 INSTALLED_APPS,但未配置设置

问题描述 投票:0回答:2

您好,我正在关注本教程https://github.com/mitchtabian/HOWTO-django-channels-daphne 部署 mn django 通道应用程序,但我在启动 daphne 时遇到问题。 到目前为止我创建了 daphne.service ;

[Unit]
Description=WebSocket Daphne Service
After=network.target

[Service]
Type=simple
User=root
WorkingDirectory=/home/django/Petsly/src
ExecStart=/home/django/CodingWithMitchChat/venv/bin/python /home/django/CodingWithMitchChat/venv/bin/daphne -b 0.0.0.0 -p 8001 newo.asgi:application
Restart=on-failure

[Install]
WantedBy=multi-user.target

 systemctl start daphne.service
启动达芙妮后, daphne 的状态首先显示没有错误,一秒钟后显示此错误:

● daphne.service - WebSocket Daphne Service
     Loaded: loaded (/etc/systemd/system/daphne.service; enabled; vendor preset: enabled)
     Active: failed (Result: exit-code) since Mon 2022-11-28 07:20:24 UTC; 2s ago
    Process: 122863 ExecStart=/home/django/Petsly/venv/bin/python /home/django/Petsly/venv/bin/daphne -b 0.0.0.0 -p 8001 >
   Main PID: 122863 (code=exited, status=1/FAILURE)

Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Main process exited, code=exited, status=1/FAILURE
Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Failed with result 'exit-code'.
Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Scheduled restart job, restart counter is at 5.
Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: Stopped WebSocket Daphne Service.
Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Start request repeated too quickly.
Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: daphne.service: Failed with result 'exit-code'.
Nov 28 07:20:24 ubuntu-g1-small3-fr-1 systemd[1]: Failed to start WebSocket Daphne Service.

和 sudo Journalctl -u daphne.service

v 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/usr/lib/python3.8/importlib/__init__.py", line 127, in import_module
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     return _bootstrap._gcd_import(name[level:], package, level)
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "<frozen importlib._bootstrap>", line 991, in _find_and_load
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "<frozen importlib._bootstrap_external>", line 848, in exec_module
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/src/./newo/asgi.py", line 7, in <module>
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     import myapp.routing
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/src/./myapp/routing.py", line 4, in <module>
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     from . import consumer
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/src/./myapp/consumer.py", line 10, in <module>
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     from.models import Thread, ChatMessage
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/src/./myapp/models.py", line 8, in <module>
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     from django.contrib.auth.models import AbstractUser , UserManager , BaseUserManager
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/venv/lib/python3.8/site-packages/django/contrib/auth/models.py", line 3, in <module>
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/venv/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 49, in <module>
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     class AbstractBaseUser(models.Model):
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/venv/lib/python3.8/site-packages/django/db/models/base.py", line 127, in __new__
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     app_config = apps.get_containing_app_config(module)
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/venv/lib/python3.8/site-packages/django/apps/registry.py", line 260, in get_containing_app_config
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     self.check_apps_ready()
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/venv/lib/python3.8/site-packages/django/apps/registry.py", line 137, in check_apps_ready
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     settings.INSTALLED_APPS
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 92, in __getattr__
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     self._setup(name)
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:   File "/home/django/Petsly/venv/lib/python3.8/site-packages/django/conf/__init__.py", line 72, in _setup
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]:     raise ImproperlyConfigured(
Nov 27 16:21:57 ubuntu-g1-small3-fr-1 python[4682]: django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.

我的设置.py:

"""
Django settings for newo project.

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

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

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

from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent


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

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = "django-insecure-h5ucd^qu43idq245i2coh1@%$#ak)p68e2ng#2%@$hvz6te9tq"

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

ALLOWED_HOSTS = ['0.0.0.0' , '185.226.117.186' , '127.0.0.0']


# Application definition

INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    'myapp',
    'kavenegar',
    'channels',
    'bootstrap5',
]

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 = "newo.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 = "newo.wsgi.application"
ASGI_APPLICATION = "newo.asgi.application"
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
        'ROUTING': 'myapp.routing.websocket_urlpatterns',
    },
}

# Database
# https://docs.djangoproject.com/en/4.1/ref/settings/#databases

DATABASES = {
    "default": {
        "ENGINE": "django.db.backends.sqlite3",
        "NAME": BASE_DIR / "db.sqlite3",
    }
}




AUTHENTICATION_BACKENDS = [
    'django.contrib.auth.backends.ModelBackend',
    'myapp.myauth.PasswordlessAuthBackend',
]

# Password validation
# https://docs.djangoproject.com/en/4.1/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/4.1/topics/i18n/

LANGUAGE_CODE = "en-us"

TIME_ZONE = "UTC"

USE_I18N = True

USE_TZ = True


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



STATIC_URL = "static/"
STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)

# Default primary key field type
# https://docs.djangoproject.com/en/4.1/ref/settings/#default-auto-field

DEFAULT_AUTO_FIELD = "django.db.models.BigAutoField"

AUTH_USER_MODEL = 'myapp.User'

MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR,'media')

我的asgi.py

from django.conf import settings
settings.configure()
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "newo.settings")

import myapp.routing






django_asgi_app = get_asgi_application()


application = ProtocolTypeRouter(
    {
        "http": django_asgi_app,
        "websocket": AllowedHostsOriginValidator(
            AuthMiddlewareStack(URLRouter(myapp.routing.websocket_urlpatterns))
        ),
    }
)

我该如何解决这个问题?

python-3.x django websocket django-channels daphne
2个回答
1
投票

在你的

asgi.py

改变这个,

from django.conf import settings
settings.configure()
import os
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "newo.settings")

import myapp.routing

对此,

from django.conf import settings
settings.configure()
import os
import django
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "newo.settings")
django.setup()
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.security.websocket import AllowedHostsOriginValidator
from django.core.asgi import get_asgi_application

import myapp.routing
...
...

0
投票

我做了同样的事情,但仍然给我同样的问题,你能告诉我你如何解决这个问题吗?我也在遵循相同的教程

© www.soinside.com 2019 - 2024. All rights reserved.