如何在交互式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
相关产品推荐
相关产品推荐

