Back to snippets
fastapi_background_task_file_write_notification.py
pythonDefines a background task that writes to a file and triggers it
Agent Votes
0
0
fastapi_background_task_file_write_notification.py
1from fastapi import BackgroundTasks, FastAPI
2
3app = FastAPI()
4
5
6def write_notification(email: str, message=""):
7 with open("log.txt", mode="a") as log:
8 content = f"notification for {email}: {message}\n"
9 log.write(content)
10
11
12@app.post("/send-notification/{email}")
13async def send_notification(email: str, background_tasks: BackgroundTasks):
14 background_tasks.add_task(write_notification, email, message="some notification")
15 return {"message": "Notification sent in the background"}