Home > Software engineering >  Is there a way to enable secure websockets on Django?
Is there a way to enable secure websockets on Django?

Time:11-16

I can't use secure websockets on Django with the sll enabled. I use the sslserver package for Django to allow HTTPS on the development server. My goal is to make a secure chat.

Here is the configuration :

INSTALLED_APPS = [
    'channels',
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'sslserver',
    'accounts',
    'chat',
]

#WSGI_APPLICATION = 'sendapp.wsgi.application'
ASGI_APPLICATION = 'sendapp.asgi.application'

# LEARN CHANNELS
CHANNEL_LAYERS = {
    "default": {
        "BACKEND": "channels.layers.InMemoryChannelLayer"
    },
}

Concerning the asgi file :

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sendapp.settings')

application = ProtocolTypeRouter({
  'https': get_asgi_application(),
  'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns))
})

I start the Django server this way :

python .\manage.py runsslserver --certificate .\sendapp\certif.crt --key .\sendapp\code.key 0.0.0.0:8000

I understand that to use secure websockets, you have to use a Daphne server. So I tried to run it in its basic configuration in the root of manage.py :

daphne sendapp.asgi:application     

but i have this error code in the shell :

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.

Does anyone have a solution to this error message ?

CodePudding user response:

I found the solution to the previous problem. It seems to come from the asgi file. More precisely from :

from django.core.asgi import get_asgi_application
django_asgi_app = get_asgi_application()

I don't know why but you have to put these two lines at the beginning of the file, they have to be the first lines of code, like this :

import os, django

from django.core.asgi import get_asgi_application

django_asgi_app = get_asgi_application()

from channels.auth import AuthMiddlewareStack

from channels.routing import ProtocolTypeRouter, URLRouter

from chat.routing import ws_urlpatterns

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sendapp.settings')
django.setup()

application = ProtocolTypeRouter({
  'https': django_asgi_app,
  'websocket': AuthMiddlewareStack(URLRouter(ws_urlpatterns))
})

Then afterwards, in a terminal :

export DJANGO_SETTINGS_MODULE =sendapp.settings

If you use powershell :

$env:DJANGO_SETTINGS_MODULE = 'sendapp.settings'

This should work now.

  • Related