Как добавить фоновые задачи при сбое запроса и возникновении HTTPException в FastAPI? ⇐ Python
Как добавить фоновые задачи при сбое запроса и возникновении HTTPException в FastAPI?
I was trying to generate logs when an exception occurs in my FastAPI endpoint using a Background task as:
from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(message=""): with open("log.txt", mode="w") as email_file: content = f"{message}" email_file.write(content) @app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: BackgroundTasks): if "hello" in email: background_tasks.add_task(write_notification, message="helloworld") raise HTTPException(status_code=500, detail="example error") background_tasks.add_task(write_notification, message="hello world.") return {"message": "Notification sent in the background"} However, the logs are not generated because according to the documentation here and here, a background task runs "only" after the return statement is executed.
Is there any workaround to this?
Источник: https://stackoverflow.com/questions/732 ... ised-in-fa
I was trying to generate logs when an exception occurs in my FastAPI endpoint using a Background task as:
from fastapi import BackgroundTasks, FastAPI app = FastAPI() def write_notification(message=""): with open("log.txt", mode="w") as email_file: content = f"{message}" email_file.write(content) @app.post("/send-notification/{email}") async def send_notification(email: str, background_tasks: BackgroundTasks): if "hello" in email: background_tasks.add_task(write_notification, message="helloworld") raise HTTPException(status_code=500, detail="example error") background_tasks.add_task(write_notification, message="hello world.") return {"message": "Notification sent in the background"} However, the logs are not generated because according to the documentation here and here, a background task runs "only" after the return statement is executed.
Is there any workaround to this?
Источник: https://stackoverflow.com/questions/732 ... ised-in-fa
-
- Похожие темы
- Ответы
- Просмотры
- Последнее сообщение
-
-
Как остановить фоновые задачи при корректном завершении работы FastAPI
Anonymous » » в форуме Python - 0 Ответы
- 30 Просмотры
-
Последнее сообщение Anonymous
-
-
-
Как использовать фоновые задачи внутри функции, вызываемой конечной точкой FastAPI?
Anonymous » » в форуме Python - 0 Ответы
- 13 Просмотры
-
Последнее сообщение Anonymous
-