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, <3.15 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.3

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.3
File Size Uploaded Provenance
django_asgi_lifespan-0.5.3.tar.gz 9.2 kB Without provenance Details

Built distribution (wheel)

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

Total release size: 21.7 kB

Release files / django_asgi_lifespan-0.5.3.tar.gz

Download URL django_asgi_lifespan-0.5.3.tar.gz
Size 9.2 kB
Tags Source
SHA-256 checksum
How to use checksums
b449ce16593e69de06c4d5335e1c0f4b0d4cf17c10a86d06434b002e55cd4339
BLAKE2b-256 checksum
How to use checksums
50e8a4211a70665b21c7d99888e3b35dd325efdb124e80dfbe1b9090a09cf1c3
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

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

Download URL django_asgi_lifespan-0.5.3-py3-none-any.whl
Size 12.5 kB
Tags Python 3
SHA-256 checksum
How to use checksums
dfc565d0fb4ffcdfd278009bd521557de49fb64f5702c618387f0268b8fdbb2c
BLAKE2b-256 checksum
How to use checksums
fee6c52fe5950b429c780d4b72e1d5f8db9840745b4a967bc26feb00c6de6117
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via twine/7.0.0 CPython/3.13.14

Security for django-asgi-lifespan 0.5.3

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.

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