Channels

4.3.2 · active · verified Thu Apr 09

Channels is a project that extends Django's capabilities beyond traditional HTTP, enabling it to handle asynchronous protocols such as WebSockets, chat protocols, and IoT protocols. It is built upon the Asynchronous Server Gateway Interface (ASGI) specification, allowing Django applications to support long-running, event-driven connections alongside conventional HTTP views. The library is currently at version 4.3.2 and is actively maintained as an official Django Project, aligning its release cadence and Python/Django version support with the core framework.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates a minimal `asgi.py` configuration using `ProtocolTypeRouter` to handle both HTTP (via Django's `get_asgi_application()`) and WebSocket connections. It includes `AuthMiddlewareStack` for session and authentication support and `AllowedHostsOriginValidator` for security. The example uses an inline echo consumer for immediate testing, but typically you would define consumers in an app's `consumers.py` and route them via a `routing.py` module. To run this, you would also need `daphne` installed and configured in `INSTALLED_APPS`.

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 django.urls import path

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.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()

# myapp/consumers.py (example consumer)
# from channels.generic.websocket import AsyncWebsocketConsumer
# import json
# class ChatConsumer(AsyncWebsocketConsumer):
#     async def connect(self):
#         self.room_name = self.scope['url_route']['kwargs']['room_name']
#         self.room_group_name = 'chat_%s' % self.room_name
#         await self.channel_layer.group_add(
#             self.room_group_name,
#             self.channel_name
#         )
#         await self.accept()
#
#     async def disconnect(self, close_code):
#         await self.channel_layer.group_discard(
#             self.room_group_name,
#             self.channel_name
#         )
#
#     async def receive(self, text_data):
#         text_data_json = json.loads(text_data)
#         message = text_data_json['message']
#         await self.channel_layer.group_send(
#             self.room_group_name,
#             {
#                 'type': 'chat_message',
#                 'message': message
#             }
#         )
#
#     async def chat_message(self, event):
#         message = event['message']
#         await self.send(text_data=json.dumps({'message': message}))

# myproject/routing.py
# from django.urls import re_path
# from myapp import consumers
#
# websocket_urlpatterns = [
#     re_path(r'ws/chat/(?P<room_name>\w+)/$', consumers.ChatConsumer.as_asgi()),
# ]

# Root ASGI application in myproject/asgi.py
application = ProtocolTypeRouter({
    "http": django_asgi_app,
    "websocket": AllowedHostsOriginValidator(
        AuthMiddlewareStack(
            URLRouter(
                # myproject.routing.websocket_urlpatterns  # Uncomment and define your routing
                [
                    path("ws/echo/", (lambda scope: type('EchoConsumer', (object,), {'as_asgi': lambda: lambda scope, receive, send: (async def _(): await scope['accept'](), await scope['send']({'type': 'websocket.accept'}), async for msg in scope['receive'](): await scope['send']({'type': 'websocket.send', 'text': msg['text']})})())())(0).as_asgi())
                ]
            )
        )
    ),
})

view raw JSON →