ASGI Ref
ASGI specification and utilities, version 3.11.1, released on a regular cadence. Provides ASGI specs, helper code, and adapters for Python applications.
Common errors
-
ERROR: Invalid requirement: 'asgiref 3.5.2'
cause The requirements.txt file contains an invalid format with extra spaces between the package name and version number.fixEnsure there are no extra spaces in the requirements.txt file; use 'asgiref==3.5.2' instead of 'asgiref 3.5.2'. -
ModuleNotFoundError: No module named 'asgiref.base_layer'
cause The 'asgi_redis' package depends on an outdated version of 'asgiref' that no longer includes 'base_layer'.fixReplace 'asgi_redis' with 'channels_redis', which is compatible with newer versions of 'asgiref'. -
ImportError: cannot import name 'ThreadSensitiveContext' from 'asgiref.sync'
cause The 'ThreadSensitiveContext' class has been removed in newer versions of 'asgiref'.fixUpdate the code to remove references to 'ThreadSensitiveContext' and use alternative approaches for thread-sensitive operations. -
ModuleNotFoundError: No module named 'asgiref.sync'
cause The 'asgiref' package is either not installed or not properly included in the project.fixInstall 'asgiref' using 'pip install asgiref' and ensure it's included in your project's dependencies. -
ERROR: Cannot install -r requirements.txt (line 8) and asgiref==3.2.5 because these package versions have conflicting dependencies.
cause The specified version of 'asgiref' conflicts with the version required by Django.fixRemove the specific version constraint for 'asgiref' in 'requirements.txt' to allow compatibility with Django's required version.
Warnings
- breaking Import paths have changed in asgiref 3.11.1; ensure correct imports to avoid ImportError.
- gotcha Using AsyncToSync without proper context can lead to deadlocks; ensure it's used within an appropriate event loop.
- breaking The 'channels' package is not found. Ensure it is installed in the environment.
- breaking The 'channels' module is not found. Ensure it is installed in your environment.
Install
-
pip install asgiref
Imports
- ASGIApp
from asgiref.typing import ASGIApp
- AsyncToSync
from asgiref.sync import AsyncToSync
Quickstart
import os
from asgiref.sync import AsyncToSync
from channels.routing import ProtocolTypeRouter, URLRouter
from channels.auth import AuthMiddlewareStack
from django.urls import path
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'your_project.settings')
application = ProtocolTypeRouter({
'http': get_asgi_application(),
'websocket': AuthMiddlewareStack(
URLRouter([
path('ws/some_path/', your_consumer.as_asgi()),
])
),
})