Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

lifespan support #2018

Open
avlubimov opened this issue Jun 14, 2023 · 1 comment
Open

lifespan support #2018

avlubimov opened this issue Jun 14, 2023 · 1 comment

Comments

@avlubimov
Copy link

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,
    }
)

@carltongibson
Copy link
Member

Hi @avlubimov.

So there's a middleware example in #1216.

Would you fancy adding some docs for this? It's a question that comes up periodically so having a good example/discussion to point people to would be helpful

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants