zoukankan      html  css  js  c++  java
  • FastAPI异步任务系列(一) FastAPI后台任务

    一、后台任务使用  

    你可以定义后台任务在后台响应之后继续运行,这对于在请求之后去做一些操作时有用的,但是客户端不会真正的等待响应中操作的完成。这包括,例如:

    • 执行操作后发送电子邮件通知
    • 处理数据,比如,后台接收一个文件需要处理,但是可以先给客户端返回响应,然后后台接着处理

    1、使用后台任务

    首先,导入BackgroundTask以及在路径操作函数中定义一个参数,并且声明类型为BackgroundTasks:

    from fastapi import BackgroundTasks, FastAPI
    
    app = FastAPI()
    
    
    @app.post("/send-notification/{email}")
    async def send_notification(email: str, background_tasks: BackgroundTasks):
        pass

    FastAPI将会创建BackgroundTasks类型的对象,并且将其当作参数传递。

    2、创建一个任务函数

    创建一个函数作为后台任务,它是一个可以接收参数的标准函数,可以使用async异步方式或者正常函数方式,FastAPI知道应该如何使用它,在这个例子中,这个后台任务将会写一个文件:

    from fastapi import BackgroundTasks, FastAPI
    
    app = FastAPI()
    
    
    def write_notification(email: str, message=""):
        with open("log.txt", mode="w") as f:
            f.write(f"notification for {email}:{message}")
    
    
    @app.post("/send-notification/{email}")
    async def send_notification(email: str, background_tasks: BackgroundTasks):
        pass

    3、添加后台任务

    在路径操作函数中,通过".add_task()"函数将任务函数添加到后台任务对象中:

    from fastapi import BackgroundTasks, FastAPI
    
    app = FastAPI()
    
    
    def write_notification(email: str, message=""):
        with open("log.txt", mode="w") as f:
            f.write(f"notification for {email}:{message}")
    
    
    @app.post("/send-notification/{email}")
    async def send_notification(email: str, background_tasks: BackgroundTasks):
        background_tasks.add_task(write_notification, email, message="notification...")
        return {"message": "Notification sent in the background"}

    .add_task()接收的参数:

    • 一个在后台运行的任务函数(write_notification)
    • 按照顺寻传递的一系列参数(email)
    • 任何的关键字参数(message="notification...")

    二、依赖注入

    在依赖注入系统中也可以使用后台任务,你可以声明一个BackgroundTasks类型的参数,在路径操作函数、依赖项、子依赖项中等。

    from fastapi import BackgroundTasks, FastAPI, Depends
    from typing import Optional
    
    app = FastAPI()
    
    
    def write_log(message: str):
        with open("log.txt", mode="a") as f:
            f.write(message)
    
    
    def get_query(background_tasks: BackgroundTasks, q: Optional[str] = None):
        if q:
            message = f"found query:{q}
    "
            background_tasks.add_task(write_log, message)
        return q
    
    
    @app.post("/dependency/background_tasks")
    async def write_log(q: str = Depends(get_query)):
        if q:
            return {"message": "write log in the background"}
    作者:iveBoy
    本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须在文章页面给出原文连接,否则保留追究法律责任的权利。
  • 相关阅读:
    微信坚硬的后脚跟
    [项目整理]Win32,MFC的可执行文件只能运行一次
    美司法部索要维基解密志愿者谷歌账户内容
    QML性能
    OSGi 的核心配置、动态化及问题
    OSGi 的由来和本质特性
    机器视觉与计算机视觉
    人工智能与深度学习
    活着就能改变世界
    选择与执行
  • 原文地址:https://www.cnblogs.com/shenjianping/p/14873320.html
Copyright © 2011-2022 走看看