FastAPI BackgroundTasks 什么时间运行?
先说出你的答案
定义边界、关键机制、一个反例;P8题再补容量、失败与验证。
查看完整题解
参考回答
直接回答
将函数与参数交给 BackgroundTasks.add_task,FastAPI 会在该响应发出后执行任务。它适合小型、可与请求解耦的操作,不需要单独搭一套任务队列。
讲清原理
任务仍在应用进程里,进程退出可能中断或丢失。传简单参数或资源 ID。任务需要数据库时自行获取会话,别依赖请求内即将关闭的对象。
例子与易错点
示例验证端点先安排任务,任务随后在本地运行。TestClient 等整个 ASGI 调用结束才返回,因此它读到结果时,任务已经执行完。
from fastapi import BackgroundTasks, FastAPI
from fastapi.testclient import TestClient
events = []
app = FastAPI()
def record_notification(item_id):
events.append(f"recorded {item_id}")
@app.post("/notifications", status_code=202)
def enqueue(tasks: BackgroundTasks):
tasks.add_task(record_notification, 7)
events.append("scheduled")
return {"status": "accepted"}
async def observe(scope, receive, send):
async def capture(message):
await send(message)
if message["type"] == "http.response.body" and not message.get("more_body"):
events.append("response sent")
await app(scope, receive, capture)
with TestClient(observe) as client:
reply = client.post("/notifications")
assert reply.status_code == 202
assert events == ["scheduled", "response sent", "recorded 7"]
print(" → ".join(events))
和评分标准对照,你能独立回答到哪一步?
自评会安排下一次复习,不保存你的口述内容。
这道题,你掌握得怎么样?
掌握程度由你主动标记,阅读和收藏不会自动改变状态。