So I have a Django application with React front-end through an API (django-restframework) and I would like to implement some websocket action (real time events) with Django Channels, is it better to create another server, just to websocket connections or integrate all in one application? I know it would change to ASGI, but don't know what it can causes or malfunction with HTTP connections after that. Thanks.
1 Answer
Top level of ASGI application stack is ProtocolTypeRouter, defined like this:
### this is in routing.py, silbling to your root urls.py
from channels.auth import AuthMiddlewareStack
from channels.routing import ProtocolTypeRouter, URLRouter
import <yourApp>.routing
from django.conf.urls import url
application = ProtocolTypeRouter({
# (http->django views is added by default)
'websocket': AuthMiddlewareStack(
URLRouter(
<yourApp>.routing.websocket_urlpatterns
),
),
})
Further, in your yourApp.routing.py you have to define websocket_urlpatterns like this:
### this is in your <websocketAppDir>/routing.py
websocket_urlpatterns = [re_path(r'ws/<yourApp>/(?P<whatEver>[\w\-.]+)/$', consumers.MsgSignalConsumer),]
So far the Channel part. Now HTTP protocol: Http protocol request will be passed from this ProtocolTypeRouter through to the django's standard routing, so all django hhtp requests stay 'untouched' and full in service.
Bottom line: you switch to asgi.py, in there you are defining
application = get_default_application() ### channels asgi
set up channels (ProtocolTypeRouter) - that's it.