一直在尝试使用 FASTAPI 中间件获取请求的正文,但似乎我只能获取 request.headers 而不能获取正文。我需要主体才能获得用于检查数据库中某些内容的密钥。考虑中间件的日志记录或身份验证使用。这必须在不自定义 APIRouter 的情况下完成,只需要在中间件级别完成,以免影响应用程序的其余部分。
@app.middleware("http")
async def TestCustomMiddleware(request: Request, call_next):
print("Middleware works!", request.headers)
response = await call_next(request)
resp_body = [section async for section in response.__dict__['body_iterator']]
print("BODY:", resp_body)
return response
Run Code Online (Sandbox Code Playgroud)
我能够得到这个,但有一个错误会破坏 POST 请求:
INFO: Started server process [37160]
INFO: Waiting for application startup.
INFO: Application startup complete.
INFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)
Middleware works! Headers({'content-type': 'application/json', 'user-agent': 'PostmanRuntime/7.26.8', 'accept': '*/*', 'cache-control': 'no-cache', 'postman-token': 'ca6839ec-833d-45c0-9b52-8f904db13966', 'host': 'localhost:8000', 'accept-encoding': 'gzip, deflate, br', 'connection': 'keep-alive', 'content-length': '12'}) …
Run Code Online (Sandbox Code Playgroud)