async_utils.py 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import inspect
  2. import typing as t
  3. from functools import wraps
  4. from .utils import _PassArg
  5. from .utils import pass_eval_context
  6. V = t.TypeVar("V")
  7. def async_variant(normal_func): # type: ignore
  8. def decorator(async_func): # type: ignore
  9. pass_arg = _PassArg.from_obj(normal_func)
  10. need_eval_context = pass_arg is None
  11. if pass_arg is _PassArg.environment:
  12. def is_async(args: t.Any) -> bool:
  13. return t.cast(bool, args[0].is_async)
  14. else:
  15. def is_async(args: t.Any) -> bool:
  16. return t.cast(bool, args[0].environment.is_async)
  17. @wraps(normal_func)
  18. def wrapper(*args, **kwargs): # type: ignore
  19. b = is_async(args)
  20. if need_eval_context:
  21. args = args[1:]
  22. if b:
  23. return async_func(*args, **kwargs)
  24. return normal_func(*args, **kwargs)
  25. if need_eval_context:
  26. wrapper = pass_eval_context(wrapper)
  27. wrapper.jinja_async_variant = True
  28. return wrapper
  29. return decorator
  30. _common_primitives = {int, float, bool, str, list, dict, tuple, type(None)}
  31. async def auto_await(value: t.Union[t.Awaitable["V"], "V"]) -> "V":
  32. # Avoid a costly call to isawaitable
  33. if type(value) in _common_primitives:
  34. return t.cast("V", value)
  35. if inspect.isawaitable(value):
  36. return await t.cast("t.Awaitable[V]", value)
  37. return t.cast("V", value)
  38. async def auto_aiter(
  39. iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  40. ) -> "t.AsyncIterator[V]":
  41. if hasattr(iterable, "__aiter__"):
  42. async for item in t.cast("t.AsyncIterable[V]", iterable):
  43. yield item
  44. else:
  45. for item in t.cast("t.Iterable[V]", iterable):
  46. yield item
  47. async def auto_to_list(
  48. value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",
  49. ) -> t.List["V"]:
  50. return [x async for x in auto_aiter(value)]