Saltar al contenido

Tareas en segundo plano - BackgroundTasks

Puedes declarar un parámetro en una función de operación de ruta o función de dependencia con el tipo BackgroundTasks, y luego puedes usarlo para programar la ejecución de tareas en segundo plano después de que se envíe la respuesta.

Puedes importarlo directamente desde fastapi:

from fastapi import BackgroundTasks

fastapi.BackgroundTasks

BackgroundTasks(tasks=None)

Hereda de: BackgroundTasks

Una colección de tareas en segundo plano que serán llamadas después de que se haya enviado una respuesta al cliente.

Lee más sobre esto en la documentación de FastAPI para Tareas en segundo plano.

Ejemplo

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"}
Código fuente en starlette/background.py
def __init__(self, tasks: Sequence[BackgroundTask] | None = None):
    self.tasks = list(tasks) if tasks else []

func instance-attribute

func = func

args instance-attribute

args = args

kwargs instance-attribute

kwargs = kwargs

is_async instance-attribute

is_async = is_async_callable(func)

tasks instance-attribute

tasks = list(tasks) if tasks else []

add_task

add_task(func, *args, **kwargs)

Agrega una función para ser llamada en segundo plano después de que se envíe la respuesta.

Lee más sobre esto en la documentación de FastAPI para Tareas en segundo plano.

PARÁMETRO DESCRIPCIÓN
func

La función a llamar después de que se envíe la respuesta.

Puede ser una función def regular o una función async def.

TIPO: Callable[P, Any]

Código fuente en fastapi/background.py
def add_task(
    self,
    func: Annotated[
        Callable[P, Any],
        Doc(
            """
            The function to call after the response is sent.

            It can be a regular `def` function or an `async def` function.
            """
        ),
    ],
    *args: P.args,
    **kwargs: P.kwargs,
) -> None:
    """
    Add a function to be called in the background after the response is sent.

    Read more about it in the
    [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
    """
    return super().add_task(func, *args, **kwargs)