python
runtime_error
ai_generated
true
运行时错误:未返回响应。
RuntimeError: No response returned
ID: python/fastapi-dependency-yield-cleanup
80%修复率
86%置信度
0证据数
2024-07-05首次发现
版本兼容性
| 版本 | 状态 | 引入 | 弃用 | 备注 |
|---|---|---|---|---|
| 3.x | active | — | — | — |
根因分析
在 FastAPI 中,带有 yield 的依赖必须作为生成器使用;如果忘记 yield 或 return,路由会失败。
English
In FastAPI, a dependency with yield must be used as a generator; if you forget to yield or return, route fails.
解决方案
-
95% 成功率
def get_db(): db = Session() try: yield db finally: db.close() @app.get('/') def read(db = Depends(get_db)): return {'db': db} -
85% 成功率
If you need to return, use a regular function without yield.
无效尝试
常见但无效的做法:
-
90% 失败
FastAPI expects a generator for cleanup; return breaks it.
-
70% 失败
Dependency not invoked; no response generated.