FastAPI中路径操作函数内的SecurityScopes对象为何为空?
问题解答
这是预期行为,具体原因如下:
SecurityScopes的注入逻辑与Security装饰器强绑定。当你在路径操作函数(如示例中的index)里直接声明SecurityScopes参数时,该参数未关联任何Security依赖,因此它的scopes属性会是空列表。- 官方文档中提到的:
它始终包含当前Security依赖项以及该特定路径操作和特定依赖树中所有依赖项声明的安全作用域。
这里的“它”特指被Security装饰器调用的依赖函数中注入的SecurityScopes对象,并非路径操作函数里直接声明的SecurityScopes。
如果你需要在路径操作函数中获取权限作用域,可以通过以下方式实现:
方法:从依赖函数返回作用域
修改依赖函数,让它返回 SecurityScopes 对象,再在路径操作函数中接收该返回值:
from typing import Annotated, Any from fastapi import FastAPI, Security from fastapi.security import SecurityScopes app = FastAPI() def dependency_one(scope: SecurityScopes): print("dependency function is running.") print(f"scope in dependency_one is {scope.scopes}.") return scope # 返回SecurityScopes对象 @app.get("/") def index( obj: Annotated[SecurityScopes, Security(dependency_one, scopes=["items"])], ): print(f"scope in path operation function is {obj.scopes}.") return "Hello test"
请求接口后,输出会变为:
INFO: Started server process [XXXX] INFO: Waiting for application startup. INFO: Application startup complete. dependency function is running. scope in dependency_one is ['items']. scope in path operation function is ['items']. INFO: 127.0.0.1:XXXX - "GET / HTTP/1.1" 200 OK
这样就能在路径操作函数中获取到正确的权限作用域了。
内容的提问来源于stack exchange,提问作者S.B
相关产品推荐
相关产品推荐

