Setting Custom Context for Requests for Python

Set per-request context to surface important metadata when things go wrong.


Attaching Context Metadata (Python)

Overview

The Hud Python SDK lets you attach custom context metadata to the forensics data of the current execution - whether it’s an HTTP request, a background job, an Arq message, or any other handler. This context is recorded and shown when an endpoint or worker fails or behaves unexpectedly, enabling richer debugging and faster investigation.

Use hud_sdk.set_context() to inject metadata relevant to the current run, such as client_id, message_id, user_tier, or feature_flag_status. The context is scoped to the current execution only and is automatically cleared afterward.

When to Use

Use set_context if:

  • You want extra identifiers in logs or error dashboards for specific requests or messages.
  • You need metadata to trace failures or abnormal behaviors across systems
  • You want to correlate issues with tenants, plans, user types, or feature rollout states.

🚧

Important Notes

  • set_context must be called during the active handling of a request or message.
  • It is per-invocation only. Calling it outside a request/message handler (e.g., in startup code) has no effect.
  • The context is automatically cleared after the handler completes.
  • Keys must be str.
  • Values can be: str | int | float | bool | list[str] | list[int] | list[float]| list[bool].

Example #1: Django Middleware

# myproject/middleware/hud_context.py
import hud_sdk

class HudContextMiddleware:
    def __init__(self, get_response):
        self.get_response = get_response

    def __call__(self, request):
        hud_sdk.set_context(
            client_id=request.headers.get("X-Client-Id"),
            request_id=request.headers.get("X-Request-Id"),
            user_tier=request.headers.get("X-User-Tier"),
        )
        return self.get_response(request)

Add it to your setting:

# settings.py
MIDDLEWARE = [
    # ...
    "myproject.middleware.hud_context.HudContextMiddleware",
]

Example #2: FastAPI Middleware

from fastapi import FastAPI, Request
import hud_sdk

app = FastAPI()

@app.middleware("http")
async def add_hud_context(request: Request, call_next):
    hud_sdk.set_context(
        client_id=request.headers.get("X-Client-Id"),
        request_id=request.headers.get("X-Request-Id"),
        user_tier=request.headers.get("X-User-Tier"),
    )
    response = await call_next(request)
    return response