我想知道是否可以将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)