Movatterモバイル変換


[0]ホーム

URL:


Saltar a contenido
Follow@fastapi onTwitter to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
You can now sponsorFastAPI 🍰
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor
sponsor

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:

fromfastapiimportBackgroundTasks

fastapi.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"}
PARAMETERDESCRIPTION
tasks

TYPE:Sequence[BackgroundTask] | NoneDEFAULT:None

Source code instarlette/background.py
3233
def__init__(self,tasks:typing.Sequence[BackgroundTask]|None=None):self.tasks=list(tasks)iftaskselse[]

funcinstance-attribute

func=func

argsinstance-attribute

args=args

kwargsinstance-attribute

kwargs=kwargs

is_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.

PARAMETERDESCRIPTION
func

The function to call after the response is sent.

It can be a regulardef function or anasync def function.

TYPE:Callable[P,Any]

*args

TYPE:argsDEFAULT:()

**kwargs

TYPE:kwargsDEFAULT:{}

Source code infastapi/background.py
38394041424344454647484950515253545556575859
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)

[8]ページ先頭

©2009-2026 Movatter.jp