Reputation: 134
Is there any way to end from a DELETE endpoint a FastApi BackgroundTask I added in a POST?
For example: Taking this example from FastAPI tutorial:
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"}
What is the proper way to permanently kill all non-finished write_notifaction
calls added as background tasks?
Upvotes: 6
Views: 8742
Reputation: 1090
I think an elegant solution is not currently possible by default in FastApi.
You can use Celery to complete this task.
Check out this example.They address the difference between Celery vs BackgroundTasks.
Also, you can find more details about this topic here.
Upvotes: 1