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

  • 相关阅读:
    openstack-1基础环境准备
    ELK补充之Filebeat
    ELK补充之logstash
    ELK
    dubbo
    zokeeper+kafka
    rabbitmq
    jenkins补充-编写自动化脚本实现devops 流水线和回滚等操作
    sonar
    python连接数据库之(连接MySQL)
  • 原文地址:https://www.cnblogs.com/leiziv5/p/15416828.html
Copyright © 2011-2022 走看看