import uvicorn
from fastapi import FastAPI,BackgroundTasks
import asyncio
import time
import datetime
app = FastAPI()
def write_notification(email: str, message: str = ""):
# 1、模拟和邮件服务器建立连接
time.sleep(3)
with open("text.txt", mode="a+") as f:
# 2、模拟发送邮件
content = f"message is {message}"+datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")+"\n"
f.write(content)
print(content)
@app.get("/")
async def root(background_task: BackgroundTasks):
background_task.add_task(write_notification, "email", message="test_message")
return {"message": "Hello, World!"}
def run_server():
uvicorn.run(app, host="0.0.0.0", port=8000)
if __name__ == "__main__":
run_server()
Fastapi BackgroundTasks实现
-
在starlette的response.py里
image.png
-
Response类的
__call__
方法, 会调用self.background
self.background
是一个BackgroundTasks
类
这个类有一个add_task
方法, 就是官方文档里的把后台函数添加到BackgroundTasks
里的 -
然后, 这个
__call__
方法循环取出每一个task最后在这里真正的用心的线程来跑后台任务
-
用的是anyio来起的线程