【发布时间】:2022-09-23 04:36:34
【问题描述】:
我正在尝试使用以下方法在 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\"
请帮助
-
如果您想将元数据附加到请求中,您可以在
log_requests中执行request.state.idem = idem,然后将request: Request作为参数添加到ad_infer_algoritm并再次使用request.state.idem检索它。那对你有用吗? -
@MatsLindh 这完美无瑕。只是不要在评论中,而是以适当的方式写下这个,以便我可以接受您的答案作为已解决。