Skip to main content

Django ASGI handler with Lifespan Protocol support.

Project description

Django ASGI Handler with Lifespan protocol support

License: MIT pypi pypi Python version Supported Django
Build Status codecov

Main features

async def example_view(request) -> HttpResponse:
    # The client is instantiated just once when the application starts,
    # and closed when the server shuts down
    httpx_client: httpx.AsyncClient = request.state["httpx_client"]

Quickstart

  1. Requirements: Python >=3.10, <3.15 and Django >=4.2,<6.1 (excluding 5.0.0 .. 5.0.2). Install the package:

    uv add django-asgi-lifespan
    

    or

    poetry add django-asgi-lifespan@latest
    

    or

    pip install --upgrade django-asgi-lifespan
    
  2. Modify asgi.py to use a ASGI Lifespan compatible handler.

    from django_asgi_lifespan.asgi import get_asgi_application
    
    django_application = get_asgi_application()
    
    
    async def application(scope, receive, send):
        if scope["type"] in {"http", "lifespan"}:
            await django_application(scope, receive, send)
        else:
            raise NotImplementedError(
                f"Unknown scope type {scope['type']}"
            )
    
  3. Add state middleware:

    MIDDLEWARE = [
        # ...
        "django_asgi_lifespan.middleware.LifespanStateMiddleware",
        # ...
    ]
    
  4. Register async context manager:

    from contextlib import asynccontextmanager
    
    import httpx
    
    from django_asgi_lifespan.types import LifespanManager
    
    
    @asynccontextmanager
    async def httpx_lifespan_manager() -> LifespanManager:
        state = {
            "httpx_client": httpx.AsyncClient()
        }
    
        try:
            yield state
        finally:
            await state["httpx_client"].aclose()
    
    from django.apps import AppConfig
    
    from django_asgi_lifespan.register import register_lifespan_manager
    from .context import (
        httpx_lifespan_manager,
    )
    
    
    class ExampleAppConfig(AppConfig):
    
        def ready(self):
            register_lifespan_manager(
                context_manager=httpx_lifespan_manager
            )
    
  5. Use some resource (in this case the HTTPX client) in views.

    from http import HTTPStatus
    
    import httpx
    from django.http import HttpResponse
    
    
    async def example_view(request) -> HttpResponse:
        httpx_client: httpx.AsyncClient = request.state["httpx_client"]
    
        await httpx_client.head("https://www.example.com/")
    
        return HttpResponse(
            "OK",
            status=HTTPStatus.OK,
            content_type="text/plain; charset=utf-8",
        )
    
  6. Run uvicorn:

    uvicorn asgi:application --lifespan=on --port=8080
    

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_asgi_lifespan-0.5.1.tar.gz (8.5 kB view details)

Uploaded Source

Built Distribution

If you're not sure about the file name format, learn more about wheel file names.

django_asgi_lifespan-0.5.1-py3-none-any.whl (11.4 kB view details)

Uploaded Python 3

File details

Details for the file django_asgi_lifespan-0.5.1.tar.gz.

File metadata

  • Download URL: django_asgi_lifespan-0.5.1.tar.gz
  • Upload date:
  • Size: 8.5 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/6.1.0 CPython/3.13.7

File hashes

Hashes for django_asgi_lifespan-0.5.1.tar.gz
Algorithm Hash digest
SHA256 2e0a422ec53ffac648e0cc247f4728d97b64e0a3c022077f937592d5af024d4b
MD5 36faa308fc365925c903b5ace31aede4
BLAKE2b-256 937914ab57a80b0cc65d032f47661b7cac3a4ce1392ed8b056a4a8caca93e12f

See more details on using hashes here.

File details

Details for the file django_asgi_lifespan-0.5.1-py3-none-any.whl.

File metadata

File hashes

Hashes for django_asgi_lifespan-0.5.1-py3-none-any.whl
Algorithm Hash digest
SHA256 98be665a406ab355d3d96971d2cfa945def764297e8c6162c8e5b1f789c029ba
MD5 702b038dd4c09c1b9d60b996699c044e
BLAKE2b-256 c7604aedbd3a5b0f9f6abaa067d1e9c03572c3ef39a666bf33c924f5bb16e740

See more details on using hashes here.

Supported by

AWS Cloud computing and Security Sponsor Datadog Monitoring Depot Continuous Integration Fastly CDN Google Download Analytics Pingdom Monitoring Sentry Error logging StatusPage Status page