django / django/channels

lifespan support

Open
#2,018 1 comment 1 reaction 0 assignees View on GitHub
Dominant language
Python
Stars
6.4k
Forks
826
PR merge metrics
No merged PRs in 30d

Description

Error:

```
[info] 0#929131 [unit] ASGI Lifespan processing exception
Traceback (most recent call last):
File "/usr/local/lib/python3.11/site-packages/django/core/handlers/asgi.py", line 150, in __call__
raise ValueError(
ValueError: Django can only handle ASGI/HTTP connections, not lifespan.

```

Minimal lifespan support for nginx unit application server + django asgi + channels

lifespan.py

```
from logging import getLogger

logger = getLogger(__name__)

async def LifeSpanHandler(scope, receive, send):
if scope['type'] == 'lifespan':
while True:
message = await receive()
if message['type'] == 'lifespan.startup':
await send({'type': 'lifespan.startup.complete'})
elif message['type'] == 'lifespan.shutdown':
await send({'type': 'lifespan.shutdown.complete'})
return
else:
logger.error(f"Lifespan handler error, wrong scope: {scope}")
```

asgi.py

```
from lifespan import LifeSpanHandler

django_asgi_app = get_asgi_application()

application = ProtocolTypeRouter(
{
"http": django_asgi_app,
"websocket": AllowedHostsOriginValidator(AuthMiddlewareStack(URLRouter(urlpatterns))),
"lifespan": LifeSpanHandler,
}
)

```

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.