Django Channels and WebSockets
last modified November 22, 2026 Python 3.15
HTTP follows a strict pattern: the client sends a request and the server answers it. The server cannot send anything on its own, so a page that must show new data, such as a chat, a live dashboard, or a notification, has to ask again and again. A WebSocket is a long-lived, two-way connection: it starts as an HTTP request, and after the handshake both sides can send messages at any time until one of them closes the connection. Django itself handles only HTTP. The Channels project adds WebSockets on top of Django's ASGI support; it routes connections to consumers, classes that react to the events of a connection, and connects the consumers with a channel layer, so that a message from one client can reach the others. In this article we build a small chat with rooms, logged-in users, and a message history, and test it. The examples use Django 6.1, Channels 4.3, Daphne 4.2, channels-redis 4.3, and Python 3.15.
The example project
The project is created with uv; the steps are explained in Django introduction.
The commands below create a project directory, install Django, Channels with the Daphne server, and the
websockets library, which we use to write WebSocket clients in Python. Then they generate the project with the
configuration package config, start the app chat, and create the folder
demos for demo scripts. The quotes around channels[daphne] keep the shell from
interpreting the brackets.
$ mkdir chatsite $ cd chatsite $ uv init --bare $ uv add django 'channels[daphne]' websockets $ uv run django-admin startproject config . $ uv run python manage.py startapp chat $ mkdir demos
The trailing dot in startproject config . creates manage.py and the
config package in the current directory. We add daphne and the new app to
INSTALLED_APPS in config/settings.py; the other entries are generated by
startproject. The daphne entry must come first: it replaces the
runserver command with a version that runs the ASGI server Daphne, and an app listed earlier wins
when two apps provide a command of the same name.
INSTALLED_APPS = [
'daphne',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'chat',
]
The listings in this article are of two kinds. A listing with a solid blue border and the label Project
file is a file of the application: models, views, templates, tests, and settings. A listing with a dashed
amber border and the label Demo script is a small helper in the demos folder; it sets up
Django, runs a few lines of code, and prints the results, so that we can watch the behaviour. Demo scripts are
not part of the application; we run one from the project directory with uv run python -m
demos.name.
Some demo scripts in this article are WebSocket clients. They talk to the running server over the network, like a browser would, so most of them do not need to set up Django.
Daphne and the ASGI application
A WebSocket connection stays open for minutes or hours, which does not fit WSGI, where a worker handles one
request and returns. Channels runs on ASGI, the asynchronous server interface, so the development server must
be an ASGI server too. The setting ASGI_APPLICATION tells Daphne's runserver which
application to load. We add it at the end of config/settings.py.
ASGI_APPLICATION = 'config.asgi.application'
The value points to the variable application in config/asgi.py, which
startproject generated. We apply the default migrations with uv run python manage.py
migrate and start the server. The banner names Daphne instead of the usual WSGI server, and an ordinary
page such as the admin login is still served; it was requested with curl from another terminal.
$ uv run python manage.py runserver Performing system checks... System check identified no issues (0 silenced). November 22, 2026 - 19:25:29 Django version 6.1.3, using settings 'config.settings' Starting ASGI/Daphne version 4.2.3 development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. HTTP GET /admin/login/ 200 [0.04, 127.0.0.1:44904]
An echo consumer
A consumer is to a WebSocket what a view is to an HTTP request. WebsocketConsumer calls its
methods for the events of one connection: connect() when a client asks to open the connection,
receive() for every message, and disconnect() when the connection is closed. Each
connection gets its own consumer instance. The first consumer accepts every connection and sends each text
message back with a prefix.
from channels.generic.websocket import WebsocketConsumer
class EchoConsumer(WebsocketConsumer):
def connect(self):
self.accept()
def receive(self, text_data=None, bytes_data=None):
self.send(text_data=f'echo: {text_data}')
Calling accept() completes the handshake; a consumer that does not accept the connection rejects
it. A message is either text (text_data) or binary data (bytes_data), and
send() takes the same two arguments.
Routing WebSocket connections
WebSocket URLs are not part of the ordinary URLconf. We keep them in the module chat/routing.py;
the list uses the same path() function, and as_asgi() turns the consumer class into
an ASGI application, similar to as_view() for class-based views.
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/echo/', consumers.EchoConsumer.as_asgi()),
]
In config/asgi.py, ProtocolTypeRouter sends HTTP requests to Django's ordinary ASGI
handler and WebSocket connections to URLRouter, which picks the consumer by the path. The handler
is created with get_asgi_application() before the other imports. The call sets up Django and
loads the apps; the consumers will import models, which is not possible before that. The noqa
comments silence the linter warning about imports that are not at the top of the file.
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django_asgi_app = get_asgi_application()
from channels.routing import ProtocolTypeRouter, URLRouter # noqa: E402
from chat.routing import websocket_urlpatterns # noqa: E402
application = ProtocolTypeRouter({
'http': django_asgi_app,
'websocket': URLRouter(websocket_urlpatterns),
})
The development server needs a restart after these changes, so that it loads the new application.
$ uv run python manage.py runserver
A WebSocket client
A browser is one possible client; for the first experiments a Python script is simpler. The websockets library
has a synchronous client: connect() performs the handshake and returns a connection with
send() and recv() methods. The script sends each command line argument and prints
the reply.
import sys
from websockets.sync.client import connect
with connect('ws://localhost:8000/ws/echo/') as ws:
for text in sys.argv[1:]:
ws.send(text)
print(ws.recv())
The script is a pure client and does not set up Django. The first block below is the output of the script, the
second shows what the server printed in its terminal: the handshake, the accepted connection, and the
disconnection when the with block closed it.
$ uv run python -m demos.echo 'Hello there!' 'How are you?' echo: Hello there! echo: How are you?
WebSocket HANDSHAKING /ws/echo/ [127.0.0.1:port] WebSocket CONNECT /ws/echo/ [127.0.0.1:port] WebSocket DISCONNECT /ws/echo/ [127.0.0.1:port]
A path without a route
URLRouter has no 404 page. A connection to a path that matches no route raises an exception
inside the application, the server answers the handshake with the status 500, and the client refuses to
continue. We try it with a one-line client; the first block shows the last line of the client's traceback, the
second the server log without its traceback.
$ uv run python -c "from websockets.sync.client import connect; connect('ws://localhost:8000/ws/nothing/')" 2>&1 | tail -n 1
websockets.exceptions.InvalidStatus: server rejected WebSocket connection: HTTP 500
WebSocket HANDSHAKING /ws/nothing/ [127.0.0.1:port] Exception inside application: No route found for path 'ws/nothing/'. ValueError: No route found for path 'ws/nothing/'. WebSocket DISCONNECT /ws/nothing/ [127.0.0.1:port]
Closing the connection
A consumer instance lives as long as its connection, so it can keep state in attributes. The new version sends
a greeting right after accepting the connection, counts the echoed messages, and closes the connection when
the client sends bye. The close code 4000 is our own; the codes 4000–4999 are reserved for
applications. The method disconnect() receives the code.
from channels.generic.websocket import WebsocketConsumer
class EchoConsumer(WebsocketConsumer):
def connect(self):
self.count = 0
self.accept()
self.send(text_data='Welcome! Send bye to leave.')
def receive(self, text_data=None, bytes_data=None):
if text_data == 'bye':
self.send(text_data=f'Goodbye after {self.count} messages.')
self.close(code=4000)
return
self.count += 1
self.send(text_data=f'echo {self.count}: {text_data}')
def disconnect(self, code):
print(f'echo consumer disconnected with code {code}')
The client reads the greeting and sends four messages. The bye message ends the conversation;
sending to or receiving from a closed connection raises ConnectionClosed, whose rcvd
attribute holds the close frame received from the server.
from websockets.exceptions import ConnectionClosed
from websockets.sync.client import connect
with connect('ws://localhost:8000/ws/echo/') as ws:
print(ws.recv())
for text in ['first', 'second', 'bye', 'third']:
try:
ws.send(text)
print(ws.recv())
except ConnectionClosed as e:
print('closed with code', e.rcvd.code)
break
The third message never gets a reply. The server log ends with the line printed by disconnect().
Channels' close() also accepts a reason text, but Daphne did not pass it to the
client in our test; the code is what a client can rely on.
$ uv run python -m demos.echo_close Welcome! Send bye to leave. echo 1: first echo 2: second Goodbye after 2 messages. closed with code 4000
WebSocket HANDSHAKING /ws/echo/ [127.0.0.1:port] WebSocket CONNECT /ws/echo/ [127.0.0.1:port] WebSocket DISCONNECT /ws/echo/ [127.0.0.1:port] echo consumer disconnected with code 4000
Rooms and groups
An echo talks to one client. In a chat, a message from one user must reach everybody in the same room, which
means reaching other consumer instances. Consumers cannot call each other; they exchange messages through the
channel layer. Every consumer has a unique channel_name, and a group is a named set of
channels: group_add() adds the consumer's channel to a group and group_send()
delivers a message to every channel in it.
from channels.generic.websocket import AsyncJsonWebsocketConsumer, WebsocketConsumer
class EchoConsumer(WebsocketConsumer):
def connect(self):
self.count = 0
self.accept()
self.send(text_data='Welcome! Send bye to leave.')
def receive(self, text_data=None, bytes_data=None):
if text_data == 'bye':
self.send(text_data=f'Goodbye after {self.count} messages.')
self.close(code=4000)
return
self.count += 1
self.send(text_data=f'echo {self.count}: {text_data}')
def disconnect(self, code):
print(f'echo consumer disconnected with code {code}')
class ChatConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
self.room = self.scope['url_route']['kwargs']['room']
self.group = f'chat_{self.room}'
await self.channel_layer.group_add(self.group, self.channel_name)
await self.accept()
async def disconnect(self, code):
await self.channel_layer.group_discard(self.group, self.channel_name)
async def receive_json(self, content, **kwargs):
await self.channel_layer.group_send(self.group, {
'type': 'chat.message',
'user': content['user'],
'text': content['text'],
})
async def chat_message(self, event):
await self.send_json({'user': event['user'], 'text': event['text']})
ChatConsumer is asynchronous: its methods are coroutines and the channel layer's methods are
awaited directly. A synchronous consumer would have to wrap every channel layer call in
async_to_sync(). AsyncJsonWebsocketConsumer also decodes incoming text as JSON and
passes it to receive_json(), and send_json() encodes the reply. The room name comes
from the URL, like keyword arguments of a view, through scope['url_route']. The scope is
the connection's equivalent of a request object: it holds the path, the headers, and, later, the user.
The message passed to group_send() is a dictionary whose type key names the handler:
Channels replaces the dot with an underscore, so chat.message calls the method
chat_message() of every consumer in the group, including the sender's. That method sends the
message to its own client. For now, the client says who it is in the user key. In
disconnect(), the consumer leaves the group.
The route takes the room as a slug, so /ws/chat/lobby/ and /ws/chat/python/ are two
rooms.
from django.urls import path
from . import consumers
websocket_urlpatterns = [
path('ws/echo/', consumers.EchoConsumer.as_asgi()),
path('ws/chat/<slug:room>/', consumers.ChatConsumer.as_asgi()),
]
The demo opens three connections: alice and bob join the lobby, carol the python room. Alice sends a message, and the script then reads one message from each connection with a timeout of one second.
import json
from websockets.sync.client import connect
URL = 'ws://localhost:8000/ws/chat/{}/'
with (connect(URL.format('lobby')) as alice,
connect(URL.format('lobby')) as bob,
connect(URL.format('python')) as carol):
alice.send(json.dumps({'user': 'alice', 'text': 'Hi, everyone!'}))
for name, ws in [('alice', alice), ('bob', bob), ('carol', carol)]:
try:
print(f'{name:6}', ws.recv(timeout=1))
except TimeoutError:
print(f'{name:6}', 'nothing')
After a restart of the server, the script fails. Channels has no channel layer unless one is configured,
self.channel_layer is None, and the exception in connect() turns the
handshake into a 500 response. The first block shows the last line from the client, the second the server log
without the traceback.
$ uv run python -m demos.rooms 2>&1 | tail -n 1 websockets.exceptions.InvalidStatus: server rejected WebSocket connection: HTTP 500
WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:port] Exception inside application: 'NoneType' object has no attribute 'group_add' AttributeError: 'NoneType' object has no attribute 'group_add' WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:port]
The in-memory channel layer
The setting CHANNEL_LAYERS configures the layer, much like CACHES configures the
cache. The in-memory layer keeps groups and messages in the memory of the server process; it needs no other
software and is fine for development.
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels.layers.InMemoryChannelLayer',
},
}
After a restart, the message reaches both connections in the lobby, the sender's too, and nothing reaches the other room.
$ uv run python -m demos.rooms
alice {"user": "alice", "text": "Hi, everyone!"}
bob {"user": "alice", "text": "Hi, everyone!"}
carol nothing
Users in a consumer
Letting clients name themselves is not good enough. The browser already sends the session cookie with the
WebSocket handshake, because the handshake is an HTTP request; Channels' middleware can read it.
AuthMiddlewareStack loads the session from the cookie and puts the user into
scope['user'], the same way Django's authentication middleware sets request.user.
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django_asgi_app = get_asgi_application()
from channels.auth import AuthMiddlewareStack # noqa: E402
from channels.routing import ProtocolTypeRouter, URLRouter # noqa: E402
from chat.routing import websocket_urlpatterns # noqa: E402
application = ProtocolTypeRouter({
'http': django_asgi_app,
'websocket': AuthMiddlewareStack(URLRouter(websocket_urlpatterns)),
})
The consumer now refuses anonymous users: calling close() in connect() before
accept() rejects the handshake. Daphne calls disconnect() for a rejected connection
as well, so the method must not touch the group, which was never set. The message carries the user name from
the session, and the client's user key is no longer needed. The rest of
chat/consumers.py is unchanged.
class ChatConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
self.user = self.scope['user']
if not self.user.is_authenticated:
await self.close()
return
self.room = self.scope['url_route']['kwargs']['room']
self.group = f'chat_{self.room}'
await self.channel_layer.group_add(self.group, self.channel_name)
await self.accept()
async def disconnect(self, code):
if not self.user.is_authenticated:
return
await self.channel_layer.group_discard(self.group, self.channel_name)
async def receive_json(self, content, **kwargs):
await self.channel_layer.group_send(self.group, {
'type': 'chat.message',
'user': self.user.username,
'text': content['text'],
})
async def chat_message(self, event):
await self.send_json({'user': event['user'], 'text': event['text']})
The users come from a seed script. It deletes and recreates alice and bob, so it can be run again.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
from django.contrib.auth.models import User
for name in ['alice', 'bob']:
User.objects.filter(username=name).delete()
User.objects.create_user(name, password=f's3cret-{name}')
print(list(User.objects.values_list('username', flat=True)))
The script prints the user names.
$ uv run python -m demos.seed ['alice', 'bob']
Logging in from a script
A script has no browser that would keep the session cookie, so the helper module wsclient.py gets
one from Django: the test client's login() creates a session in the project's database and stores
its key in the cookie sessionid. This module sets up Django for that. The function
chat() connects to a room with optional Cookie and Origin headers, and
attempt() sends one message and prints the reply, or the status of a rejected handshake.
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
import json
from django.test import Client
from websockets.exceptions import InvalidStatus
from websockets.sync.client import connect
def login(username):
client = Client()
client.login(username=username, password=f's3cret-{username}')
return f'sessionid={client.cookies["sessionid"].value}'
def chat(room, cookie=None, origin=None):
headers = {'Cookie': cookie} if cookie else {}
return connect(f'ws://localhost:8000/ws/chat/{room}/', origin=origin,
additional_headers=headers)
def attempt(label, room='lobby', cookie=None, origin=None):
try:
with chat(room, cookie, origin) as ws:
ws.send(json.dumps({'text': 'Is anybody here?'}))
print(f'{label}: {ws.recv(timeout=1)}')
except InvalidStatus as e:
print(f'{label}: rejected with HTTP {e.response.status_code}')
The demo tries the lobby once without a cookie and once as alice.
from demos.wsclient import attempt, login
attempt('anonymous')
attempt('alice', cookie=login('alice'))
The anonymous attempt is rejected with 403, and alice's message comes back with her name. The server log shows
the rejection as REJECT.
$ uv run python -m demos.auth
anonymous: rejected with HTTP 403
alice: {"user": "alice", "text": "Is anybody here?"}
WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:port] WebSocket REJECT /ws/chat/lobby/ [127.0.0.1:port] WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:port] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:port] WebSocket CONNECT /ws/chat/lobby/ [127.0.0.1:port] WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:port]
Checking the origin
Django's CSRF protection covers forms, not WebSockets. A page on another site could open a WebSocket to our
server, and if the browser attached the user's session cookie, the page could chat in the user's name.
Browsers send the address of the page that opened a WebSocket in the Origin header.
AllowedHostsOriginValidator accepts only origins whose host is in ALLOWED_HOSTS;
while DEBUG is on and the list is empty, it allows localhost,
127.0.0.1, and [::1].
import os
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django_asgi_app = get_asgi_application()
from channels.auth import AuthMiddlewareStack # noqa: E402
from channels.routing import ProtocolTypeRouter, URLRouter # noqa: E402
from channels.security.websocket import AllowedHostsOriginValidator # noqa: E402
from chat.routing import websocket_urlpatterns # noqa: E402
application = ProtocolTypeRouter({
'http': django_asgi_app,
'websocket': AllowedHostsOriginValidator(
AuthMiddlewareStack(URLRouter(websocket_urlpatterns))
),
})
The demo connects as alice three times: without an Origin header, from a foreign site, and from
the server's own address.
from demos.wsclient import attempt, login
cookie = login('alice')
attempt('no origin', cookie=cookie)
attempt('evil.example', cookie=cookie, origin='https://evil.example')
attempt('localhost', cookie=cookie, origin='http://localhost:8000')
Only the last attempt gets through. A missing Origin header is rejected as well, unless
ALLOWED_HOSTS contains '*'; from now on our script clients must send one.
$ uv run python -m demos.origins
no origin: rejected with HTTP 403
evil.example: rejected with HTTP 403
localhost: {"user": "alice", "text": "Is anybody here?"}
A chat page
The browser client is an ordinary Django page. The view requires a logged-in user and renders the room template.
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
@login_required
def room(request, room):
return render(request, 'chat/room.html', {'room': room})
The app's URLconf maps a room name to the view.
from django.urls import path
from . import views
urlpatterns = [
path('<slug:room>/', views.room, name='room'),
]
The project includes the login and logout views of django.contrib.auth under
/accounts/ and the chat pages under /chat/. The setting LOGIN_URL
defaults to /accounts/login/, so login_required finds the login page without
configuration.
from django.urls import include, path
urlpatterns = [
path('accounts/', include('django.contrib.auth.urls')),
path('chat/', include('chat.urls')),
]
The login view renders registration/login.html. We put the template into the app's
templates folder, where the app template loader finds it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Log in</title>
</head>
<body>
<h1>Log in</h1>
<form method="post">
{% csrf_token %}
{{ form.as_p }}
<button>Log in</button>
</form>
</body>
</html>
The room template contains a list for the messages and a form. The json_script filter passes the
room name to JavaScript safely. The script opens a WebSocket to the same host, with wss on an
HTTPS page; the browser adds the session cookie and the Origin header. Every incoming message
becomes a list item; textContent inserts the text as text, so a message with HTML tags cannot
inject markup. Submitting the form sends the text as JSON instead of loading a new page.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Room {{ room }}</title>
<style>
body { font-family: sans-serif; max-width: 40em; margin: 2em auto; }
#log { list-style: none; padding: 0.5em; border: 1px solid #ccc; height: 14em; overflow-y: auto; }
#status { color: #777; }
</style>
</head>
<body>
<h1>Room {{ room }}</h1>
<p>Logged in as {{ user.username }} <span id="status">connecting...</span></p>
<ul id="log"></ul>
<form id="form">
<input id="text" autocomplete="off" autofocus required>
<button>Send</button>
</form>
{{ room|json_script:"room-name" }}
<script>
const room = JSON.parse(document.getElementById('room-name').textContent);
const scheme = location.protocol === 'https:' ? 'wss' : 'ws';
const socket = new WebSocket(`${scheme}://${location.host}/ws/chat/${room}/`);
const status = document.getElementById('status');
const log = document.getElementById('log');
const input = document.getElementById('text');
socket.onopen = () => status.textContent = '(connected)';
socket.onclose = () => status.textContent = '(disconnected)';
socket.onmessage = (e) => {
const data = JSON.parse(e.data);
const item = document.createElement('li');
item.textContent = `${data.user}: ${data.text}`;
log.append(item);
log.scrollTop = log.scrollHeight;
};
document.getElementById('form').onsubmit = (e) => {
e.preventDefault();
socket.send(JSON.stringify({text: input.value}));
input.value = '';
};
</script>
</body>
</html>
An anonymous request for a room is redirected to the login page, with the room in the next
parameter.
$ curl -s -o /dev/null -w '%{http_code} %{redirect_url}\n' localhost:8000/chat/lobby/
302 http://localhost:8000/accounts/login/?next=/chat/lobby/
Chatting in the browser
We logged in as alice in one browser window and as bob in a private window, which has its own cookies, opened the lobby in both, and exchanged a few messages. Each message appears in both windows as soon as it is sent.
The server log shows both users logging in and loading the page, followed by one WebSocket connection per window. While the users chat, nothing more is logged: the messages travel over the open connections. The two disconnections at the end were logged when the windows were closed.
HTTP GET /chat/lobby/ 302 [0.01, 127.0.0.1:port] HTTP GET /accounts/login/?next=/chat/lobby/ 200 [0.01, 127.0.0.1:port] Not Found: /favicon.ico HTTP GET /favicon.ico 404 [0.01, 127.0.0.1:port] HTTP POST /accounts/login/?next=/chat/lobby/ 302 [0.27, 127.0.0.1:port] HTTP GET /chat/lobby/ 200 [0.00, 127.0.0.1:port] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:port] WebSocket CONNECT /ws/chat/lobby/ [127.0.0.1:port] HTTP GET /accounts/login/?next=/chat/lobby/ 200 [0.00, 127.0.0.1:port] HTTP POST /accounts/login/?next=/chat/lobby/ 302 [0.29, 127.0.0.1:port] HTTP GET /chat/lobby/ 200 [0.00, 127.0.0.1:port] WebSocket HANDSHAKING /ws/chat/lobby/ [127.0.0.1:port] WebSocket CONNECT /ws/chat/lobby/ [127.0.0.1:port] WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:port] WebSocket DISCONNECT /ws/chat/lobby/ [127.0.0.1:port]
Saving messages
Messages that are sent while a user is not connected are lost. To show a newcomer what was said, the chat stores the messages in the database.
from django.conf import settings
from django.db import models
class Message(models.Model):
room = models.SlugField()
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
text = models.CharField(max_length=500)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['created']
def __str__(self):
return f'{self.user}: {self.text}'
We create the table.
$ uv run python manage.py makemigrations chat
Migrations for 'chat':
chat/migrations/0001_initial.py
+ Create model Message
$ uv run python manage.py migrate chat
Operations to perform:
Apply all migrations: chat
Running migrations:
Applying chat.0001_initial... OK
Sending the history
The ORM is synchronous, and calling it directly from an async consumer raises
SynchronousOnlyOperation. Channels' decorator database_sync_to_async runs a method
in a worker thread and also closes database connections that are too old, as Django does at the end of a
request. save() stores each message before it is broadcast; history() loads the last
ten messages of the room, newest first, and reverses them, so that the client gets them in the original order
right after connecting. The method builds plain dictionaries in the thread; a lazy QuerySet returned to async
code would run its query there. This is the full and final chat/consumers.py.
from channels.db import database_sync_to_async
from channels.generic.websocket import AsyncJsonWebsocketConsumer, WebsocketConsumer
from .models import Message
class EchoConsumer(WebsocketConsumer):
def connect(self):
self.count = 0
self.accept()
self.send(text_data='Welcome! Send bye to leave.')
def receive(self, text_data=None, bytes_data=None):
if text_data == 'bye':
self.send(text_data=f'Goodbye after {self.count} messages.')
self.close(code=4000)
return
self.count += 1
self.send(text_data=f'echo {self.count}: {text_data}')
def disconnect(self, code):
print(f'echo consumer disconnected with code {code}')
class ChatConsumer(AsyncJsonWebsocketConsumer):
async def connect(self):
self.user = self.scope['user']
if not self.user.is_authenticated:
await self.close()
return
self.room = self.scope['url_route']['kwargs']['room']
self.group = f'chat_{self.room}'
await self.channel_layer.group_add(self.group, self.channel_name)
await self.accept()
for message in await self.history():
await self.send_json(message)
async def disconnect(self, code):
if not self.user.is_authenticated:
return
await self.channel_layer.group_discard(self.group, self.channel_name)
async def receive_json(self, content, **kwargs):
await self.save(content['text'])
await self.channel_layer.group_send(self.group, {
'type': 'chat.message',
'user': self.user.username,
'text': content['text'],
})
async def chat_message(self, event):
await self.send_json({'user': event['user'], 'text': event['text']})
@database_sync_to_async
def history(self):
messages = (Message.objects.filter(room=self.room)
.select_related('user').order_by('-created')[:10])
return [{'user': m.user.username, 'text': m.text} for m in reversed(messages)]
@database_sync_to_async
def save(self, text):
Message.objects.create(room=self.room, user=self.user, text=text)
In the demo, alice sends two messages to the lobby and leaves; afterwards bob connects and reads whatever
arrives within a second. Both connections send the Origin header. At the end, the script counts
the saved messages with the ORM.
import json
from demos.wsclient import chat, login
ORIGIN = 'http://localhost:8000'
with chat('lobby', login('alice'), ORIGIN) as alice:
for text in ['Is anybody here?', 'I will be back later.']:
alice.send(json.dumps({'text': text}))
alice.recv()
with chat('lobby', login('bob'), ORIGIN) as bob:
while True:
try:
print(bob.recv(timeout=1))
except TimeoutError:
break
from chat.models import Message # noqa: E402
print(Message.objects.filter(room='lobby').count(), 'messages in lobby')
We deleted the messages from the earlier experiments before running the demo. Bob receives alice's messages although he was not connected when she sent them.
$ uv run python -m demos.history
{"user": "alice", "text": "Is anybody here?"}
{"user": "alice", "text": "I will be back later."}
2 messages in lobby
Sending from outside a consumer
Not every message comes from a client. A view, a management command, or a background task may need to notify
the users in a room. Any code can send to a group with get_channel_layer(); in synchronous code
the coroutine is wrapped in async_to_sync(). The script below sends a system announcement to a
room. The message has the same type as the chat messages, so the consumers handle it with
chat_message().
import os
import django
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings')
django.setup()
import sys
from asgiref.sync import async_to_sync
from channels.layers import get_channel_layer
layer = get_channel_layer()
async_to_sync(layer.group_send)(f'chat_{sys.argv[1]}', {
'type': 'chat.message',
'user': 'system',
'text': sys.argv[2],
})
print('sent with', type(layer).__name__)
To see whether the announcement arrives, the second script joins a room as bob and prints the messages it receives until it waits longer than the given number of seconds.
import sys
from demos.wsclient import chat, login
room, seconds = sys.argv[1], float(sys.argv[2])
with chat(room, login('bob'), 'http://localhost:8000') as ws:
print('listening')
while True:
try:
print('received', ws.recv(timeout=seconds))
except TimeoutError:
print('done')
break
We start the listener in the background, send the announcement, and wait for the listener to finish. The messages table was emptied first, so the listener gets no history. The announcement is sent without an error but never arrives: the in-memory layer lives inside one process, and the announcement went to a separate, empty layer in the process of the script.
$ uv run python -m demos.listen lobby 2 & $ sleep 1.5 listening $ uv run python -m demos.announce lobby 'Server restart at 22:00' sent with InMemoryChannelLayer $ wait done
A Redis channel layer
A layer shared between processes needs a server. channels-redis stores groups and messages in Redis, so the development server, scripts, workers, and the several server processes of a production deployment all see the same groups. We run Redis 8 in Docker on port 6380, which leaves the default port free for a Redis server installed on the machine, and add the package.
$ docker run -d --name chat-redis -p 6380:6379 redis:8 $ uv add channels-redis | tail -n 3 Installed 2 packages in 2ms + channels-redis==4.3.0 + redis==8.1.0
Configuring the Redis layer
The new CHANNEL_LAYERS replaces the in-memory one at the end of config/settings.py.
hosts lists the Redis servers.
CHANNEL_LAYERS = {
'default': {
'BACKEND': 'channels_redis.core.RedisChannelLayer',
'CONFIG': {
'hosts': [('127.0.0.1', 6380)],
},
},
}
After a restart of the server, the same commands deliver the announcement to bob's connection.
$ uv run python -m demos.listen lobby 2 &
$ sleep 1.5
listening
$ uv run python -m demos.announce lobby 'Server restart at 22:00'
sent with RedisChannelLayer
received {"user": "system", "text": "Server restart at 22:00"}
$ wait
done
Testing consumers
Channels' WebsocketCommunicator runs an ASGI application in the test's event loop and plays the
client: connect() returns whether the handshake was accepted, send_json_to() sends a
message, receive_json_from() waits for one, and receive_nothing() checks that
nothing arrives. The tests use the routes without the middleware and put the user into the scope directly,
which saves logging in. The class switches the channel layer to the in-memory one with
override_settings, so the tests need no Redis.
from channels.routing import URLRouter
from channels.testing import WebsocketCommunicator
from django.contrib.auth.models import AnonymousUser, User
from django.test import TestCase, override_settings
from .models import Message
from .routing import websocket_urlpatterns
application = URLRouter(websocket_urlpatterns)
IN_MEMORY = {'default': {'BACKEND': 'channels.layers.InMemoryChannelLayer'}}
@override_settings(CHANNEL_LAYERS=IN_MEMORY)
class ChatConsumerTests(TestCase):
@classmethod
def setUpTestData(cls):
cls.alice = User.objects.create_user('alice')
cls.bob = User.objects.create_user('bob')
async def join(self, user, room='lobby'):
communicator = WebsocketCommunicator(application, f'/ws/chat/{room}/')
communicator.scope['user'] = user
connected, _ = await communicator.connect()
self.assertTrue(connected)
return communicator
async def test_anonymous_user_is_rejected(self):
communicator = WebsocketCommunicator(application, '/ws/chat/lobby/')
communicator.scope['user'] = AnonymousUser()
connected, _ = await communicator.connect()
self.assertFalse(connected)
async def test_message_goes_to_the_room(self):
alice = await self.join(self.alice)
bob = await self.join(self.bob)
carol = await self.join(self.bob, room='python')
await alice.send_json_to({'text': 'Hi, everyone!'})
expected = {'user': 'alice', 'text': 'Hi, everyone!'}
self.assertEqual(await alice.receive_json_from(), expected)
self.assertEqual(await bob.receive_json_from(), expected)
self.assertTrue(await carol.receive_nothing())
for communicator in (alice, bob, carol):
await communicator.disconnect()
async def test_history_is_sent_on_connect(self):
await Message.objects.acreate(room='lobby', user=self.alice, text='Earlier')
bob = await self.join(self.bob)
self.assertEqual(await bob.receive_json_from(), {'user': 'alice', 'text': 'Earlier'})
await bob.disconnect()
The test methods are coroutines; Django's TestCase runs them in an event loop. The data from
setUpTestData() and the message created with the async ORM method acreate() are
visible to the consumer's database_sync_to_async methods, and everything is rolled back after
each test. Each test disconnects its communicators, so that the consumers finish cleanly. We stopped the Redis
container before running the tests.
$ uv run python manage.py test chat -v 2 Found 3 test(s). test_anonymous_user_is_rejected (chat.tests.ChatConsumerTests.test_anonymous_user_is_rejected) ... ok test_history_is_sent_on_connect (chat.tests.ChatConsumerTests.test_history_is_sent_on_connect) ... ok test_message_goes_to_the_room (chat.tests.ChatConsumerTests.test_message_goes_to_the_room) ... ok ---------------------------------------------------------------------- Ran 3 tests in 0.113s OK
Source
In this article we have served a Django project with Daphne, written synchronous and asynchronous WebSocket
consumers, routed connections with ProtocolTypeRouter and URLRouter, broadcast
messages to rooms with groups, authenticated users from the session, checked the origin, built a chat page,
stored the messages with the ORM, sent messages from outside a consumer over a Redis channel layer, and tested
the consumer. Related articles are Async Django, Django sessions and cookies, Django
authentication, Celery with Django, and Django
testing.
Author
List all Django tutorials.