Background Tasks - BackgroundTasks¶
You can declare a parameter in a path operation function or dependency function with the type BackgroundTasks, and then you can use it to schedule the execution of background tasks after the response is sent.
You can import it directly from fastapi:
fromfastapiimport BackgroundTasks
fastapi.BackgroundTasks ¶
BackgroundTasks(tasks=None)
Bases: BackgroundTasks
A collection of background tasks that will be called after a response has been sent to the client.
Read more about it in the FastAPI docs for Background Tasks.
Example¶
fromfastapiimport BackgroundTasks, FastAPI
app = FastAPI()
defwrite_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 defsend_notification(email: str, background_tasks: BackgroundTasks):
background_tasks.add_task(write_notification, email, message="some notification")
return {"message": "Notification sent in the background"}
Source code in 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)
add_task ¶
add_task(func, *args, **kwargs)
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.
| PARAMETER | DESCRIPTION |
|---|---|
func
|
The function to call after the response is sent. It can be a regular
TYPE:
|
Source code in 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/).
"""
return super().add_task(func, *args, **kwargs)