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

epfja78i  于 2023-01-26  发布在  Go
关注(0)|答案(1)|浏览(213)

你好,我正在按照https://github.com/mitchtabian/HOWTO-django- channels-daphne教程来部署mn django channels应用程序,但是我在启动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的状态首先显示我没有错误,然后显示此错误:

● 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达芙妮服务

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.

我的网站: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))
        ),
    }
)

我怎样才能解决这个问题?

lf5gs5x2

lf5gs5x21#

在你的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
...
...

相关问题