Coverage for fastapi/background.py: 100%

7 statements  

« prev     ^ index     » next       coverage.py v7.6.1, created at 2024-08-08 03:53 +0000

1from typing import Any, Callable 1abcde

2 

3from starlette.background import BackgroundTasks as StarletteBackgroundTasks 1abcde

4from typing_extensions import Annotated, Doc, ParamSpec 1abcde

5 

6P = ParamSpec("P") 1abcde

7 

8 

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. 

13 

14 Read more about it in the 

15 [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/). 

16 

17 ## Example 

18 

19 ```python 

20 from fastapi import BackgroundTasks, FastAPI 

21 

22 app = FastAPI() 

23 

24 

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) 

29 

30 

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 """ 

37 

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. 

45 

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. 

55 

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