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