zoukankan      html  css  js  c++  java
  • 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后才能执行完毕。所以我们不必等着任务全部执行完毕再返回,针对特别耗时的任务必须放在后台执行,不能占用前端的进程,不然会影响用户体验和接口返回的。

  • 相关阅读:
    hdoj 5311 Hidden String(KMP)
    hdoj 1532 Drainage Ditches(最大网络流)
    ubuntu中php+mysql环境搭建
    android:clipToPadding 和 android:clipChildren
    Js实现动画框架
    JavaScript初步认识
    JavaScript鼠标进入与退出监听动画
    Android框架集合
    Android 6.0(Android M)动态授权
    Android应用申请ROOT权限
  • 原文地址:https://www.cnblogs.com/leiziv5/p/15416828.html
Copyright © 2011-2022 走看看