Daphne - ASGI Server
Daphne is a pure-Python HTTP, HTTP/2, and WebSocket protocol server for ASGI (Asynchronous Server Gateway Interface) applications. It is primarily developed to power Django Channels and acts as the reference server for ASGI. It supports automatic negotiation of protocols, removing the need for URL prefixing for different endpoints. The current version is 4.2.1.
Warnings
- gotcha Daphne requires Python 3.9 or later. Using older Python versions will lead to installation or runtime errors.
- gotcha When `daphne` is added to `INSTALLED_APPS` for `runserver` integration, it can conflict with other third-party apps that also overload or replace the `runserver` command (e.g., Whitenoise's `runserver_nostatic`).
- gotcha Daphne's HTTP/2 support is limited to 'normal' requests and does not include extended features like Server Push. If using a reverse proxy in front of Daphne for HTTP/2, ensure the proxy correctly understands and passes through the HTTP/2 connection.
- gotcha Setting a root path (equivalent to WSGI's `SCRIPT_NAME`) can be done via the `Daphne-Root-Path` HTTP header or the `--root-path` command-line option. The header takes precedence. The root path value should start with a slash but not end with one.
Install
-
pip install daphne
Quickstart
# myproject/asgi.py
import os
from channels.routing import ProtocolTypeRouter
from django.core.asgi import get_asgi_application
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')
# Initialize Django ASGI application early to ensure the AppRegistry
# is populated before importing code that may import ORM models.
django_asgi_app = get_asgi_application()
application = ProtocolTypeRouter({
"http": django_asgi_app,
# Add WebSocket protocol here if using Django Channels
# "websocket": URLRouter(websocket_urlpatterns)
})
# To run:
# Ensure myproject is on the Python path (e.g., run from parent directory of myproject)
# daphne -b 0.0.0.0 -p 8000 myproject.asgi:application