Overview

Django Channels 4.0, released on August 10, 2022, requires Django 4.0+ and improves testing tools for WebSocket and async consumers.

Main Features

Django 4.0+ compatibility

Channels 4.0 is aligned with Django 4.0+ and takes advantage of the framework's async improvements, including native async views.

python
from channels.generic.websocket import AsyncWebsocketConsumer
import json

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        self.room = self.scope['url_route']['kwargs']['room']
        await self.channel_layer.group_add(self.room, self.channel_name)
        await self.accept()

    async def receive(self, text_data):
        data = json.loads(text_data)
        await self.channel_layer.group_send(
            self.room, {'type': 'chat.message', 'message': data['message']}
        )

Improved testing

Testing tools are enriched with an improved WebsocketCommunicator for more reliable consumer testing.

python
from channels.testing import WebsocketCommunicator
import pytest

@pytest.mark.asyncio
async def test_chat_consumer():
    communicator = WebsocketCommunicator(
        ChatConsumer.as_asgi(), '/ws/chat/test/'
    )
    connected, _ = await communicator.connect()
    assert connected
    await communicator.disconnect()

Sources