Skip to main content

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 and Django >=4.2 (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
    

Metadata

Release files for django-asgi-lifespan 0.5.4

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for django-asgi-lifespan 0.5.4
File Size Uploaded Provenance
django_asgi_lifespan-0.5.4.tar.gz 9.8 kB Without provenance Details

Built distribution (wheel)

Table of built distributions (wheels) for django-asgi-lifespan 0.5.4
File Interpreter ABI Platform
django_asgi_lifespan-0.5.4-py3-none-any.whl Python 3 none any Details

Total release size: 22.1 kB

Release files / django_asgi_lifespan-0.5.4.tar.gz

Download URL django_asgi_lifespan-0.5.4.tar.gz
Size 9.8 kB
Tags Source
SHA-256 checksum
How to use checksums
035c2d3392a52f85a317608833bd79bf4d9d1c569d189465c3511bc5909064f0
BLAKE2b-256 checksum
How to use checksums
32341ed378ae4adce12cb5c90f0904308bc0a716142a7b9d5b67c605503760be
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Release files / django_asgi_lifespan-0.5.4-py3-none-any.whl

Download URL django_asgi_lifespan-0.5.4-py3-none-any.whl
Size 12.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
81eed315ab3e21bb14ef230076954500cbab22b94ea1feb7233378d9d4d4c92b
BLAKE2b-256 checksum
How to use checksums
39fb938f8212bb1a53f675624c4b49c065ac4379d5deb2d17d000e2df9eb30e7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.16

Security for django-asgi-lifespan 0.5.4

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page