怎样用 yield 依赖管理 FastAPI 数据库会话?
查看完整题解
参考回答
直接回答
依赖创建 Session 后 yield 给路由,退出时关闭 Session。写入应由业务在合适时刻提交并处理失败。关闭用来释放资源,不能等同于提交。
讲清原理
当前 FastAPI 可用 Depends(scope="function") 在响应送出前清理 yield 依赖;默认请求作用域在响应发送后清理。流式生成若还用数据库,必须按实际生命周期设计。
例子与易错点
示例记录会话打开和关闭,并测试正常请求与 404 后都完成清理。后台任务通常需要独立获得会话。
from typing import Annotated
from fastapi import Depends, FastAPI, HTTPException
from fastapi.responses import StreamingResponse
from fastapi.testclient import TestClient
from sqlalchemy import create_engine, text
from sqlalchemy.orm import Session
from sqlalchemy.pool import StaticPool
engine = create_engine("sqlite://", poolclass=StaticPool,
connect_args={"check_same_thread": False})
app = FastAPI()
events = []
def database():
try:
with Session(engine) as session:
events.append("open")
yield session
finally:
events.append("closed")
@app.get("/items/{item_id}")
def item(item_id: int, db: Annotated[Session, Depends(database)]):
if item_id != 1:
raise HTTPException(404, "item not found")
return {"id": db.execute(text("SELECT 1")).scalar_one()}
@app.get("/plain")
def plain(db: Annotated[Session, Depends(database, scope="function")]):
assert db.execute(text("SELECT 1")).scalar_one() == 1
def stream():
events.append("stream")
yield b"ready"
return StreamingResponse(stream(), media_type="text/plain")
with TestClient(app) as client:
assert client.get("/items/1").json() == {"id": 1}
assert client.get("/items/2").status_code == 404
assert events == ["open", "closed", "open", "closed"]
events.clear()
assert client.get("/plain").text == "ready"
assert events == ["open", "closed", "stream"]
print("closed after 200 and 404; function scope closed before stream")
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。