Hi i have my middleware written like this
@app.middleware("http")
async def request_middleware(request, call_next):
end_point = request.url.path
global request_id
request_id = get_request_id()
with logger.contextualize(request_id=request_id, end_point=end_point):
logger.info("----------Request started----------")
try:
response = await call_next(request)
except Exception as ex:
logger.error(f"Request failed: {ex}")
response = JSONResponse()
finally:
response.headers["X-Request-Id"] = request_id
logger.info("----------Request ended----------")
return response
i want the request_id defined in middleware to be accessible in other function defined, how can we do that?
Another 2 solutions:
request.state
in your middleware, and then access request.state
in the view functions. More info in https://fastapi.tiangolo.com/tutorial/sql-databases/?h=request.#about-requeststatefrom starlette_context import context
@app.middleware("http")
async def request_middleware(request, call_next):
request_id = get_request_id()
context['request_id'] = request_id
@router.post('foobar')
async def foorbar():
context['request_id']
Instead of a global request_id, you can use a context variable, which is not shared between async tasks
from contextvars import ContextVar
req_id: ContextVar[str] = ContextVar('req_id', default='')
# Inside your middleware
req_id.set(get_request_id())
# Inside other functions, even different files, you import that variable
req_id.get()
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.