📝 Add a section on handling errors inside background tasks by tsayin4 · Pull Request #16467 · fastapi/fastapi · GitHub
Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions docs/en/docs/tutorial/background-tasks.md
25 changes: 25 additions & 0 deletions docs_src/background_tasks/tutorial003_py310.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import logging

from fastapi import BackgroundTasks, FastAPI

app = FastAPI()

logger = logging.getLogger(__name__)


def send_notification(email: str):
try:
write_notification(email)
except Exception:
logger.exception("Could not send the notification to %s", email)


def write_notification(email: str):
with open("log.txt", mode="w") as email_file:
email_file.write(f"notification for {email}")


@app.post("/send-notification/{email}")
async def send_notification_endpoint(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(send_notification, email)
return {"message": "Notification sent in the background"}
39 changes: 39 additions & 0 deletions tests/test_tutorial/test_background_tasks/test_tutorial003.py
Loading