使用daphne服务器运行我的 Django Channels 时出现这种错误。routing.py
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.
这是文档对daphne服务器的解释,
Daphne 是用于 ASGI 和 ASGI-HTTP 的 HTTP、HTTP2 和 WebSocket 协议服务器,旨在为 Django 通道提供支持。
支持协议自动协商;不需要 URL 前缀来确定 WebSocket 端点与 HTTP 端点。
注意:Daphne 2 与 Channels 1.x 应用程序不兼容,仅与 Channels 2.x 和其他 ASGI 应用程序兼容。安装 1.x 版本的 Daphne 以获得 Channels 1.x 支持。
如您所见,我们可以通过daphneHTTP服务器同时使用和WS协议,而无需使用Gunicorn服务器。您可以做的只是将以下行添加到文件顶部。routing.py
from .wsgi import *
所以现在你的routing.py文件应该是这样的,
# DockerDjangoNginx is my project name
# your routing.py file should be in this location where the wsgi.py file is placed
# DockerDjangoNginx/DockerDjangoNginx/routing.py
from .wsgi import * # add this line to top of your code
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import comapp.routing as routing
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
routing.websocket_urlpatterns
)
),
})
现在你可以运行你的daphne服务器了。
(venv) [root@t2mdocker]#daphne -b 0.0.0.0 -p 8000 DockerDjangoNginx.routing:application
2019-05-30 03:33:06,390 INFO Starting server at tcp:port=8000:interface=0.0.0.0
2019-05-30 03:33:06,391 INFO HTTP/2 support enabled
2019-05-30 03:33:06,391 INFO Configuring endpoint tcp:port=8000:interface=0.0.0.0
2019-05-30 03:33:06,392 INFO Listening on TCP address 0.0.0.0:8000
HTTP/2 support not enabled (install the http2 and tls Twisted extras)如果您在运行daphne服务器时看到类似的内容,您可以运行pip install -U Twisted[tls,http2]以纠正这些错误。