Как добавить фоновые задачи при сбое запроса и возникновении HTTPException в FastAPI?Python

Программы на 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
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «Python»