I got this kind of error when running my Django Channels's routing.py
using daphne server.
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.
This is what documentation explain about daphne servers,
Daphne is a HTTP, HTTP2 and WebSocket protocol server for ASGI and ASGI-HTTP, developed to power Django Channels.
It supports automatic negotiation of protocols; there’s no need for URL prefixing to determine WebSocket endpoints versus HTTP endpoints.
Note: Daphne 2 is not compatible with Channels 1.x applications, only with Channels 2.x and other ASGI applications. Install a 1.x version of Daphne for Channels 1.x support.
As you can see, we can use both HTTP
and WS
protocol through daphne server without using Gunicorn server. What you can do is just add below line to top of your routing.py
file.
from .wsgi import *
So now your routing.py
file should be like this,
# 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
)
),
})
Now you can run your daphne server.
(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
If you see something like this HTTP/2 support not enabled (install the http2 and tls Twisted extras)
when running daphne server, you can run pip install -U Twisted[tls,http2]
to correct those errors.