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.
fromfastapiimportBackgroundTasks,FastAPIapp=FastAPI()defwrite_notification(email:str,message=""):withopen("log.txt",mode="w")asemail_file:content=f"notification for {email}: {message}"email_file.write(content)@app.post("/send-notification/{email}")asyncdefsend_notification(email:str,background_tasks:BackgroundTasks):background_tasks.add_task(write_notification,email,message="some notification")return{"message":"Notification sent in the background"}
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
defadd_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/). """returnsuper().add_task(func,*args,**kwargs)