定义在返回响应后后台运行的任务,例如像发送邮件这种耗时动作
- 在路径操作函数中导入BackgroundTasks并定义一个参数,其类型声明为:BackgroundTasks
- 通过.add_task()添加任务
add_task()作为参数接收:
- 要在后台运行的任务函数 ( write_notification)。
- 后面参数为任务函数的所需参数
from fastapi import FastAPI, HTTPException, Request, BackgroundTasks, status
from fastapi.responses import JSONResponse
import uvicorn
import time
app = FastAPI()
def write_notification(email: str, message=""):
with open('log.txt', "a") as email_file:
time.sleep(3)
content = f"输入的邮箱是: {email}, 发送的消息是: {message} \n"
email_file.write(content)
@app.post("/send_nitification/{email}")
async def send_nitification(email: str, backgroud_task: BackgroundTasks):
backgroud_task.add_task(write_notification, email, message="这是发送的消息")
return JSONResponse(status_code=status.HTTP_200_OK,
content={
"code": 200,
"msg": "消息正在后台执行"
})
if __name__ == "__main__":
uvicorn.run(
app="error_handler:app",
host="127.0.0.1",
port=8080,
reload=True,
debug=True,
log_level="debug",
access_log=True,
use_colors=True
)