0
0
Djangoframework~5 mins

Channels for WebSocket support in Django

Choose your learning style9 modes available
Introduction

Channels let Django handle real-time communication like chat or live updates. They add WebSocket support to Django, which normally works only with regular web pages.

You want to build a chat app where messages appear instantly.
You need live notifications on your website without refreshing the page.
You want to show real-time data like stock prices or sports scores.
You want to handle background tasks that send updates to users.
You want to support multiplayer games or collaborative tools in your app.
Syntax
Django
from channels.generic.websocket import AsyncWebsocketConsumer
import json

class ChatConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()

    async def disconnect(self, close_code):
        pass

    async def receive(self, text_data):
        data = json.loads(text_data)
        message = data['message']

        await self.send(text_data=json.dumps({
            'message': message
        }))

Use AsyncWebsocketConsumer to create WebSocket handlers with async code.

Override connect, disconnect, and receive methods to control connection and messages.

Examples
This example shows how to accept a WebSocket connection.
Django
class MyConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()
This echoes back any message received from the client.
Django
async def receive(self, text_data):
    await self.send(text_data=text_data)
This runs code when the WebSocket disconnects.
Django
async def disconnect(self, close_code):
    print('Disconnected')
Sample Program

This simple WebSocket consumer accepts connections and echoes back any message it receives in JSON format.

Django
from channels.generic.websocket import AsyncWebsocketConsumer
import json

class EchoConsumer(AsyncWebsocketConsumer):
    async def connect(self):
        await self.accept()

    async def disconnect(self, close_code):
        pass

    async def receive(self, text_data):
        # Receive message from WebSocket
        data = json.loads(text_data)
        message = data.get('message', '')

        # Send message back to WebSocket
        await self.send(text_data=json.dumps({
            'message': message
        }))
OutputSuccess
Important Notes

Remember to add Channels to your Django project settings and routing.

WebSocket connections stay open, unlike normal HTTP requests.

Use async methods for better performance with many connections.

Summary

Channels add WebSocket support to Django for real-time features.

Create consumers by subclassing AsyncWebsocketConsumer and overriding key methods.

Use JSON to send and receive messages easily over WebSocket.