Background Tasks -BackgroundTasks¶
You can declare a parameter in apath operation function or dependency function with the typeBackgroundTasks, and then you can use it to schedule the execution of background tasks after the response is sent.
You can import it directly fromfastapi:
fromfastapiimportBackgroundTasksfastapi.BackgroundTasks¶
BackgroundTasks(tasks=None) Bases:BackgroundTasks
A collection of background tasks that will be called after a response has beensent to the client.
Read more about it in theFastAPI docs for Background Tasks.
Example¶
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"}Source code instarlette/background.py
2728 | |
funcinstance-attribute¶
func=funcargsinstance-attribute¶
args=argskwargsinstance-attribute¶
kwargs=kwargsis_asyncinstance-attribute¶
is_async=is_async_callable(func)tasksinstance-attribute¶
tasks=list(tasks)iftaskselse[]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 theFastAPI docs for Background Tasks.
| PARAMETER | DESCRIPTION |
|---|---|
func | The function to call after the response is sent. It can be a regular TYPE: |
Source code infastapi/background.py
40414243444546474849505152535455565758596061 | |







