即发即忘: 后台任务
即发即忘:后台任务
Section titled “即发即忘:后台任务”有时,API 请求会触发需要时间才能完成的操作,例如发送确认邮件、处理视频文件或进行大量数据计算。如果让用户等待这些任务完成,你的 API 会显得缓慢且无响应。
FastAPI 提供了一个简单的机制来解决这个问题:后台任务 (Background Tasks)。这允许你立即向用户返回响应,而服务器继续在后台处理耗时的逻辑。
使用 BackgroundTasks 类
Section titled “使用 BackgroundTasks 类”要使用此功能,只需在你的路径操作函数中声明一个类型为 BackgroundTasks 的参数。对于简单的用例,你无需安装额外的库(如 Celery);它已内置于 FastAPI 中(通过 Starlette)。
你不是直接调用你的耗时函数,而是使用 background_tasks 对象的 .add_task() 方法。你需要传入函数引用以及它所需的任何参数。
示例:发送通知
Section titled “示例:发送通知”让我们模拟发送一封电子邮件通知。我们定义一个标准的 Python 函数来处理逻辑,然后将其调度到我们的端点中。
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
# This is our heavy task# 这是我们的耗时任务def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content)
@app.post("/send-notification/{email}")def send_notification(email: str, background_tasks: BackgroundTasks): # Schedule the task # 安排任务 background_tasks.add_task(write_notification, email, message="some notification")
# Return the response immediately # 立即返回响应 return {"message": "Notification sent in the background"}当客户端调用 /send-notification/user@example.com 时:
send_notification函数执行。- 任务被添加到队列中。
- FastAPI 向客户端发送 JSON 响应
{"message": "Notification sent in the background"}。 - 在响应发送之后,
write_notification函数在服务器上运行。
这种“即发即忘”(Fire and Forget)模式确保你的 API 保持快速响应,并提供更好的用户体验。