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 instanciated just once when the application starts,
    # and closed when the server shuts down
    httpx_client: httpx.AsyncClient = request.state["httpx_client"]

Quickstart

  1. Python ^3.10 || ^3.11 || ^3.12 || ^3.13 and Django ^4.2 || ^5.0.3 || ^5.1 are supported. To install this package run:

    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.4.0.tar.gz (13.6 kB view details)

Uploaded Source

Built Distribution

django_asgi_lifespan-0.4.0-py3-none-any.whl (11.1 kB view details)

Uploaded Python 3

File details

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

File metadata

  • Download URL: django_asgi_lifespan-0.4.0.tar.gz
  • Upload date:
  • Size: 13.6 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? No
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for django_asgi_lifespan-0.4.0.tar.gz
Algorithm Hash digest
SHA256 a1a7d6451b08d24671bebd12571993cef16e25ec25e84a0d53d3f62a7845891f
MD5 2d81129d4725c5e9c32773e037370f53
BLAKE2b-256 240263a812cedbeb4482a78ac134a16f22150e29df25ccbf4575f8641fea2c64

See more details on using hashes here.

File details

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

File metadata

File hashes

Hashes for django_asgi_lifespan-0.4.0-py3-none-any.whl
Algorithm Hash digest
SHA256 f7fa18ecdeae9df2c92bf50ac717dc10df0465af5c0f29715b8a92a4e7388bac
MD5 7ac484ec441754658637ead5f9bdab54
BLAKE2b-256 c7fb433256bf86381fe56c3e139526d4ef7c4fd121ed31b5d2056cc9b9d50c35

See more details on using hashes here.

Supported by

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