我有这样的想法
class RequestContext(BaseHTTPMiddleware):
async def dispatch(self, request: Request, call_next: RequestResponseEndpoint):
request_id = request_ctx.set(str(uuid4())) # generate uuid to request
body = await request.body()
if body:
logger.info(...) # log request with body
else:
logger.info(...) # log request without body
response = await call_next(request)
response.headers['X-Request-ID'] = request_ctx.get()
logger.info("%s" % (response.status_code))
request_ctx.reset(request_id)
return response
因此body = await request.body()
行冻结了所有具有body的请求,我从所有请求中获得了504个请求。在这种情况下,如何安全地阅读请求正文?我只想记录请求参数
如果您仍然想使用BaseHTTP,我最近遇到了这个问题,并提出了一个解决方案:
中间件代码
来自TypeError from Python 3 async for loop
我真的希望这能帮助别人!我发现这对日志记录非常有用
非常感谢@Eddified参加aiwrap课程
我不会创建一个继承自BaseHTTPMiddleware的中间件,因为它有一些issues,FastAPI为您提供了创建自己的路由器的机会,根据我的经验,这种方法更好
一切正常
相关问题 更多 >
编程相关推荐