Python FastAPI从API密钥获取用户ID

Python FastAPI从API密钥获取用户ID,python,python-3.x,python-asyncio,fastapi,Python,Python 3.x,Python Asyncio,Fastapi,在fastAPI中,只需在路由器级别编写一个安全依赖项,即可保护URL的整个部分 router.include_router( my_router, prefix="/mypath", dependencies=[Depends(auth.oauth2_scheme)] ) 这样可以避免重复大量代码 唯一的问题是,我想用路由器级别的依赖项来保护URL的一部分,该依赖项检查用户令牌的有效性并检索该令牌的用户id 我发现的唯一方法是向所有函数添加另一个依

在fastAPI中,只需在路由器级别编写一个安全依赖项,即可保护URL的整个部分

router.include_router(
    my_router,
    prefix="/mypath",
    dependencies=[Depends(auth.oauth2_scheme)]
)
这样可以避免重复大量代码

唯一的问题是,我想用路由器级别的依赖项来保护URL的一部分,该依赖项检查用户令牌的有效性并检索该令牌的用户id

我发现的唯一方法是向所有函数添加另一个依赖项,但这会导致重复我刚才保存的代码

长话短说,有没有办法在路由器级别添加依赖项,检索并返回用户id,并将返回的值传递给处理函数?差不多

路由器.py

router.include_router(
        my_router,
        prefix="/mypath",
        dependencies=[user_id = Depends(auth.oauth2_scheme)]
    )
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 {}
我的路由器.py

router.include_router(
        my_router,
        prefix="/mypath",
        dependencies=[user_id = Depends(auth.oauth2_scheme)]
    )
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 {}

在依赖函数中对用户进行身份验证后,将用户id添加到
请求.state
,然后在路由上可以从请求对象访问它

async def oauth2_方案(请求:请求):
request.state.user_id=“foo”
my_router=APIRouter()
@我的路由器。获取(“/”)
异步def hello(请求:请求):
打印(请求.状态.用户\u id)
app.include_路由器(
我的路由器,
依赖项=[依赖项(oauth2_方案)]
)

谢谢,我没有考虑直接访问请求。值得补充的是,路由依赖项和普通依赖项有两个不同的作用域,可以复制(一个检查身份验证密钥,另一个获取数据),由于缓存,不会造成性能损失,正如在“我不知道为什么我在提问时没有找到它”中所讨论的。。。