import uvicorn
from fastapi import FastAPI,BackgroundTasks
import asyncio
import time
import datetime
app = FastAPI()
def write_to_file(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 index(background_task: BackgroundTasks):
background_task.add_task(write_to_file, "email", message="content")
return {"message": "ok"}
def run_server():
uvicorn.run(app, host="0.0.0.0", port=8000)
if __name__ == "__main__":
run_server()
使用 fastapi 的 BackgroundTasks 执行后台任务
于 2024-05-18 10:22:34 首次发布