channels-redis
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
- breaking Version 4.0.0 migrated from `aioredis` to `redis-py`. This changed the configuration for `hosts`; specifying hosts as tuples is no longer supported, and for dicts, only the `address` key is considered. Pass `password` inline in the URI.
- deprecated The `asgi_redis` package is an older name for channels-redis and is intended for Channels 1.x projects. Do not use it for Channels 2.x+ projects.
- gotcha The `RedisPubSubChannelLayer` is currently in Beta status. This means it may be subject to breaking changes as it matures. Use with caution in production environments where stability is paramount.
- breaking Channels-redis 4.x dropped support for older Python and Django versions. Python 3.8 support was dropped in 4.3.0, and Python 3.7 was dropped in 4.2.0. Minimum Django version is 4.2.2 for `channels-redis` 4.3.0.
- gotcha When using `async_to_sync()` with `redis-py 4.x`, ensure that Redis connections are manually closed when an event loop shuts down to avoid warnings or resource leaks. This was addressed for the pub-sub layer in 4.1.0 but remains a general consideration.
- gotcha When using sharding, passing multiple hosts to `CONFIG['hosts']` enables sharding. However, changing this host list can lead to loss of some sharded data. All servers talking to the same layer should have the same prefix and host list.
Install
-
pip install channels-redis
Imports
- RedisChannelLayer
from channels_redis.core import RedisChannelLayer
- RedisPubSubChannelLayer
from channels_redis.pubsub import RedisPubSubChannelLayer
Quickstart
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
)
),
})