python runtime_error ai_generated true

RuntimeError: Dependency 'get_db' returned a value that is not a valid dependency

ID: python/fastapi-dependency-cache-error

Also available as: JSON · Markdown · 中文
80%Fix Rate
83%Confidence
0Evidence
2025-09-01First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.9 active
3.10 active

Root Cause

FastAPI 依赖注入函数返回了非可调用的对象

generic

中文

FastAPI 依赖注入函数返回了非可调用的对象

Workarounds

  1. 95% success 确保依赖函数返回可调用对象或正确类型
    def get_db():
        return SessionLocal()  # 返回实例而非类
  2. 90% success 使用类作为依赖并正确配置
    class CommonQueryParams:
        def __init__(self, q: str = None):
            self.q = q
    @app.get('/items')
    def get_items(params: CommonQueryParams = Depends()):
        ...

Dead Ends

Common approaches that don't work:

  1. 在依赖函数中返回 None 80% fail

    None 不是有效依赖

  2. 使用类作为依赖但不实例化 70% fail

    FastAPI 需要可调用对象