我在 Fastapi 身份验证中看到了两种不同的使用方法:
方法一:
@app.get('/api/user/me')
async def user_me(user: dict = Depends(auth)):
return user
和方法2:@app.get('/api/user/me', dependencies=[Depends(auth)])
async def user_me(user: dict):
return user
方法 1 和方法 2 之间有什么区别,哪个更适合保护 API,即需要身份验证?
最佳答案
正如@Omer Alkin 正确指出的那样,当我们想要使用其返回值(用户或 token 或 smth.)时,需要在路径操作参数列表中指定依赖项。这是来自 documentation 的示例:
async def get_current_user(token: str = Depends(oauth2_scheme)):
user = fake_decode_token(token)
return user
@app.get("/users/me")
async def read_users_me(current_user: User = Depends(get_current_user)):
return current_user
如果依赖的返回值对我们来说不重要或者不返回,但只有一个副作用是重要的,例如依赖抛出异常,那么我们可以在路径操作装饰器中指定依赖。在这种情况下,我们还可以使用
APIRouter
立即为一组操作执行依赖项(进行身份验证)。 :
async def get_token_header(x_token: str = Header(...)):
if x_token != "fake-super-secret-token":
raise HTTPException(status_code=400, detail="X-Token header invalid")
router = APIRouter(
prefix="/items",
tags=["items"],
dependencies=[Depends(get_token_header)],
responses={404: {"description": "Not found"}},
)
还需要注意的是,您可以在路径操作或其子依赖中重用相同的依赖,因为 FastAPI 实现了 cache policy默认情况下:If one of your dependencies is declared multiple times for the same path operation, for example, multiple dependencies have a common sub-dependency, FastAPI will know to call that sub-dependency only once per request.
关于python - 在 Fastapi 中,在哪里放置用于身份验证的依赖项/依赖项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67307265/