我们正在使用 Python FastAPI 编写一个 Web 服务,该服务将托管在 Kubernetes 中。出于审计目的,我们需要保存特定路由的request/的原始 JSON 正文。JSON的主体大小约为1MB,最好这不应该影响响应时间。我们怎样才能做到这一点?responserequestresponse
有没有办法在中间件中获取响应内容?以下代码是从此处复制的。
@app.middleware("http")
async def add_process_time_header(request: Request, call_next):
start_time = time.time()
response = await call_next(request)
process_time = time.time() - start_time
response.headers["X-Process-Time"] = str(process_time)
return response
Run Code Online (Sandbox Code Playgroud) 我想知道是否可以将dependencieskwarg 的结果传递到include_router传递给它的路由器。我想要做的是从x-token请求标头中解码 JWT 并将解码后的有效负载传递给路由books。
我知道我可以编写authenticate_and_decode_JWT为 routers/book.py 中每个路由的依赖项,但这对于大型应用程序来说会非常重复。
主要.py
from typing import Optional
from jose import jwt
from fastapi import FastAPI, Depends, Header, HTTPException, status
from jose.exceptions import JWTError
from routers import books
app = FastAPI()
def authenticate_and_decode_JWT(x_token: str = Header(None)):
try:
payload = jwt.decode(x_token.split(' ')[1], 'secret key', algorithms=['HS256'])
return payload # pass decoded user information from here to books.router routes somehow
except JWTError:
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED)
app.include_router(
books.router,
prefix="/books",
dependencies=[Depends(authenticate_and_decode_JWT)],
) …Run Code Online (Sandbox Code Playgroud)