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

如何在交互式Shell中使用FastAPI的Depends()注入依赖?

问题解答

核心原因

FastAPI的Depends只是框架用来标记依赖关系的标记器,本身不会自动实例化或注入依赖对象——只有当FastAPI框架在处理请求的上下文里时,才会自动解析并注入Depends标记的依赖。你直接在IPython里调用b(),框架完全没介入,所以a参数拿到的是Depends实例,自然会报AttributeError。

两种解决方式

1. 手动传递依赖(最简单直接)

既然框架没介入,直接给__call__方法传A的实例就行:

>>> from src.repositories import A, B
>>> b = B()
>>> b(A())  # 手动传入A的实例
hello
'hello'

2. 借助FastAPI的依赖解析机制实现自动注入

如果想让FastAPI帮你自动处理依赖注入,必须把代码放到FastAPI的上下文里运行,有两种实用方法:

方法一:用TestClient模拟请求

先把你的类和FastAPI应用绑定:

# src/repositories/__init__.py
from fastapi import FastAPI, Depends

class A:
    def greet(self) -> str:
        print('hello')
        return 'hello'

class B:
    def __call__(self, a: A = Depends()):
        return a.greet()

app = FastAPI()

# 定义一个接口,让FastAPI处理依赖
@app.get("/greet")
def get_greet(result: str = Depends(B())):
    return result

然后在IPython里用TestClient调用接口:

>>> from fastapi.testclient import TestClient
>>> from src.repositories import app
>>> client = TestClient(app)
>>> response = client.get("/greet")
hello
>>> response.json()
'hello'
方法二:手动调用FastAPI的依赖解析工具

如果不想写接口,可以直接用FastAPI内部的依赖解析函数resolve_dependencies(注意这是异步操作,IPython支持直接用await):

>>> from fastapi.dependencies.utils import resolve_dependencies
>>> from fastapi import Request
>>> from src.repositories import A, B
>>>
>>> # 创建一个空的请求上下文(FastAPI依赖解析需要这个)
>>> request = Request(scope={"type": "http"})
>>>
>>> # 解析B.__call__方法的依赖
>>> b = B()
>>> dependencies, _, _ = await resolve_dependencies(
...     depends=b.__call__.__annotations__,
...     request=request,
...     dependency_overrides={}
... )
>>>
>>> # 用解析好的依赖调用b()
>>> b(**dependencies)
hello
'hello'

内容的提问来源于stack exchange,提问作者HyeonJunOh

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 09:20:13