Spaces:
Build error
Build error
Download app/middleware/correlation.py from anwarkxc/trackademi: direct link, hf CLI and curl.
- Browser
- Download file 1.11 kB
-
https://huggingface.co/spaces/anwarkxc/trackademi/resolve/main/app/middleware/correlation.py
- Command line
-
hf download hf://spaces/anwarkxc/trackademi/app/middleware/correlation.py
-
curl -L -o correlation.py https://huggingface.co/spaces/anwarkxc/trackademi/resolve/main/app/middleware/correlation.py
1.11 kB
| """Correlation ID middleware — extracts or generates X-Correlation-ID for every request. | |
| The ID is stored in a contextvars.ContextVar so any code in the request path | |
| (services, DB calls, logging) can call ``get_correlation_id()`` to read it. | |
| """ | |
| import uuid | |
| import contextvars | |
| from starlette.middleware.base import BaseHTTPMiddleware | |
| from starlette.requests import Request | |
| from starlette.responses import Response | |
| CORRELATION_HEADER = "X-Correlation-ID" | |
| _correlation_id_var: contextvars.ContextVar[str | None] = contextvars.ContextVar( | |
| "correlation_id", default=None | |
| ) | |
| def get_correlation_id() -> str | None: | |
| return _correlation_id_var.get() | |
| class CorrelationIdMiddleware(BaseHTTPMiddleware): | |
| async def dispatch(self, request: Request, call_next): | |
| cid = request.headers.get(CORRELATION_HEADER) or str(uuid.uuid4()) | |
| token = _correlation_id_var.set(cid) | |
| try: | |
| response: Response = await call_next(request) | |
| response.headers[CORRELATION_HEADER] = cid | |
| return response | |
| finally: | |
| _correlation_id_var.reset(token) | |