Java 后端面试题库 / 全部题解免费阅读理解原理,有条理地回答

FastAPI BackgroundTasks 什么时间运行?

查看完整题解

参考回答

直接回答

将函数与参数交给 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))

相关题:第 65 题、第 66 题、第 69 题、第 73 题。

这道题,你掌握得怎么样?

掌握程度由你主动标记,阅读和收藏不会自动改变状态。