Django Channels

repository·main·Indexed 27 days ago

https://github.com/django/channels

Extends Django to handle asynchronous protocols like WebSockets by introducing the ASGI interface. It utilizes the Daphne server for HTTP, HTTP2, and WebSocket traffic, and provides a channel layer specification for communication between application components, including support for Redis backends via channels_redis.

Tokens
24.2K
Snippets
68
Records
120
Agent score
89%

What's inside django-channels

  1. Overview of Django Channels

    main

    Django Channels augments Django to provide support for asynchronous protocols and tasks, including:

    • WebSockets
    • Long-poll HTTP
    • Task offloading
    • Other async support

    It uses familiar Django design patterns and a flexible framework that allows for customizing behaviors or writing support for custom protocols.

  2. Overview of Django Channels

    main
    Django Channels extends Django's capabilities beyond HTTP to handle WebSockets, chat protocols, IoT protocols, and more. It is built on the ASGI (Asynchronous Server Gateway Interface) specification and allows you to handle non-HTTP connections using either synchronous or asynchronous styles.
  3. Use Channels as a low-latency task queue

    main

    You can use channel layers to offload work to worker servers listening on fixed channel names, acting as a simple, low-latency task queue.

    Important Considerations:

    • Delivery Guarantees: This system provides at-most-once delivery. It does not support retries or return values. For tasks requiring high reliability or guarantees, use a dedicated task queue.
    • Compatibility: This feature does not work with the in-memory channel layer.
    • Setup: Implementation requires two parts: sending events to a fixed channel name and setting up consumers to receive them.
  4. Understand the ASGI application interface

    main

    ASGI (Asynchronous Server Gateway Interface) is the specification that Django Channels is built upon. An ASGI application is defined as a single asynchronous callable that accepts three arguments: scope (a dictionary defining connection properties), receive (an awaitable to receive events), and send (an awaitable to send events).

    Applications are instantiated once per scope (e.g., once per HTTP request or once per WebSocket connection). The scope dictionary always contains a type key which identifies the protocol being used.

    async def application(scope, receive, send):
        event = await receive()
        ...
        await send({"type": "websocket.send", ...})
  5. Understand Scopes and Events in Channels

    main

    Channels and ASGI operate using two core concepts: scopes and events.

    • Scope: A set of details about a single incoming connection (e.g., path, IP address, user ID). The scope persists for the lifetime of the connection. For HTTP, the scope lasts for a single request; for WebSockets, it lasts for the duration of the socket connection.
    • Events: User interactions that occur during the lifetime of a scope (e.g., an HTTP request, a WebSocket frame, or a chat message).

    Your Channels application is instantiated once per scope and is fed a stream of events to process.

  6. Explore community projects built on Django Channels

    main
    A variety of community-maintained projects extend Django Channels functionality, including specialized channel layers, protocols, and frameworks. Use these to add specific capabilities like Socket.IO support, SSE, or specific database backends for your channel layer.
  7. Understand the Django Channels ecosystem

    main

    Django Channels is composed of several distinct packages that work together:

    • Channels: The core Django integration layer.
    • Daphne: The HTTP and WebSocket termination server.
    • asgiref: The base ASGI library.
    • channels_redis: An optional Redis channel layer backend for managing communication between different parts of your application.
  8. Persist session changes in WebSocket consumers

    main

    Unlike HTTP consumers where sessions are saved automatically on non-500 responses, WebSocket consumers do not automatically save session changes.

    To persist changes made to the session during a WebSocket connection, you must manually call the save method:

    • For synchronous consumers: scope["session"].save()
    • For asynchronous consumers: scope["session"].asave()

    If you do not call these methods, changes will be available within the current consumer instance but will not be persisted to the session store for other connections or HTTP views.

  9. Quick Setup for development

    main

    To set up a local development environment for Channels, fork and clone the repository, then install the package in editable mode with the necessary test and Daphne dependencies.

    Note for zsh users: If you encounter a zsh: no matches found: .[tests] error, use noglob to prevent shell globbing issues.