Request-scoped context object that holds trace_id and other request data. This provides a Flask g-like object for FastAPI applications.
| 23 | |
| 24 | |
| 25 | class RequestContext: |
| 26 | """ |
| 27 | Request-scoped context object that holds trace_id and other request data. |
| 28 | |
| 29 | This provides a Flask g-like object for FastAPI applications. |
| 30 | """ |
| 31 | |
| 32 | def __init__( |
| 33 | self, |
| 34 | trace_id: str | None = None, |
| 35 | api_path: str | None = None, |
| 36 | env: str | None = None, |
| 37 | user_type: str | None = None, |
| 38 | user_name: str | None = None, |
| 39 | source: str | None = None, |
| 40 | ): |
| 41 | self.trace_id = trace_id or "trace-id" |
| 42 | self.api_path = api_path |
| 43 | self.env = env |
| 44 | self.user_type = user_type |
| 45 | self.user_name = user_name |
| 46 | self.source = source |
| 47 | self._data: dict[str, Any] = {} |
| 48 | |
| 49 | def set(self, key: str, value: Any) -> None: |
| 50 | """Set a value in the context.""" |
| 51 | self._data[key] = value |
| 52 | |
| 53 | def get(self, key: str, default: Any | None = None) -> Any: |
| 54 | """Get a value from the context.""" |
| 55 | return self._data.get(key, default) |
| 56 | |
| 57 | def __setattr__(self, name: str, value: Any) -> None: |
| 58 | if name.startswith("_") or name in ( |
| 59 | "trace_id", |
| 60 | "api_path", |
| 61 | "env", |
| 62 | "user_type", |
| 63 | "user_name", |
| 64 | "source", |
| 65 | ): |
| 66 | super().__setattr__(name, value) |
| 67 | else: |
| 68 | if not hasattr(self, "_data"): |
| 69 | super().__setattr__(name, value) |
| 70 | else: |
| 71 | self._data[name] = value |
| 72 | |
| 73 | def __getattr__(self, name: str) -> Any: |
| 74 | if hasattr(self, "_data") and name in self._data: |
| 75 | return self._data[name] |
| 76 | raise AttributeError(f"'{self.__class__.__name__}' object has no attribute '{name}'") |
| 77 | |
| 78 | def to_dict(self) -> dict[str, Any]: |
| 79 | """Convert context to dictionary.""" |
| 80 | return { |
| 81 | "trace_id": self.trace_id, |
| 82 | "api_path": self.api_path, |
no outgoing calls