首页 > 解决方案 > 在 Fastapi 中将依赖/依赖项放在哪里进行身份验证?

问题描述

我在 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,即需要身份验证?

标签: pythonpython-3.xauthenticationfastapi

解决方案


在某些情况下,您实际上并不需要路径操作函数中依赖项的返回值。或者依赖不返回值。但是您仍然需要执行/解决它。对于这些情况,您可以将依赖项列表添加到路径操作装饰器中,而不是使用 Depends 声明路径操作函数参数。

更多细节和技巧可以在这里找到:https ://fastapi.tiangolo.com/tutorial/dependencies/dependencies-in-path-operation-decorators/


推荐阅读