Channels
Strapper real-time deployment log
by Archie To, 18 April 2023
This real-time deployment log feature was implemented by following a tutorial on Django Channels.
All of the code below can be found in the Strapper GitLab repository
Setup
$ pip install -U daphne channels["daphne"]
In app_starter/app_starter/settings.py
:
INSTALLED_APPS = [
"daphne",
...,
]
ASGI_APPLICATION = "app_starter.asgi.application"
Configure ASGI app
Since wsgi doesn’t support long-lived connections, we will have to serve our app as an asgi app. In app_starter/app_starter/asgi.py
:
"""
ASGI config for app_starter project.
It exposes the ASGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/4.1/howto/deployment/asgi/
"""
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
from normal_users.routing import websocket_urlpatterns
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_starter.settings')
# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()
application = ProtocolTypeRouter({
"http": django_asgi_app,
"websocket": AllowedHostsOriginValidator(
AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
),
})
Here we are using ProtocolTypeRouter
as the root application, which
defines what asgi application to serve depending on the protocol type: