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

其他格式: JSON · Markdown 中文 · English
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.

generic

解决方案

  1. 100% 成功率 Define a proper dependency function
    def get_db():
        return db_session
    
    @app.get('/items')
    def read_items(db=Depends(get_db)):
        ...
  2. 90% 成功率 Use a class as a dependency with __call__
    class DBSession:
        def __call__(self):
            return db_session
    
    app.dependency_overrides[get_db] = DBSession()

无效尝试

常见但无效的做法:

  1. Passing a string or integer as a dependency 100% 失败

    Must be a callable.

  2. Using a class without __call__ 80% 失败

    Classes must be instantiable or have __call__.