参考
https://fastapi.tiangolo.com/zh/tutorial/background-tasks/
应用场景
对需要在请求之后执行的操作很有用,但客户端不必在接收响应之前等待操作完成
例子
- 发送电子邮件通知
- 处理数据
示例代码
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
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}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}
注意事项
需要执行繁重的后台计算,并且不一定需要由同一进程运行(例如,您不需要共享内存、变量等),那么使用其他更大的工具(如 Celery
)可能更好。