python runtime_error ai_generated true

RuntimeError: No response returned

ID: python/fastapi-dependency-yield-cleanup

Also available as: JSON · Markdown · 中文
80%Fix Rate
86%Confidence
0Evidence
2024-07-05First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
3.x active

Root Cause

In FastAPI, a dependency with yield must be used as a generator; if you forget to yield or return, route fails.

generic

中文

在 FastAPI 中,带有 yield 的依赖必须作为生成器使用;如果忘记 yield 或 return,路由会失败。

Workarounds

  1. 95% success
    def get_db():
        db = Session()
        try:
            yield db
        finally:
            db.close()
    
    @app.get('/')
    def read(db = Depends(get_db)):
        return {'db': db}
  2. 85% success
    If you need to return, use a regular function without yield.

Dead Ends

Common approaches that don't work:

  1. 90% fail

    FastAPI expects a generator for cleanup; return breaks it.

  2. 70% fail

    Dependency not invoked; no response generated.