Fastapi Background Tasks
Background Tasks 后台任务 你可以定义一个在返回响应之后运行的后台任务。 这对请求之后执行一些操作十分有用,客户端无需一直等待操作任务完成再接收响应。 这包含一些例子: 执行操作后发送电子邮件 由于连接邮件服务器并发送邮件一般会比较“慢”(几秒钟),你可以立刻返回响应并在后台发送邮件请求。 处理数据 例如,你收到了一个文件需要缓慢处理,你可以返回一个 “Accepted” 响应 (HTTP 202) 并在后台处理文件。 Using Background Tasks 使用后台任务 首先要导入 BackgroundTasks 并在执行函数中定义一个路径参数,使用 BackgroundTasks 类型声明。 from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(email: str, message=""): with open("log.txt", mode="w") as email_file: content = f"notification for {email}: {message}" email_file.write(content) @app.post("/send-notification/{email}") async def send_notification(email: str, backgroud_tasks: Background(Tasks): # Add parameter here background_tasks.add_task(write_notification, email, message="some notification") # add backgroud task here return {"message": "Notification sent in the background"} Create a task function 创建任务函数 创建一个函数放到后台运行,只是一个接收参数的基本函数,可以是 async def 或者就普通的 def 函数,FastAPI 会正确的处理它。 在这个例子中的任务函数将会编写文件,并且写入操作不使用 async 或 await 故使用 def 定义了一个基本的函数。 ...