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
:
from fastapi import 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¶
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"}
PARAMETER | DESCRIPTION |
---|---|
tasks
|
TYPE:
|
Source code in starlette/background.py
32 33 |
|
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:
|
*args
|
TYPE:
|
**kwargs
|
TYPE:
|
Source code in fastapi/background.py
38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
|