fastapi 后台服务

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, background_tasks: BackgroundTasks):
    background_tasks.add_task(write_notification, email, message="some notification")
    return {"message": "Notification sent in the background"}







# 在最下面加上 这一句
if __name__ == "__main__":
    import uvicorn
    import os
    uvicorn.run(app=f"{os.path.basename(__file__).split('.')[0]}:app",
                host="0.0.0.0", port=9114, reload=False, )




原理是发送请求后, 给一个count的id, 然后维护一个字典, 用户输入id, 返回跑完后写入文件的地址即可. 然后用户就去地址下载结果了.

posted on 2025-10-20 10:40  张博的博客  阅读(8)  评论(0)    收藏  举报

导航