python / expert
Snippet
Contextvar-Driven Error Tracking in Async ASGI Middleware
Async ASGI middleware uses contextvars to maintain thread-safe, coroutine-isolated request context across asynchronous execution flows when handling exceptions.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import contextvarsfrom django.core.exceptions import PermissionDeniedrequest_id_var = contextvars.ContextVar('request_id', default=None)class AsyncExceptionContextMiddleware:def __init__(self, get_response):self.get_response = get_responseasync def __call__(self, request):token = request_id_var.set(request.headers.get('X-Request-ID', 'anon'))try:return await self.get_response(request)except PermissionDenied as exc:req_id = request_id_var.get()raise RuntimeError(f"[Req: {req_id}] Async Auth Failure: {exc}") from excfinally:request_id_var.reset(token)
django
Breakdown
1
request_id_var = contextvars.ContextVar('request_id', default=None)
Instantiates a ContextVar object to safely pass state through asynchronous task chains.
2
token = request_id_var.set(request.headers.get('X-Request-ID', 'anon'))
Binds the incoming request header identifier to the current async context and returns a reset token.
3
finally: request_id_var.reset(token)
Ensures context isolation by cleaning up the ContextVar state after async execution completes.