python / expert
Snippet
Async Request Context Middleware for Correlation ID Injection
This middleware demonstrates asynchronous HTTP request handling in Django, capturing header context and ensuring exception propagation across async boundaries.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
from typing import Callable, Awaitablefrom django.http import HttpRequest, HttpResponseclass AsyncCorrelationMiddleware:def __init__(self, get_response: Callable[[HttpRequest], Awaitable[HttpResponse]]):self.get_response = get_responseasync def __call__(self, request: HttpRequest) -> HttpResponse:request.correlation_id = request.headers.get("X-Correlation-ID", "anon")try:response = await self.get_response(request)response["X-Correlation-ID"] = request.correlation_idreturn responseexcept Exception as exc:request.meta_error = str(exc)raise
django
Breakdown
1
class AsyncCorrelationMiddleware:
Defines an asynchronous middleware class compatible with Django's ASGI pipeline.
2
def __init__(self, get_response: Callable[[HttpRequest], Awaitable[HttpResponse]]):
Stores the downstream asynchronous response handler executable.
3
async def __call__(self, request: HttpRequest) -> HttpResponse:
Defines the async call interface invoked for processing incoming HTTP requests.
4
request.correlation_id = request.headers.get("X-Correlation-ID", "anon")
Extracts incoming correlation header or assigns a default value to the request.
5
response = await self.get_response(request)
Awaits downstream request processing asynchronously to generate the response.