-
Notifications
You must be signed in to change notification settings - Fork 3
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Merge pull request #14 from wednesday-solutions/feat/request-id-injec…
…tion Feat/request id injection
- Loading branch information
Showing
4 changed files
with
40 additions
and
4 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,22 @@ | ||
from fastapi import FastAPI | ||
from starlette.middleware.base import BaseHTTPMiddleware | ||
from starlette.requests import Request | ||
from fastapi.responses import JSONResponse | ||
import contextvars | ||
import uuid | ||
|
||
request_id_contextvar = contextvars.ContextVar("request_id", default=None) | ||
|
||
class RequestIdInjection(BaseHTTPMiddleware): | ||
def dispatch(self, request: Request, call_next): | ||
request_id = str(uuid.uuid4()) | ||
request_id_contextvar.set(request_id) | ||
try: | ||
return call_next(request) | ||
|
||
except Exception as ex: | ||
print(ex) | ||
return JSONResponse(content={"success": False}, status_code=500) | ||
|
||
finally: | ||
assert request_id_contextvar.get() == request_id |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -115,4 +115,5 @@ flake8 | |
black | ||
pre-commit | ||
pybreaker | ||
pytest-asyncio | ||
pytest-asyncio | ||
contextvars |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters