Movatterモバイル変換


[0]ホーム

URL:


Ana içeriğe geç
Join theFastAPI Cloud waiting list 🚀
Follow@fastapi onX (Twitter) to stay updated
FollowFastAPI onLinkedIn to stay updated
Subscribe to theFastAPI and friends newsletter 🎉
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"}
Source code instarlette/background.py
2728
def__init__(self,tasks: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]

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