Source code for ferrosoft.apps.ferrobase.context

#  Copyright (c) 2026 Ferrosoft GmbH. All rights reserved.
"""ASGI lifespan context managers for shared HTTP client lifecycle."""
from contextlib import asynccontextmanager

import httpx

from django_asgi_lifespan.types import LifespanManager


[docs] @asynccontextmanager async def httpx_lifespan_manager() -> LifespanManager: """Manage an HTTPX ``AsyncClient`` across the full ASGI application lifespan. Yields a state dict so that request handlers can reuse one long-lived connection pool via ``request.state.httpx_client`` instead of opening a new connection per request. Yields: dict: ``{"httpx_client": httpx.AsyncClient}`` """ state = {"httpx_client": httpx.AsyncClient()} try: yield state finally: await state["httpx_client"].aclose()