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