background.py 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. from __future__ import annotations
  2. from collections.abc import Callable, Sequence
  3. from typing import Any, ParamSpec
  4. from starlette._utils import is_async_callable
  5. from starlette.concurrency import run_in_threadpool
  6. P = ParamSpec("P")
  7. class BackgroundTask:
  8. def __init__(self, func: Callable[P, Any], *args: P.args, **kwargs: P.kwargs) -> None:
  9. self.func = func
  10. self.args = args
  11. self.kwargs = kwargs
  12. self.is_async = is_async_callable(func)
  13. async def __call__(self) -> None:
  14. if self.is_async:
  15. await self.func(*self.args, **self.kwargs)
  16. else:
  17. await run_in_threadpool(self.func, *self.args, **self.kwargs)
  18. class BackgroundTasks(BackgroundTask):
  19. def __init__(self, tasks: Sequence[BackgroundTask] | None = None):
  20. self.tasks = list(tasks) if tasks else []
  21. def add_task(self, func: Callable[P, Any], *args: P.args, **kwargs: P.kwargs) -> None:
  22. task = BackgroundTask(func, *args, **kwargs)
  23. self.tasks.append(task)
  24. async def __call__(self) -> None:
  25. for task in self.tasks:
  26. await task()