VB.net 2010 视频教程 VB.net 2010 视频教程 python基础视频教程
SQL Server 2008 视频教程 c#入门经典教程 Visual Basic从门到精通视频教程
当前位置:
首页 > temp > python入门教程 >
  • FastAPI 学习之路(四十)后台任务

 我们在实际的开发中,都会遇到,我们要执行的一些任务很耗时,但是呢,对于前端呢,没必要进行等待。比如发送邮件,读取文件。我们在fastapi如何实现呢。

        其实很简单,fastapi已经给我们封装好一个现成的模块,我们直接调用使用即可,非常方便。我们举一个简单例子演示下

 

复制代码
from fastapi import FastAPI,BackgroundTasks
import time
app = FastAPI(docs_url="/openapi",
              redoc_url="/apidoc")

def write_notification(email: str, message=""):
    time.sleep(200)
    with open("log.txt", mode="w") as email_file:
        content = f"name {email}: {message}"
        email_file.write(content)
@app.post("/sendtxt/")
async def sendtxt(email: str, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="不关注")
    return {"message": "在后台读写"}
复制代码

 我们可以去测试下

 

 我们的接口处理完成,但是后台任务还需要等待200s后才能执行完毕。所以我们不必等着任务全部执行完毕再返回,针对特别耗时的任务必须放在后台执行,不能占用前端的进程,不然会影响用户体验和接口返回的。

 

来源:https://www.cnblogs.com/leiziv5/p/15416828.html


相关教程