在 Fastapi 中在哪里放置用于身份验证的依赖项/依赖项?

Where to put depends/ dependendies for authentication in Fastapi?

我见过两种在 Fastapi 身份验证中使用 depends 的不同方法:

方法一:

@app.get('/api/user/me')
async def user_me(user: dict = Depends(auth)):
    return user

和方法二:

@app.get('/api/user/me', dependencies=[Depends(auth)])
async def user_me(user: dict):
    return user

方法 1 和方法 2 之间有什么区别,哪种方法更适合保护 API 即要求身份验证?

In some cases you don't really need the return value of a dependency inside your path operation function. Or the dependency doesn't return a value. But you still need it to be executed/solved. For those cases, instead of declaring a path operation function parameter with Depends, you can add a list of dependencies to the path operation decorator.

可以在此处找到更多详细信息和提示:https://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/

正如@Omer Alkin 正确指出的那样,当我们想要使用其 return 值(用户或令牌或其他)时,需要在路径操作参数列表中指定依赖项。这是来自 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

如果依赖的return值对我们不重要或者没有被return编辑,而只有一个副作用很重要,比如依赖抛出异常,那么我们可以在路径操作装饰器中指定依赖。

这种情况下,我们也可以对一组操作立即执行依赖(做鉴权),使用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.