Coverage for fastapi/background.py: 100%
8 statements
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
« prev ^ index » next coverage.py v7.6.1, created at 2025-12-04 08:29 +0000
1from typing import Any, Callable 1abcdefg
3from annotated_doc import Doc 1abcdefg
4from starlette.background import BackgroundTasks as StarletteBackgroundTasks 1abcdefg
5from typing_extensions import Annotated, ParamSpec 1abcdefg
7P = ParamSpec("P") 1abcdefg
10class BackgroundTasks(StarletteBackgroundTasks): 1abcdefg
11 """
12 A collection of background tasks that will be called after a response has been
13 sent to the client.
15 Read more about it in the
16 [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
18 ## Example
20 ```python
21 from fastapi import BackgroundTasks, FastAPI
23 app = FastAPI()
26 def write_notification(email: str, message=""):
27 with open("log.txt", mode="w") as email_file:
28 content = f"notification for {email}: {message}"
29 email_file.write(content)
32 @app.post("/send-notification/{email}")
33 async def send_notification(email: str, background_tasks: BackgroundTasks):
34 background_tasks.add_task(write_notification, email, message="some notification")
35 return {"message": "Notification sent in the background"}
36 ```
37 """
39 def add_task( 1abcdefg
40 self,
41 func: Annotated[
42 Callable[P, Any],
43 Doc(
44 """
45 The function to call after the response is sent.
47 It can be a regular `def` function or an `async def` function.
48 """
49 ),
50 ],
51 *args: P.args,
52 **kwargs: P.kwargs,
53 ) -> None:
54 """
55 Add a function to be called in the background after the response is sent.
57 Read more about it in the
58 [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
59 """
60 return super().add_task(func, *args, **kwargs) 1hijklmnopqrstuvwxyzABCDEFGHI