需要使用django Rest框架启动AGSI服务器

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

我是 websocket 的初学者,我需要与 Django 频道聊天。当我运行命令启动 ASGI 服务器时,我收到此错误

daphne -b 0.0.0.0 -p 8001 项目.asgi:应用程序 引发配置不当( django.core.exceptions.ImproperlyConfigured:请求设置INSTALLED_APPS,但未配置设置。在访问设置之前,您必须定义环境变量 DJANGO_SETTINGS_MODULE 或调用 settings.configure()。

这里是asgi.py

import os
import django
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from chat.routing import websocket_urlpatterns
from django.conf import settings


settings.configure(project.settings) 

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": URLRouter(
        websocket_urlpatterns
    ),
})

设置.py:

INSTALLED_APPS = [
    'daphne',
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles", 
    
    'djoser',
    'rest_framework',
    'rest_framework_simplejwt',
    'channels',
    'channels_redis',
    
    
    # apps
    "accounts",
    "chat"
]
ASGI_APPLICATION = "project.asgi.application"
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels_redis.core.RedisChannelLayer",
        "CONFIG": {
            "hosts": [("127.0.0.1", 6379)],
        },
    },
}

我需要启动 Web 套接字服务器来为聊天应用程序发出 api 请求

django-rest-framework websocket django-channels
1个回答
0
投票

在 asgi.py 的开头添加以下行

import os
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project.settings')
© www.soinside.com 2019 - 2024. All rights reserved.