python
type_error
ai_generated
true
FastAPI 错误:无效的依赖项:'get_db' 不是可调用对象或类。
fastapi.exceptions.FastAPIError: Invalid dependency: 'get_db' is not a callable or a class.
ID: python/fastapi-dependency-error
80%修复率
85%置信度
0证据数
2025-04-15首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
FastAPI 中的依赖项必须是可调用对象(函数或类),返回所需的值。
English
Dependencies in FastAPI must be callables (functions or classes) that return the required value.
解决方案
-
100% 成功率 Define a proper dependency function
def get_db(): return db_session @app.get('/items') def read_items(db=Depends(get_db)): ... -
90% 成功率 Use a class as a dependency with __call__
class DBSession: def __call__(self): return db_session app.dependency_overrides[get_db] = DBSession()
无效尝试
常见但无效的做法:
-
Passing a string or integer as a dependency
100% 失败
Must be a callable.
-
Using a class without __call__
80% 失败
Classes must be instantiable or have __call__.