You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

60 lines
1.7 KiB

  1. from typing import Any, Callable
  2. from starlette.background import BackgroundTasks as StarletteBackgroundTasks
  3. from typing_extensions import Annotated, Doc, ParamSpec
  4. P = ParamSpec("P")
  5. class BackgroundTasks(StarletteBackgroundTasks):
  6. """
  7. A collection of background tasks that will be called after a response has been
  8. sent to the client.
  9. Read more about it in the
  10. [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
  11. ## Example
  12. ```python
  13. from fastapi import BackgroundTasks, FastAPI
  14. app = FastAPI()
  15. def write_notification(email: str, message=""):
  16. with open("log.txt", mode="w") as email_file:
  17. content = f"notification for {email}: {message}"
  18. email_file.write(content)
  19. @app.post("/send-notification/{email}")
  20. async def send_notification(email: str, background_tasks: BackgroundTasks):
  21. background_tasks.add_task(write_notification, email, message="some notification")
  22. return {"message": "Notification sent in the background"}
  23. ```
  24. """
  25. def add_task(
  26. self,
  27. func: Annotated[
  28. Callable[P, Any],
  29. Doc(
  30. """
  31. The function to call after the response is sent.
  32. It can be a regular `def` function or an `async def` function.
  33. """
  34. ),
  35. ],
  36. *args: P.args,
  37. **kwargs: P.kwargs,
  38. ) -> None:
  39. """
  40. Add a function to be called in the background after the response is sent.
  41. Read more about it in the
  42. [FastAPI docs for Background Tasks](https://fastapi.tiangolo.com/tutorial/background-tasks/).
  43. """
  44. return super().add_task(func, *args, **kwargs)