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.2.tar.gz (9.2 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.2-py3-none-any.whl (12.5 kB view details)

Uploaded Python 3

File details

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

File metadata

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

File hashes

Hashes for django_asgi_lifespan-0.5.2.tar.gz
Algorithm Hash digest
SHA256 a56872ffc8cd41a9236fd435e18740646da5762dfb1157c639b3909b531a8b3a
MD5 faaac956cb31133afa9e4966c48b61bf
BLAKE2b-256 267ad0ba29fa4c3d105d83b0f0fef41c7ac51c291907b40b154e6ffa6ee5f488

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for django_asgi_lifespan-0.5.2-py3-none-any.whl
Algorithm Hash digest
SHA256 d0478aa6b217c04eb56aaaf8a51cf57e51719d9af6266101cd715743ac03d9c5
MD5 a605fe3c0f0689ee75a45b4681eb50ab
BLAKE2b-256 e7065c79ef479cc130eb0bf9e29c2aec3f2d7865c226e3e672ab7123ef20552d

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