首页 > 解决方案 > FastApi 后台任务杀死

问题描述

有没有办法从 DELETE 端点结束我在 POST 中添加的 FastApi BackgroundTask?

例如:以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"}

永久终止write_notifaction作为后台任务添加的所有未完成调用的正确方法是什么?

标签: pythonmultithreadingbackgroundfastapi

解决方案


我认为目前在 FastApi 中默认情况下不可能有一个优雅的解决方案。
您可以使用Celery来完成此任务。

看看这个例子。他们解决了 Celery 与 BackgroundTasks 之间的区别。

此外,您可以在此处找到有关此主题的更多详细信息。


推荐阅读