You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.02 01:07:09