【发布时间】:2020-08-05 20:27:57
【问题描述】:
在 fastAPI 中,可以简单地在路由器级别编写安全依赖项并保护 URL 的整个部分。
router.include_router(
my_router,
prefix="/mypath",
dependencies=[Depends(auth.oauth2_scheme)]
)
这样可以避免重复大量代码。
唯一的问题是我想保护具有路由器级别依赖关系的 URL 的一部分,该依赖关系检查用户令牌的有效性并检索该令牌的用户 ID。
我发现的唯一方法是为所有函数添加另一个依赖项,但这会导致重复我刚刚保存的代码。
长话短说,有没有办法在路由器级别添加依赖项,检索并返回用户 ID,并将返回值传递给处理函数?类似的东西
router.py
router.include_router(
my_router,
prefix="/mypath",
dependencies=[user_id = Depends(auth.oauth2_scheme)]
)
my_router.py
my_router = APIRouter()
@my_router.get("/my_path")
async def get_my_path(**kwargs):
user_id = kwargs["user_id"]
# Do stuff with the user_id
return {}
【问题讨论】:
标签: python python-3.x python-asyncio fastapi