1
0
mirror of https://github.com/home-assistant/core.git synced 2026-05-19 15:00:27 +01:00
Files
core/homeassistant/components/http/request_context.py
T
2026-04-30 21:14:48 +02:00

27 lines
809 B
Python

"""Middleware to set the request context."""
from collections.abc import Awaitable, Callable
from contextvars import ContextVar
from aiohttp.web import Application, Request, StreamResponse, middleware
from homeassistant.core import callback
from homeassistant.helpers.http import current_request # noqa: F401
@callback
def setup_request_context(
app: Application, context: ContextVar[Request | None]
) -> None:
"""Create request context middleware for the app."""
@middleware
async def request_context_middleware(
request: Request, handler: Callable[[Request], Awaitable[StreamResponse]]
) -> StreamResponse:
"""Request context middleware."""
context.set(request)
return await handler(request)
app.middlewares.append(request_context_middleware)