今天主要说后台任务,它主要就是在返回响应后运行任务。
对于需要在请求之后发生的操作很有用,但客户端实际上不必在接收响应之前等待操作完成。
这包括,例如:
- 电子邮件发送的通知,需要连接电子邮件服务器
- 很慢的数据文件处理,因文件大写入时太慢
使用BackgroundTasks
首先,导入BackgroundTasks
其次在路径操作函数中定义一个参数,其类型声明为:BackgroundTasks
from fastapi import BackgroundTasks, FastAPI
app = FastAPI()
def write_file(data: str):
with open("log.txt", mode="w") as w:
w.write(data)
@app.post("/write-file/")
async def send_notification(data: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, data)
return {"message": "Notification sent in the background"}
在上述示例中,消息将在发送响应后log.txt写入文件。
如果请求成功,它将在后台任务中写入日志。
然后在路径操作函数中生成一个后台任务将使用data数据写入一条消息。