Sobes.tech
Middle+

How is WebSocket handled in Django?

sobes.tech AI

Answer from AI

Working with WebSocket in Django is implemented using third-party libraries, the most popular of which is Django Channels. Django Channels extends Django's capabilities by adding support for asynchronous protocols such as WebSocket.

Main components of Django Channels:

  1. ASGI (Asynchronous Server Gateway Interface): A standard that replaces WSGI and provides an interface for asynchronous web servers.
  2. Channels: The core library providing tools for working with ASGI and WebSocket.
  3. Channel Layers: A component for message exchange between Django instances and other services. Necessary for broadcast messages and coordination between different worker processes.

Integration process:

  1. Installation:
    pip install channels daphne
    
  2. Configure settings.py:
    // settings.py
    
    INSTALLED_APPS = [
        // ... other apps
        'channels',
    ]
    
    ASGI_APPLICATION = 'your_project_name.asgi.application' // Path to ASGI application
    
  3. Create asgi.py:
    // your_project_name/asgi.py
    
    import os
    
    from channels.auth import AuthMiddlewareStack // For authentication
    from channels.routing import ProtocolTypeRouter, URLRouter // For routing
    from channels.security.websocket import AllowedHostsOriginValidator // For security
    from django.core.asgi import get_asgi_application // Replaces get_wsgi_application
    
    from your_app_name import routing // Routes for WebSocket
    
    os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project_name.settings")
    # Using get_asgi_application instead of get_wsgi_application
    django_asgi_app = get_asgi_application()
    
    application = ProtocolTypeRouter({
        "http": django_asgi_app, // HTTP requests are handled normally
        "websocket": AllowedHostsOriginValidator( // WebSocket routing
            AuthMiddlewareStack( // Optional, for authentication
                URLRouter(routing.websocket_urlpatterns) // WebSocket routes
            )
        ),
    })
    
  4. Create consumers.py: These are asynchronous functions or classes that handle WebSocket connections.
    // your_app_name/consumers.py
    
    import json
    
    from channels.generic.websocket import AsyncWebsocketConsumer // Asynchronous consumer
    
    class ChatConsumer(AsyncWebsocketConsumer):
        async def connect(self):
            // Handle connection setup
            self.room_name = self.scope["url_route"]["kwargs"]["room_name"]
            self.room_group_name = f"chat_{self.room_name}"
    
            // Join channel layer group
            await self.channel_layer.group_add(self.room_group_name, self.channel_name)
    
            await self.accept() // Accept connection
    
        async def disconnect(self, close_code):
            // Handle disconnection
            await self.channel_layer.group_discard(self.room_group_name, self.channel_name) // Leave group
    
        async def receive(self, text_data):
            // Handle incoming messages from client
            text_data_json = json.loads(text_data)
            message = text_data_json["message"]
    
            // Send message to channel layer group
            await self.channel_layer.group_send(
                self.room_group_name, {"type": "chat.message", "message": message}
            )
    
        async def chat_message(self, event):
            // Handle messages received from channel layer
            message = event["message"]
    
            // Send message back to client via WebSocket
            await self.send(text_data=json.dumps({"message": message}))
    
  5. Create routing.py: Define routes for WebSocket connections.
    // your_app_name/routing.py
    
    from django.urls import re_path // For regex in URL
    
    from . import consumers // Import consumers
    
    websocket_urlpatterns = [
        re_path(r"ws/chat/(?P<room_name>\w+)/$", consumers.ChatConsumer.as_asgi()), // WebSocket route
    ]
    
  6. ASGI server: Run the project using an ASGI server, such as Daphne or Uvicorn.
    daphne your_project_name.asgi:application
    

Thus, Django Channels allows handling WebSocket requests asynchronously, using Consumers for logic and Channel Layers for inter-process message exchange.