channels-redis

4.3.0 · active · verified Thu Apr 09

channels-redis (version 4.3.0) is a Redis-backed ASGI channel layer implementation for Django Channels. It enables real-time communication, supporting WebSockets, chat protocols, and other asynchronous features in Django applications. It is the official Django-maintained channel layer recommended for production use and is actively maintained with regular updates.

Warnings

Install

Imports

Quickstart

To use channels-redis, you typically configure your `CHANNEL_LAYERS` setting in `settings.py` and set up your ASGI application in `asgi.py`. Ensure a Redis server (version 5.0 or higher) is running. This example shows a basic setup for the default `RedisChannelLayer` and a structure for `asgi.py`. You would further define `websocket_urlpatterns` in your app's `routing.py` and include it in the `URLRouter`.

import os
from django.core.asgi import get_asgi_application
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.conf import settings

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "your_project.settings")

# In your settings.py (e.g., your_project/settings.py):
# CHANNEL_LAYERS = {
#     "default": {
#         "BACKEND": "channels_redis.core.RedisChannelLayer",
#         "CONFIG": {
#             "hosts": [os.environ.get('REDIS_URL', 'redis://localhost:6379')],
#         },
#     },
# }

# Example routing (your_project/routing.py)
# from django.urls import re_path
# from chat.consumers import ChatConsumer
# websocket_urlpatterns = [
#     re_path(r'ws/chat/(?P<room_name>\w+)/$', ChatConsumer.as_asgi()),
# ]

application = ProtocolTypeRouter({
    "http": get_asgi_application(),
    "websocket": AuthMiddlewareStack(
        URLRouter(
            # Replace with your app's websocket_urlpatterns
            # Example: chat.routing.websocket_urlpatterns
            [] # Placeholder for actual URLRouter patterns
        )
    ),
})

view raw JSON →