python:Fastapi - BackgroundTasks (后台任务)

今天主要说后台任务,它主要就是在返回响应后运行任务。

对于需要在请求之后发生的操作很有用,但客户端实际上不必在接收响应之前等待操作完成。

这包括,例如:

  • 电子邮件发送的通知,需要连接电子邮件服务器
  • 很慢的数据文件处理,因文件大写入时太慢

使用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数据写入一条消息。

<

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值