[英]Capture unique id in router.post fastapi
我正在嘗試使用以下方法在 python 中使用 fastapi 捕獲 api 所花費的時間:
import string, time, random, logging
from starlette.requests import Request
@app.middleware("http")
async def log_requests(request: Request, call_next):
idem = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
logger.info(f"rid={idem} start request path={request.url.path}")
start_time = time.time()
response = await call_next(request)
process_time = (time.time() - start_time) * 1000
formatted_process_time = '{0:.2f}'.format(process_time)
logger.info(f"rid={idem} completed_in={formatted_process_time}ms status_code={response.status_code}")
return response
我想在@router.post
部分中捕獲唯一的id idem
,如下所示,但它給出了錯誤:
import logging as log
@router.post("/infer/", response_description="AD Data Infer")
async def ad_infer_algorithm(ad_infer_config: ADInferConfigSchema = Body(...)):
log.info("Executing AD Train Algorithm with config"+idem)
return "2"
請幫助
FastAPI 在request
object 上有一個state
屬性。 這允許您將 state 附加到來自中間件的請求,然后在 controller(或其他中間件)中訪問該 state。
由於您的中間件中已經有request
object 可用,您只需將idem
附加到請求 state 那里:
async def log_requests(request: Request, call_next):
idem = ''.join(random.choices(string.ascii_uppercase + string.digits, k=6))
request.state.idem = idem
(旁注:您可能可以將random.choices
調用替換為secrets.token_urlsafe
以獲得隨機生成的標識符(除非您需要控制大寫和小寫標識符 - 因為您沒有包含 ascii_lowercase)。
然后,您可以在視圖 controller 中訪問該 state:
@router.post("/infer/", response_description="AD Data Infer")
async def ad_infer_algorithm(request: Request, ad_infer_config: ADInferConfigSchema = Body(...)):
log.info("Executing AD Train Algorithm with config" + request.state.idem)
return "2"
(另一個注意事項:日志記錄命令通常應使用占位符( %s
),然后將變量用作 arguments: log.info("Executing AD Train Algorithm with config %s", request.state.idem)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.