Merge pull request #1392 from pallets/inline-async
Before adoption: this commit came in with the history the project adopted, so no landing records it.
async support doesn't require patching
authored by David Lord · committed by GitHub · parents a9b06f4, 1932ce3 · Browse files · 15 files·+713 added−856 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
15 files+713 added−856 removed
- tests:+255 added−262 removed
- other:+458 added−594 removed
Provenance
- Commit
9d4689b- Tree
240f231- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
a9b06f4- Parent 2
1932ce3
15 files changed+713 added−856 removed
modified:docs/intro.rst+2 added-2 removed
10 unmodified lines11 - Define and import macros within templates.12 - HTML templates can use autoescaping to prevent XSS from untrusted13 user input.14 - A sandboxed environment can safely render untrusted templates.15-- AsyncIO support for generating templates and calling async16- functions.15+- Async support for generating templates that automatically handle16+ sync and async functions without extra syntax.17 - I18N support with Babel.18 - Templates are compiled to optimized Python code just-in-time and19 cached, or can be compiled ahead-of-time.20 - Exceptions point to the correct line in templates to make debugging43 unmodified linesadded:src/jinja2/async_utils.py+76 added
1+import inspect2+import typing as t3+from functools import wraps4+5+from .utils import _PassArg6+from .utils import pass_eval_context7+8+if t.TYPE_CHECKING:9+ V = t.TypeVar("V")10+11+12+def async_variant(normal_func):13+ def decorator(async_func):14+ pass_arg = _PassArg.from_obj(normal_func)15+ need_eval_context = pass_arg is None16+17+ if pass_arg is _PassArg.environment:18+19+ def is_async(args):20+ return args[0].is_async21+22+ else:23+24+ def is_async(args):25+ return args[0].environment.is_async26+27+ @wraps(normal_func)28+ def wrapper(*args, **kwargs):29+ b = is_async(args)30+31+ if need_eval_context:32+ args = args[1:]33+34+ if b:35+ return async_func(*args, **kwargs)36+37+ return normal_func(*args, **kwargs)38+39+ if need_eval_context:40+ wrapper = pass_eval_context(wrapper)41+42+ wrapper.jinja_async_variant = True43+ return wrapper44+45+ return decorator46+47+48+async def auto_await(value):49+ if inspect.isawaitable(value):50+ return await value51+52+ return value53+54+55+async def auto_aiter(iterable):56+ if hasattr(iterable, "__aiter__"):57+ async for item in iterable:58+ yield item59+ else:60+ for item in iterable:61+ yield item62+63+64+async def auto_to_list(65+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",66+) -> "t.List[V]":67+ seq = []68+69+ if hasattr(value, "__aiter__"):70+ async for item in t.cast(t.AsyncIterable, value):71+ seq.append(item)72+ else:73+ for item in t.cast(t.Iterable, value):74+ seq.append(item)75+76+ return seqdeleted:src/jinja2/asyncfilters.py-261 removed
1-import typing2-import typing as t3-import warnings4-from functools import wraps5-from itertools import groupby6-7-from . import filters8-from .asyncsupport import auto_aiter9-from .asyncsupport import auto_await10-from .utils import _PassArg11-from .utils import pass_eval_context12-13-if t.TYPE_CHECKING:14- from .environment import Environment15- from .nodes import EvalContext16- from .runtime import Context17- from .runtime import Undefined18-19- V = t.TypeVar("V")20-21-22-async def auto_to_seq(23- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",24-) -> "t.List[V]":25- seq = []26-27- if hasattr(value, "__aiter__"):28- async for item in t.cast(t.AsyncIterable, value):29- seq.append(item)30- else:31- for item in t.cast(t.Iterable, value):32- seq.append(item)33-34- return seq35-36-37-async def async_select_or_reject(38- context: "Context",39- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",40- args: t.Tuple,41- kwargs: t.Dict[str, t.Any],42- modfunc: t.Callable[[t.Any], t.Any],43- lookup_attr: bool,44-) -> "t.AsyncIterator[V]":45- if value:46- func = filters.prepare_select_or_reject(47- context, args, kwargs, modfunc, lookup_attr48- )49-50- async for item in auto_aiter(value):51- if func(item):52- yield item53-54-55-def dual_filter(normal_func, async_func):56- pass_arg = _PassArg.from_obj(normal_func)57- wrapper_has_eval_context = False58-59- if pass_arg is _PassArg.environment:60- wrapper_has_eval_context = False61-62- def is_async(args):63- return args[0].is_async64-65- else:66- wrapper_has_eval_context = pass_arg is None67-68- def is_async(args):69- return args[0].environment.is_async70-71- @wraps(normal_func)72- def wrapper(*args, **kwargs):73- b = is_async(args)74-75- if wrapper_has_eval_context:76- args = args[1:]77-78- if b:79- return async_func(*args, **kwargs)80-81- return normal_func(*args, **kwargs)82-83- if wrapper_has_eval_context:84- wrapper = pass_eval_context(wrapper)85-86- wrapper.jinja_async_variant = True87- return wrapper88-89-90-def async_variant(original):91- def decorator(f):92- return dual_filter(original, f)93-94- return decorator95-96-97-def asyncfiltervariant(original):98- warnings.warn(99- "'asyncfiltervariant' is renamed to 'async_variant', the old"100- " name will be removed in Jinja 3.1.",101- DeprecationWarning,102- stacklevel=2,103- )104- return async_variant(original)105-106-107-@async_variant(filters.do_first)108-async def do_first(109- environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"110-) -> "t.Union[V, Undefined]":111- try:112- return t.cast("V", await auto_aiter(seq).__anext__())113- except StopAsyncIteration:114- return environment.undefined("No first item, sequence was empty.")115-116-117-@async_variant(filters.do_groupby)118-async def do_groupby(119- environment: "Environment",120- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",121- attribute: t.Union[str, int],122- default: t.Optional[t.Any] = None,123-) -> "t.List[t.Tuple[t.Any, t.List[V]]]":124- expr = filters.make_attrgetter(environment, attribute, default=default)125- return [126- filters._GroupTuple(key, await auto_to_seq(values))127- for key, values in groupby(sorted(await auto_to_seq(value), key=expr), expr)128- ]129-130-131-@async_variant(filters.do_join)132-async def do_join(133- eval_ctx: "EvalContext",134- value: t.Union[t.AsyncIterable, t.Iterable],135- d: str = "",136- attribute: t.Optional[t.Union[str, int]] = None,137-) -> str:138- return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)139-140-141-@async_variant(filters.do_list)142-async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":143- return await auto_to_seq(value)144-145-146-@async_variant(filters.do_reject)147-async def do_reject(148- context: "Context",149- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",150- *args: t.Any,151- **kwargs: t.Any,152-) -> "t.AsyncIterator[V]":153- return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)154-155-156-@async_variant(filters.do_rejectattr)157-async def do_rejectattr(158- context: "Context",159- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",160- *args: t.Any,161- **kwargs: t.Any,162-) -> "t.AsyncIterator[V]":163- return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)164-165-166-@async_variant(filters.do_select)167-async def do_select(168- context: "Context",169- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",170- *args: t.Any,171- **kwargs: t.Any,172-) -> "t.AsyncIterator[V]":173- return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)174-175-176-@async_variant(filters.do_selectattr)177-async def do_selectattr(178- context: "Context",179- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",180- *args: t.Any,181- **kwargs: t.Any,182-) -> "t.AsyncIterator[V]":183- return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)184-185-186-@typing.overload187-def do_map(188- context: "Context",189- value: t.Union[t.AsyncIterable, t.Iterable],190- name: str,191- *args: t.Any,192- **kwargs: t.Any,193-) -> t.Iterable:194- ...195-196-197-@typing.overload198-def do_map(199- context: "Context",200- value: t.Union[t.AsyncIterable, t.Iterable],201- *,202- attribute: str = ...,203- default: t.Optional[t.Any] = None,204-) -> t.Iterable:205- ...206-207-208-@async_variant(filters.do_map)209-async def do_map(context, value, *args, **kwargs):210- if value:211- func = filters.prepare_map(context, args, kwargs)212-213- async for item in auto_aiter(value):214- yield await auto_await(func(item))215-216-217-@async_variant(filters.do_sum)218-async def do_sum(219- environment: "Environment",220- iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",221- attribute: t.Optional[t.Union[str, int]] = None,222- start: "V" = 0, # type: ignore223-) -> "V":224- rv = start225-226- if attribute is not None:227- func = filters.make_attrgetter(environment, attribute)228- else:229-230- def func(x):231- return x232-233- async for item in auto_aiter(iterable):234- rv += func(item)235-236- return rv237-238-239-@async_variant(filters.do_slice)240-async def do_slice(241- value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",242- slices: int,243- fill_with: t.Optional[t.Any] = None,244-) -> "t.Iterator[t.List[V]]":245- return filters.do_slice(await auto_to_seq(value), slices, fill_with)246-247-248-ASYNC_FILTERS = {249- "first": do_first,250- "groupby": do_groupby,251- "join": do_join,252- "list": do_list,253- # we intentionally do not support do_last because it may not be safe in async254- "reject": do_reject,255- "rejectattr": do_rejectattr,256- "map": do_map,257- "select": do_select,258- "selectattr": do_selectattr,259- "sum": do_sum,260- "slice": do_slice,261-}deleted:src/jinja2/asyncsupport.py-249 removed
1-"""The code for async support. Importing this patches Jinja."""2-import asyncio3-import inspect4-from functools import update_wrapper5-6-from markupsafe import Markup7-8-from .environment import TemplateModule9-from .runtime import LoopContext10-from .utils import concat11-from .utils import internalcode12-from .utils import missing13-14-15-async def concat_async(async_gen):16- rv = []17-18- async def collect():19- async for event in async_gen:20- rv.append(event)21-22- await collect()23- return concat(rv)24-25-26-async def generate_async(self, *args, **kwargs):27- vars = dict(*args, **kwargs)28- try:29- async for event in self.root_render_func(self.new_context(vars)):30- yield event31- except Exception:32- yield self.environment.handle_exception()33-34-35-def wrap_generate_func(original_generate):36- def _convert_generator(self, loop, args, kwargs):37- async_gen = self.generate_async(*args, **kwargs)38- try:39- while 1:40- yield loop.run_until_complete(async_gen.__anext__())41- except StopAsyncIteration:42- pass43-44- def generate(self, *args, **kwargs):45- if not self.environment.is_async:46- return original_generate(self, *args, **kwargs)47- return _convert_generator(self, asyncio.get_event_loop(), args, kwargs)48-49- return update_wrapper(generate, original_generate)50-51-52-async def render_async(self, *args, **kwargs):53- if not self.environment.is_async:54- raise RuntimeError("The environment was not created with async mode enabled.")55-56- vars = dict(*args, **kwargs)57- ctx = self.new_context(vars)58-59- try:60- return await concat_async(self.root_render_func(ctx))61- except Exception:62- return self.environment.handle_exception()63-64-65-def wrap_render_func(original_render):66- def render(self, *args, **kwargs):67- if not self.environment.is_async:68- return original_render(self, *args, **kwargs)69- loop = asyncio.get_event_loop()70- return loop.run_until_complete(self.render_async(*args, **kwargs))71-72- return update_wrapper(render, original_render)73-74-75-def wrap_block_reference_call(original_call):76- @internalcode77- async def async_call(self):78- rv = await concat_async(self._stack[self._depth](self._context))79- if self._context.eval_ctx.autoescape:80- rv = Markup(rv)81- return rv82-83- @internalcode84- def __call__(self):85- if not self._context.environment.is_async:86- return original_call(self)87- return async_call(self)88-89- return update_wrapper(__call__, original_call)90-91-92-def wrap_macro_invoke(original_invoke):93- @internalcode94- async def async_invoke(self, arguments, autoescape):95- rv = await self._func(*arguments)96- if autoescape:97- rv = Markup(rv)98- return rv99-100- @internalcode101- def _invoke(self, arguments, autoescape):102- if not self._environment.is_async:103- return original_invoke(self, arguments, autoescape)104- return async_invoke(self, arguments, autoescape)105-106- return update_wrapper(_invoke, original_invoke)107-108-109-@internalcode110-async def get_default_module_async(self):111- if self._module is not None:112- return self._module113- self._module = rv = await self.make_module_async()114- return rv115-116-117-def wrap_default_module(original_default_module):118- @internalcode119- def _get_default_module(self, ctx=None):120- if self.environment.is_async:121- raise RuntimeError("Template module attribute is unavailable in async mode")122- return original_default_module(self, ctx)123-124- return _get_default_module125-126-127-async def make_module_async(self, vars=None, shared=False, locals=None):128- context = self.new_context(vars, shared, locals)129- body_stream = []130- async for item in self.root_render_func(context):131- body_stream.append(item)132- return TemplateModule(self, context, body_stream)133-134-135-def patch_template():136- from . import Template137-138- Template.generate = wrap_generate_func(Template.generate)139- Template.generate_async = update_wrapper(generate_async, Template.generate_async)140- Template.render_async = update_wrapper(render_async, Template.render_async)141- Template.render = wrap_render_func(Template.render)142- Template._get_default_module = wrap_default_module(Template._get_default_module)143- Template._get_default_module_async = get_default_module_async144- Template.make_module_async = update_wrapper(145- make_module_async, Template.make_module_async146- )147-148-149-def patch_runtime():150- from .runtime import BlockReference, Macro151-152- BlockReference.__call__ = wrap_block_reference_call(BlockReference.__call__)153- Macro._invoke = wrap_macro_invoke(Macro._invoke)154-155-156-def patch_filters():157- from .filters import FILTERS158- from .asyncfilters import ASYNC_FILTERS159-160- FILTERS.update(ASYNC_FILTERS)161-162-163-def patch_all():164- patch_template()165- patch_runtime()166- patch_filters()167-168-169-async def auto_await(value):170- if inspect.isawaitable(value):171- return await value172- return value173-174-175-async def auto_aiter(iterable):176- if hasattr(iterable, "__aiter__"):177- async for item in iterable:178- yield item179- return180- for item in iterable:181- yield item182-183-184-class AsyncLoopContext(LoopContext):185- _to_iterator = staticmethod(auto_aiter)186-187- @property188- async def length(self):189- if self._length is not None:190- return self._length191-192- try:193- self._length = len(self._iterable)194- except TypeError:195- iterable = [x async for x in self._iterator]196- self._iterator = self._to_iterator(iterable)197- self._length = len(iterable) + self.index + (self._after is not missing)198-199- return self._length200-201- @property202- async def revindex0(self):203- return await self.length - self.index204-205- @property206- async def revindex(self):207- return await self.length - self.index0208-209- async def _peek_next(self):210- if self._after is not missing:211- return self._after212-213- try:214- self._after = await self._iterator.__anext__()215- except StopAsyncIteration:216- self._after = missing217-218- return self._after219-220- @property221- async def last(self):222- return await self._peek_next() is missing223-224- @property225- async def nextitem(self):226- rv = await self._peek_next()227-228- if rv is missing:229- return self._undefined("there is no next item")230-231- return rv232-233- def __aiter__(self):234- return self235-236- async def __anext__(self):237- if self._after is not missing:238- rv = self._after239- self._after = missing240- else:241- rv = await self._iterator.__anext__()242-243- self.index0 += 1244- self._before = self._current245- self._current = rv246- return rv, self247-248-249-patch_all()modified:src/jinja2/compiler.py+7 added-8 removed
725 unmodified lines726 def visit_Template(self, node, frame=None):727 assert frame is None, "no root frame allowed"728 eval_ctx = EvalContext(self.environment, self.name)729 730- from .runtime import exported730+ from .runtime import exported, async_exported731 732- self.writeline("from __future__ import generator_stop") # Python < 3.7733- self.writeline("from jinja2.runtime import " + ", ".join(exported))734-732 if self.environment.is_async:736- self.writeline(737- "from jinja2.asyncsupport import auto_await, "738- "auto_aiter, AsyncLoopContext"739- )733+ exported_names = sorted(exported + async_exported)734+ else:735+ exported_names = sorted(exported)736 737+ self.writeline("from __future__ import generator_stop") # Python < 3.7738+ self.writeline("from jinja2.runtime import " + ", ".join(exported_names))739+740 # if we want a deferred initialization we cannot move the741 # environment into a local name742 envenv = "" if self.defer_init else ", environment=environment"743 1111 unmodified linesmodified:src/jinja2/environment.py+87 added-44 removed
43 unmodified lines44 from .runtime import Undefined45 from .utils import _PassArg46 from .utils import concat47 from .utils import consume48-from .utils import have_async_gen48 from .utils import import_string49 from .utils import internalcode50 from .utils import LRUCache51 from .utils import missing288 unmodified lines340 341 # load extensions342 self.extensions = load_extensions(self, extensions)343 345- self.enable_async = enable_async346- self.is_async = self.enable_async and have_async_gen347- if self.is_async:348- # runs patch_all() to enable async support349- from . import asyncsupport # noqa: F401350-344+ self.is_async = enable_async345 _environment_sanity_check(self)346 347 def add_extension(self, extension):348 """Adds an extension after the environment was created.763 unmodified lines1112 template.render({'knights': 'that say nih'})1113 1114 This will return the rendered template as a string.1115 """1122- vars = dict(*args, **kwargs)1116+ if self.environment.is_async:1117+ import asyncio1118+1119+ loop = asyncio.get_event_loop()1120+ return loop.run_until_complete(self.render_async(*args, **kwargs))1121+1122+ ctx = self.new_context(dict(*args, **kwargs))1123+1124 try:1124- return concat(self.root_render_func(self.new_context(vars)))1125+ return concat(self.root_render_func(ctx))1126 except Exception:1127 self.environment.handle_exception()1128 1128- def render_async(self, *args, **kwargs):1129+ async def render_async(self, *args, **kwargs):1130 """This works similar to :meth:`render` but returns a coroutine1131 that when awaited returns the entire rendered template string. This1132 requires the async feature to be enabled.1133 1134 Example usage::1135 1136 await template.render_async(knights='that say nih; asynchronously')1137 """1137- # see asyncsupport for the actual implementation1138- raise NotImplementedError(1139- "This feature is not available for this version of Python"1140- )1138+ if not self.environment.is_async:1139+ raise RuntimeError(1140+ "The environment was not created with async mode enabled."1141+ )1142 1143+ ctx = self.new_context(dict(*args, **kwargs))1144+1145+ try:1146+ return concat([n async for n in self.root_render_func(ctx)])1147+ except Exception:1148+ return self.environment.handle_exception()1149+1150 def stream(self, *args, **kwargs):1151 """Works exactly like :meth:`generate` but returns a1152 :class:`TemplateStream`.1153 """6 unmodified lines1160 a generator that yields one item after another as strings.1161 1162 It accepts the same arguments as :meth:`render`.1163 """1156- vars = dict(*args, **kwargs)1164+ if self.environment.is_async:1165+ import asyncio1166+1167+ loop = asyncio.get_event_loop()1168+ async_gen = self.generate_async(*args, **kwargs)1169+1170+ try:1171+ while True:1172+ yield loop.run_until_complete(async_gen.__anext__())1173+ except StopAsyncIteration:1174+ return1175+1176+ ctx = self.new_context(dict(*args, **kwargs))1177+1178 try:1158- yield from self.root_render_func(self.new_context(vars))1179+ yield from self.root_render_func(ctx)1180 except Exception:1181 yield self.environment.handle_exception()1182 1162- def generate_async(self, *args, **kwargs):1183+ async def generate_async(self, *args, **kwargs):1184 """An async version of :meth:`generate`. Works very similarly but1185 returns an async iterator instead.1186 """1166- # see asyncsupport for the actual implementation1167- raise NotImplementedError(1168- "This feature is not available for this version of Python"1169- )1187+ if not self.environment.is_async:1188+ raise RuntimeError(1189+ "The environment was not created with async mode enabled."1190+ )1191 1192+ ctx = self.new_context(dict(*args, **kwargs))1193+1194+ try:1195+ async for event in self.root_render_func(ctx):1196+ yield event1197+ except Exception:1198+ yield self.environment.handle_exception()1199+1200 def new_context(self, vars=None, shared=False, locals=None):1201 """Create a new :class:`Context` for this template. The vars1202 provided will be passed to the template. Per default the globals1203 are added to the context. If shared is set to `True` the data11 unmodified lines1215 rather than caching it. It's also possible to provide1216 a dict which is then used as context. The arguments are the same1217 as for the :meth:`new_context` method.1218 """1190- return TemplateModule(self, self.new_context(vars, shared, locals))1219+ ctx = self.new_context(vars, shared, locals)1220+ return TemplateModule(self, ctx)1221 1192- def make_module_async(self, vars=None, shared=False, locals=None):1222+ async def make_module_async(self, vars=None, shared=False, locals=None):1223 """As template module creation can invoke template code for1224 asynchronous executions this method must be used instead of the1225 normal :meth:`make_module` one. Likewise the module attribute1226 becomes unavailable in async mode.1227 """1198- # see asyncsupport for the actual implementation1199- raise NotImplementedError(1200- "This feature is not available for this version of Python"1201- )1228+ ctx = self.new_context(vars, shared, locals)1229+ return TemplateModule(self, ctx, [x async for x in self.root_render_func(ctx)])1230 1231 @internalcode1232 def _get_default_module(self, ctx=None):1233 """If a context is passed in, this means that the template was1206- imported. Imported templates have access to the current template's1207- globals by default, but they can only be accessed via the context1208- during runtime.1234+ imported. Imported templates have access to the current1235+ template's globals by default, but they can only be accessed via1236+ the context during runtime.1237 1210- If there are new globals, we need to create a new1211- module because the cached module is already rendered and will not have1212- access to globals from the current context. This new module is not1213- cached as :attr:`_module` because the template can be imported elsewhere,1214- and it should have access to only the current template's globals.1238+ If there are new globals, we need to create a new module because1239+ the cached module is already rendered and will not have access1240+ to globals from the current context. This new module is not1241+ cached because the template can be imported elsewhere, and it1242+ should have access to only the current template's globals.1243 """1244+ if self.environment.is_async:1245+ raise RuntimeError("Module is not available in async mode.")1246+1247 if ctx is not None:1217- globals = {1218- key: ctx.parent[key] for key in ctx.globals_keys - self.globals.keys()1248+ keys = ctx.globals_keys - self.globals.keys()1219- }1220- if globals:1221- return self.make_module(globals)1222- if self._module is not None:1223- return self._module1224- self._module = rv = self.make_module()1225- return rv1249 1250+ if keys:1251+ return self.make_module({k: ctx.parent[k] for k in keys})1252+1253+ if self._module is None:1254+ self._module = self.make_module()1255+1256+ return self._module1257+1258+ async def _get_default_module_async(self, ctx=None):1259+ if ctx is not None:1260+ keys = ctx.globals_keys - self.globals.keys()1261+1262+ if keys:1263+ return await self.make_module_async({k: ctx.parent[k] for k in keys})1264+1265+ if self._module is None:1266+ self._module = await self.make_module_async()1267+1268+ return self._module1269+1270 @property1271 def module(self):1272 """The template as module. This is used for imports in the1273 template runtime but is also useful if one wants to access182 unmodified linesmodified:src/jinja2/filters.py+177 added-13 removed
11 unmodified lines12 from markupsafe import escape13 from markupsafe import Markup14 from markupsafe import soft_str15 16+from .async_utils import async_variant17+from .async_utils import auto_aiter18+from .async_utils import auto_await19+from .async_utils import auto_to_list20 from .exceptions import FilterArgumentError21 from .runtime import Undefined22 from .utils import htmlsafe_json_dumps23 from .utils import pass_context529 unmodified lines553 return value554 555 556 @pass_eval_context553-def do_join(557+def sync_do_join(558 eval_ctx: "EvalContext",559 value: t.Iterable,560 d: str = "",561 attribute: t.Optional[t.Union[str, int]] = None,48 unmodified lines610 # no html involved, to normal joining611 return soft_str(d).join(map(soft_str, value))612 613 614+@async_variant(sync_do_join)615+async def do_join(616+ eval_ctx: "EvalContext",617+ value: t.Union[t.AsyncIterable, t.Iterable],618+ d: str = "",619+ attribute: t.Optional[t.Union[str, int]] = None,620+) -> str:621+ return sync_do_join(eval_ctx, await auto_to_list(value), d, attribute)622+623+624 def do_center(value: str, width: int = 80) -> str:625 """Centers the value in a field of a given width."""626 return soft_str(value).center(width)627 628 629 @pass_environment616-def do_first(630+def sync_do_first(631 environment: "Environment", seq: "t.Iterable[V]"632 ) -> "t.Union[V, Undefined]":633 """Return the first item of a sequence."""634 try:1 unmodified line636 except StopIteration:637 return environment.undefined("No first item, sequence was empty.")638 639 640+@async_variant(sync_do_first)641+async def do_first(642+ environment: "Environment", seq: "t.Union[t.AsyncIterable[V], t.Iterable[V]]"643+) -> "t.Union[V, Undefined]":644+ try:645+ return t.cast("V", await auto_aiter(seq).__anext__())646+ except StopAsyncIteration:647+ return environment.undefined("No first item, sequence was empty.")648+649+650 @pass_environment651 def do_last(652 environment: "Environment", seq: "t.Reversible[V]"653 ) -> "t.Union[V, Undefined]":11 unmodified lines665 except StopIteration:666 return environment.undefined("No last item, sequence was empty.")667 668 669+# No async do_last, it may not be safe in async mode.670+671+672 @pass_context673 def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":674 """Return a random item from the sequence."""675 try:356 unmodified lines1032 1033 return Markup(str(value)).striptags()1034 1035 1009-def do_slice(1036+def sync_do_slice(1037 value: "t.Collection[V]", slices: int, fill_with: "t.Optional[V]" = None1038 ) -> "t.Iterator[t.List[V]]":1039 """Slice an iterator and return a list of lists containing1040 those items. Useful if you want to create a div containing34 unmodified lines1075 1076 yield tmp1077 1078 1079+@async_variant(sync_do_slice)1080+async def do_slice(1081+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1082+ slices: int,1083+ fill_with: t.Optional[t.Any] = None,1084+) -> "t.Iterator[t.List[V]]":1085+ return sync_do_slice(await auto_to_list(value), slices, fill_with)1086+1087+1088 def do_batch(1089 value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None1090 ) -> "t.Iterator[t.List[V]]":1091 """83 unmodified lines1175 return tuple.__str__(self)1176 1177 1178 @pass_environment1143-def do_groupby(1179+def sync_do_groupby(1180 environment: "Environment",1181 value: "t.Iterable[V]",1182 attribute: t.Union[str, int],1183 default: t.Optional[t.Any] = None,49 unmodified lines1233 for key, values in groupby(sorted(value, key=expr), expr)1234 ]1235 1236 1237+@async_variant(sync_do_groupby)1238+async def do_groupby(1239+ environment: "Environment",1240+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1241+ attribute: t.Union[str, int],1242+ default: t.Optional[t.Any] = None,1243+) -> "t.List[t.Tuple[t.Any, t.List[V]]]":1244+ expr = make_attrgetter(environment, attribute, default=default)1245+ return [1246+ _GroupTuple(key, await auto_to_list(values))1247+ for key, values in groupby(sorted(await auto_to_list(value), key=expr), expr)1248+ ]1249+1250+1251 @pass_environment1202-def do_sum(1252+def sync_do_sum(1253 environment: "Environment",1254 iterable: "t.Iterable[V]",1255 attribute: t.Optional[t.Union[str, int]] = None,1256 start: "V" = 0, # type: ignore17 unmodified lines1274 1275 return sum(iterable, start)1276 1277 1278+@async_variant(sync_do_sum)1279+async def do_sum(1280+ environment: "Environment",1281+ iterable: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1282+ attribute: t.Optional[t.Union[str, int]] = None,1283+ start: "V" = 0, # type: ignore1284+) -> "V":1285+ rv = start1286+1287+ if attribute is not None:1288+ func = make_attrgetter(environment, attribute)1289+ else:1290+1291+ def func(x):1292+ return x1293+1294+ async for item in auto_aiter(iterable):1295+ rv += func(item)1296+1297+ return rv1298+1299+1228-def do_list(value: "t.Iterable[V]") -> "t.List[V]":1300+def sync_do_list(value: "t.Iterable[V]") -> "t.List[V]":1301 """Convert the value into a list. If it was a string the returned list1302 will be a list of characters.1303 """1304 return list(value)1305 1306 1307+@async_variant(sync_do_list)1308+async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":1309+ return await auto_to_list(value)1310+1311+1312 def do_mark_safe(value: str) -> Markup:1313 """Mark the value as safe which means that in an environment with automatic1314 escaping enabled this variable will not be escaped.1315 """64 unmodified lines1380 return environment.undefined(obj=obj, name=name)1381 1382 1383 @typing.overload1307-def do_map(1384+def sync_do_map(1385 context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any1386 ) -> t.Iterable:1387 ...1388 1389 1390 @typing.overload1314-def do_map(1391+def sync_do_map(1392 context: "Context",1393 value: t.Iterable,1394 *,1395 attribute: str = ...,2 unmodified lines1398 ...1399 1400 1401 @pass_context1325-def do_map(context, value, *args, **kwargs):1402+def sync_do_map(context, value, *args, **kwargs):1403 """Applies a filter on a sequence of objects or looks up an attribute.1404 This is useful when dealing with lists of objects but you are really1405 only interested in a certain value of it.1406 38 unmodified lines1445 for item in value:1446 yield func(item)1447 1448 1449+@typing.overload1450+def do_map(1451+ context: "Context",1452+ value: t.Union[t.AsyncIterable, t.Iterable],1453+ name: str,1454+ *args: t.Any,1455+ **kwargs: t.Any,1456+) -> t.Iterable:1457+ ...1458+1459+1460+@typing.overload1461+def do_map(1462+ context: "Context",1463+ value: t.Union[t.AsyncIterable, t.Iterable],1464+ *,1465+ attribute: str = ...,1466+ default: t.Optional[t.Any] = None,1467+) -> t.Iterable:1468+ ...1469+1470+1471+@async_variant(sync_do_map)1472+async def do_map(context, value, *args, **kwargs):1473+ if value:1474+ func = prepare_map(context, args, kwargs)1475+1476+ async for item in auto_aiter(value):1477+ yield await auto_await(func(item))1478+1479+1480 @pass_context1373-def do_select(1481+def sync_do_select(1482 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1483 ) -> "t.Iterator[V]":1484 """Filters a sequence of objects by applying a test to each object,1485 and only selecting the objects with the test succeeding.21 unmodified lines1507 """1508 return select_or_reject(context, value, args, kwargs, lambda x: x, False)1509 1510 1511+@async_variant(sync_do_select)1512+async def do_select(1513+ context: "Context",1514+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1515+ *args: t.Any,1516+ **kwargs: t.Any,1517+) -> "t.AsyncIterator[V]":1518+ return async_select_or_reject(context, value, args, kwargs, lambda x: x, False)1519+1520+1521 @pass_context1404-def do_reject(1522+def sync_do_reject(1523 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1524 ) -> "t.Iterator[V]":1525 """Filters a sequence of objects by applying a test to each object,1526 and rejecting the objects with the test succeeding.16 unmodified lines1543 """1544 return select_or_reject(context, value, args, kwargs, lambda x: not x, False)1545 1546 1547+@async_variant(sync_do_reject)1548+async def do_reject(1549+ context: "Context",1550+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1551+ *args: t.Any,1552+ **kwargs: t.Any,1553+) -> "t.AsyncIterator[V]":1554+ return async_select_or_reject(context, value, args, kwargs, lambda x: not x, False)1555+1556+1557 @pass_context1430-def do_selectattr(1558+def sync_do_selectattr(1559 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1560 ) -> "t.Iterator[V]":1561 """Filters a sequence of objects by applying a test to the specified1562 attribute of each object, and only selecting the objects with the20 unmodified lines1583 """1584 return select_or_reject(context, value, args, kwargs, lambda x: x, True)1585 1586 1587+@async_variant(sync_do_selectattr)1588+async def do_selectattr(1589+ context: "Context",1590+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1591+ *args: t.Any,1592+ **kwargs: t.Any,1593+) -> "t.AsyncIterator[V]":1594+ return async_select_or_reject(context, value, args, kwargs, lambda x: x, True)1595+1596+1597 @pass_context1460-def do_rejectattr(1598+def sync_do_rejectattr(1599 context: "Context", value: "t.Iterable[V]", *args: t.Any, **kwargs: t.Any1600 ) -> "t.Iterator[V]":1601 """Filters a sequence of objects by applying a test to the specified1602 attribute of each object, and rejecting the objects with the test18 unmodified lines1621 """1622 return select_or_reject(context, value, args, kwargs, lambda x: not x, True)1623 1624 1625+@async_variant(sync_do_rejectattr)1626+async def do_rejectattr(1627+ context: "Context",1628+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1629+ *args: t.Any,1630+ **kwargs: t.Any,1631+) -> "t.AsyncIterator[V]":1632+ return async_select_or_reject(context, value, args, kwargs, lambda x: not x, True)1633+1634+1635 @pass_eval_context1636 def do_tojson(1637 eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None1638 ) -> Markup:99 unmodified lines1738 if func(item):1739 yield item1740 1741 1742+async def async_select_or_reject(1743+ context: "Context",1744+ value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",1745+ args: t.Tuple,1746+ kwargs: t.Dict[str, t.Any],1747+ modfunc: t.Callable[[t.Any], t.Any],1748+ lookup_attr: bool,1749+) -> "t.AsyncIterator[V]":1750+ if value:1751+ func = prepare_select_or_reject(context, args, kwargs, modfunc, lookup_attr)1752+1753+ async for item in auto_aiter(value):1754+ if func(item):1755+ yield item1756+1757+1758 FILTERS = {1759 "abs": abs,1760 "attr": do_attr,1761 "batch": do_batch,51 unmodified linesmodified:src/jinja2/nativetypes.py+3 added-4 removed
84 unmodified lines85 nodes are concatenated as strings. If the result can be parsed86 with :func:`ast.literal_eval`, the parsed value is returned.87 Otherwise, the string is returned.88 """89- vars = dict(*args, **kwargs)89+ ctx = self.new_context(dict(*args, **kwargs))90 91 try:92- return native_concat(self.root_render_func(self.new_context(vars)))92+ return native_concat(self.root_render_func(ctx))93 except Exception:94 return self.environment.handle_exception()95 96 async def render_async(self, *args, **kwargs):1 unmodified line98 raise RuntimeError(99 "The environment was not created with async mode enabled."100 )101 102- vars = dict(*args, **kwargs)103- ctx = self.new_context(vars)102+ ctx = self.new_context(dict(*args, **kwargs))103 104 try:105 return native_concat([n async for n in self.root_render_func(ctx)])106 except Exception:4 unmodified linesmodified:src/jinja2/runtime.py+102 added-2 removed
7 unmodified lines8 from markupsafe import escape # noqa: F4019 from markupsafe import Markup10 from markupsafe import soft_str11 12+from .async_utils import auto_aiter13+from .async_utils import auto_await # noqa: F40114 from .exceptions import TemplateNotFound # noqa: F40115 from .exceptions import TemplateRuntimeError # noqa: F40116 from .exceptions import UndefinedError17 from .nodes import EvalContext25 unmodified lines43 "Namespace",44 "Undefined",45 "internalcode",46 ]47+async_exported = [48+ "AsyncLoopContext",49+ "auto_aiter",50+ "auto_await",51+]52 53 54 def identity(x):55 """Returns its argument. Useful for certain things in the319 unmodified lines375 )376 return BlockReference(self.name, self._context, self._stack, self._depth + 1)377 378 @internalcode379+ async def _async_call(self):380+ rv = concat([x async for x in self._stack[self._depth](self._context)])381+382+ if self._context.eval_ctx.autoescape:383+ return Markup(rv)384+385+ return rv386+387+ @internalcode388 def __call__(self):389+ if self._context.environment.is_async:390+ return self._async_call()391+392 rv = concat(self._stack[self._depth](self._context))393+394 if self._context.eval_ctx.autoescape:375- rv = Markup(rv)395+ return Markup(rv)396+397 return rv398 399 400 class LoopContext:186 unmodified lines587 def __repr__(self):588 return f"<{self.__class__.__name__} {self.index}/{self.length}>"589 590 591+class AsyncLoopContext(LoopContext):592+ @staticmethod593+ def _to_iterator(iterable):594+ return auto_aiter(iterable)595+596+ @property597+ async def length(self):598+ if self._length is not None:599+ return self._length600+601+ try:602+ self._length = len(self._iterable)603+ except TypeError:604+ iterable = [x async for x in self._iterator]605+ self._iterator = self._to_iterator(iterable)606+ self._length = len(iterable) + self.index + (self._after is not missing)607+608+ return self._length609+610+ @property611+ async def revindex0(self):612+ return await self.length - self.index613+614+ @property615+ async def revindex(self):616+ return await self.length - self.index0617+618+ async def _peek_next(self):619+ if self._after is not missing:620+ return self._after621+622+ try:623+ self._after = await self._iterator.__anext__()624+ except StopAsyncIteration:625+ self._after = missing626+627+ return self._after628+629+ @property630+ async def last(self):631+ return await self._peek_next() is missing632+633+ @property634+ async def nextitem(self):635+ rv = await self._peek_next()636+637+ if rv is missing:638+ return self._undefined("there is no next item")639+640+ return rv641+642+ def __aiter__(self):643+ return self644+645+ async def __anext__(self):646+ if self._after is not missing:647+ rv = self._after648+ self._after = missing649+ else:650+ rv = await self._iterator.__anext__()651+652+ self.index0 += 1653+ self._before = self._current654+ self._current = rv655+ return rv, self656+657+658 class Macro:659 """Wraps a macro function."""660 661 def __init__(97 unmodified lines759 )760 761 return self._invoke(arguments, autoescape)762 763+ async def _async_invoke(self, arguments, autoescape):764+ rv = await self._func(*arguments)765+766+ if autoescape:767+ return Markup(rv)768+769+ return rv770+771 def _invoke(self, arguments, autoescape):676- """This method is being swapped out by the async implementation."""772+ if self._environment.is_async:773+ return self._async_invoke(arguments, autoescape)774+775 rv = self._func(*arguments)776+777 if autoescape:778 rv = Markup(rv)779+780 return rv781 782 def __repr__(self):783 name = "anonymous" if self.name is None else repr(self.name)252 unmodified linesmodified:src/jinja2/utils.py-11 removed
18 unmodified lines19 20 # special singleton representing missing values for the runtime21 missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()22 23-# internal code23 internal_code: t.MutableSet[CodeType] = set()24 25 concat = "".join26 28-_slash_escape = "\\/" not in json.dumps("/")27 30-28 def pass_context(f: "F") -> "F":29 """Pass the :class:`~jinja2.runtime.Context` as the first argument30 to the decorated function when called while rendering a template.31 796 unmodified lines828 def __repr__(self):829 return f"<Namespace {self.__attrs!r}>"830 831 835-# does this python version support async for in and async generators?836-try:837- exec("async def _():\n async for _ in ():\n yield _")838- have_async_gen = True839-except SyntaxError:840- have_async_gen = False841-842-832 class Markup(markupsafe.Markup):833 def __init__(self, *args, **kwargs):834 warnings.warn(835 "'jinja2.Markup' is deprecated and will be removed in Jinja"15 unmodified linesmodified:tests/conftest.py+1 added-8 removed
1 import os2 3 import pytest4 5-from jinja2 import Environment5 from jinja2 import loaders7-from jinja2.utils import have_async_gen6+from jinja2.environment import Environment7 8 10-def pytest_ignore_collect(path):11- if "async" in path.basename and not have_async_gen:12- return True13- return False14-15-9 @pytest.fixture10 def env():11 """returns a new environment."""12 return Environment()37 unmodified linesadded:tests/test_async_filters.py+253 added
1+from collections import namedtuple2+3+import pytest4+from markupsafe import Markup5+6+from jinja2 import Environment7+from jinja2.async_utils import auto_aiter8+9+10+async def make_aiter(iter):11+ for item in iter:12+ yield item13+14+15+def mark_dualiter(parameter, factory):16+ def decorator(f):17+ return pytest.mark.parametrize(18+ parameter, [lambda: factory(), lambda: make_aiter(factory())]19+ )(f)20+21+ return decorator22+23+24+@pytest.fixture25+def env_async():26+ return Environment(enable_async=True)27+28+29+@mark_dualiter("foo", lambda: range(10))30+def test_first(env_async, foo):31+ tmpl = env_async.from_string("{{ foo()|first }}")32+ out = tmpl.render(foo=foo)33+ assert out == "0"34+35+36+@mark_dualiter(37+ "items",38+ lambda: [39+ {"foo": 1, "bar": 2},40+ {"foo": 2, "bar": 3},41+ {"foo": 1, "bar": 1},42+ {"foo": 3, "bar": 4},43+ ],44+)45+def test_groupby(env_async, items):46+ tmpl = env_async.from_string(47+ """48+ {%- for grouper, list in items()|groupby('foo') -%}49+ {{ grouper }}{% for x in list %}: {{ x.foo }}, {{ x.bar }}{% endfor %}|50+ {%- endfor %}"""51+ )52+ assert tmpl.render(items=items).split("|") == [53+ "1: 1, 2: 1, 1",54+ "2: 2, 3",55+ "3: 3, 4",56+ "",57+ ]58+59+60+@mark_dualiter("items", lambda: [("a", 1), ("a", 2), ("b", 1)])61+def test_groupby_tuple_index(env_async, items):62+ tmpl = env_async.from_string(63+ """64+ {%- for grouper, list in items()|groupby(0) -%}65+ {{ grouper }}{% for x in list %}:{{ x.1 }}{% endfor %}|66+ {%- endfor %}"""67+ )68+ assert tmpl.render(items=items) == "a:1:2|b:1|"69+70+71+def make_articles():72+ Date = namedtuple("Date", "day,month,year")73+ Article = namedtuple("Article", "title,date")74+ return [75+ Article("aha", Date(1, 1, 1970)),76+ Article("interesting", Date(2, 1, 1970)),77+ Article("really?", Date(3, 1, 1970)),78+ Article("totally not", Date(1, 1, 1971)),79+ ]80+81+82+@mark_dualiter("articles", make_articles)83+def test_groupby_multidot(env_async, articles):84+ tmpl = env_async.from_string(85+ """86+ {%- for year, list in articles()|groupby('date.year') -%}87+ {{ year }}{% for x in list %}[{{ x.title }}]{% endfor %}|88+ {%- endfor %}"""89+ )90+ assert tmpl.render(articles=articles).split("|") == [91+ "1970[aha][interesting][really?]",92+ "1971[totally not]",93+ "",94+ ]95+96+97+@mark_dualiter("int_items", lambda: [1, 2, 3])98+def test_join_env_int(env_async, int_items):99+ tmpl = env_async.from_string('{{ items()|join("|") }}')100+ out = tmpl.render(items=int_items)101+ assert out == "1|2|3"102+103+104+@mark_dualiter("string_items", lambda: ["<foo>", Markup("<span>foo</span>")])105+def test_join_string_list(string_items):106+ env2 = Environment(autoescape=True, enable_async=True)107+ tmpl = env2.from_string('{{ ["<foo>", "<span>foo</span>"|safe]|join }}')108+ assert tmpl.render(items=string_items) == "<foo><span>foo</span>"109+110+111+def make_users():112+ User = namedtuple("User", "username")113+ return map(User, ["foo", "bar"])114+115+116+@mark_dualiter("users", make_users)117+def test_join_attribute(env_async, users):118+ tmpl = env_async.from_string("""{{ users()|join(', ', 'username') }}""")119+ assert tmpl.render(users=users) == "foo, bar"120+121+122+@mark_dualiter("items", lambda: [1, 2, 3, 4, 5])123+def test_simple_reject(env_async, items):124+ tmpl = env_async.from_string('{{ items()|reject("odd")|join("|") }}')125+ assert tmpl.render(items=items) == "2|4"126+127+128+@mark_dualiter("items", lambda: [None, False, 0, 1, 2, 3, 4, 5])129+def test_bool_reject(env_async, items):130+ tmpl = env_async.from_string('{{ items()|reject|join("|") }}')131+ assert tmpl.render(items=items) == "None|False|0"132+133+134+@mark_dualiter("items", lambda: [1, 2, 3, 4, 5])135+def test_simple_select(env_async, items):136+ tmpl = env_async.from_string('{{ items()|select("odd")|join("|") }}')137+ assert tmpl.render(items=items) == "1|3|5"138+139+140+@mark_dualiter("items", lambda: [None, False, 0, 1, 2, 3, 4, 5])141+def test_bool_select(env_async, items):142+ tmpl = env_async.from_string('{{ items()|select|join("|") }}')143+ assert tmpl.render(items=items) == "1|2|3|4|5"144+145+146+def make_users(): # type: ignore147+ User = namedtuple("User", "name,is_active")148+ return [149+ User("john", True),150+ User("jane", True),151+ User("mike", False),152+ ]153+154+155+@mark_dualiter("users", make_users)156+def test_simple_select_attr(env_async, users):157+ tmpl = env_async.from_string(158+ '{{ users()|selectattr("is_active")|map(attribute="name")|join("|") }}'159+ )160+ assert tmpl.render(users=users) == "john|jane"161+162+163+@mark_dualiter("items", lambda: list("123"))164+def test_simple_map(env_async, items):165+ tmpl = env_async.from_string('{{ items()|map("int")|sum }}')166+ assert tmpl.render(items=items) == "6"167+168+169+def test_map_sum(env_async): # async map + async filter170+ tmpl = env_async.from_string('{{ [[1,2], [3], [4,5,6]]|map("sum")|list }}')171+ assert tmpl.render() == "[3, 3, 15]"172+173+174+@mark_dualiter("users", make_users)175+def test_attribute_map(env_async, users):176+ tmpl = env_async.from_string('{{ users()|map(attribute="name")|join("|") }}')177+ assert tmpl.render(users=users) == "john|jane|mike"178+179+180+def test_empty_map(env_async):181+ tmpl = env_async.from_string('{{ none|map("upper")|list }}')182+ assert tmpl.render() == "[]"183+184+185+@mark_dualiter("items", lambda: [1, 2, 3, 4, 5, 6])186+def test_sum(env_async, items):187+ tmpl = env_async.from_string("""{{ items()|sum }}""")188+ assert tmpl.render(items=items) == "21"189+190+191+@mark_dualiter("items", lambda: [{"value": 23}, {"value": 1}, {"value": 18}])192+def test_sum_attributes(env_async, items):193+ tmpl = env_async.from_string("""{{ items()|sum('value') }}""")194+ assert tmpl.render(items=items)195+196+197+def test_sum_attributes_nested(env_async):198+ tmpl = env_async.from_string("""{{ values|sum('real.value') }}""")199+ assert (200+ tmpl.render(201+ values=[202+ {"real": {"value": 23}},203+ {"real": {"value": 1}},204+ {"real": {"value": 18}},205+ ]206+ )207+ == "42"208+ )209+210+211+def test_sum_attributes_tuple(env_async):212+ tmpl = env_async.from_string("""{{ values.items()|sum('1') }}""")213+ assert tmpl.render(values={"foo": 23, "bar": 1, "baz": 18}) == "42"214+215+216+@mark_dualiter("items", lambda: range(10))217+def test_slice(env_async, items):218+ tmpl = env_async.from_string(219+ "{{ items()|slice(3)|list }}|{{ items()|slice(3, 'X')|list }}"220+ )221+ out = tmpl.render(items=items)222+ assert out == (223+ "[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"224+ "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]"225+ )226+227+228+def test_custom_async_filter(env_async):229+ async def customfilter(val):230+ return str(val)231+232+ env_async.filters["customfilter"] = customfilter233+ tmpl = env_async.from_string("{{ 'static'|customfilter }} {{ arg|customfilter }}")234+ out = tmpl.render(arg="dynamic")235+ assert out == "static dynamic"236+237+238+@mark_dualiter("items", lambda: range(10))239+def test_custom_async_iteratable_filter(env_async, items):240+ async def customfilter(iterable):241+ items = []242+ async for item in auto_aiter(iterable):243+ items.append(str(item))244+ if len(items) == 3:245+ break246+ return ",".join(items)247+248+ env_async.filters["customfilter"] = customfilter249+ tmpl = env_async.from_string(250+ "{{ items()|customfilter }} .. {{ [3, 4, 5, 6]|customfilter }}"251+ )252+ out = tmpl.render(items=items)253+ assert out == "0,1,2 .. 3,4,5"modified:tests/test_async.py+1 added-1 removed
4 unmodified lines5 from jinja2 import ChainableUndefined6 from jinja2 import DictLoader7 from jinja2 import Environment8 from jinja2 import Template9-from jinja2.asyncsupport import auto_aiter9+from jinja2.async_utils import auto_aiter10 from jinja2.exceptions import TemplateNotFound11 from jinja2.exceptions import TemplatesNotFound12 from jinja2.exceptions import UndefinedError13 from jinja2.nativetypes import NativeEnvironment615 unmodified linesdeleted:tests/test_asyncfilters.py-253 removed
1-from collections import namedtuple2-3-import pytest4-from markupsafe import Markup5-6-from jinja2 import Environment7-from jinja2.asyncsupport import auto_aiter8-9-10-async def make_aiter(iter):11- for item in iter:12- yield item13-14-15-def mark_dualiter(parameter, factory):16- def decorator(f):17- return pytest.mark.parametrize(18- parameter, [lambda: factory(), lambda: make_aiter(factory())]19- )(f)20-21- return decorator22-23-24-@pytest.fixture25-def env_async():26- return Environment(enable_async=True)27-28-29-@mark_dualiter("foo", lambda: range(10))30-def test_first(env_async, foo):31- tmpl = env_async.from_string("{{ foo()|first }}")32- out = tmpl.render(foo=foo)33- assert out == "0"34-35-36-@mark_dualiter(37- "items",38- lambda: [39- {"foo": 1, "bar": 2},40- {"foo": 2, "bar": 3},41- {"foo": 1, "bar": 1},42- {"foo": 3, "bar": 4},43- ],44-)45-def test_groupby(env_async, items):46- tmpl = env_async.from_string(47- """48- {%- for grouper, list in items()|groupby('foo') -%}49- {{ grouper }}{% for x in list %}: {{ x.foo }}, {{ x.bar }}{% endfor %}|50- {%- endfor %}"""51- )52- assert tmpl.render(items=items).split("|") == [53- "1: 1, 2: 1, 1",54- "2: 2, 3",55- "3: 3, 4",56- "",57- ]58-59-60-@mark_dualiter("items", lambda: [("a", 1), ("a", 2), ("b", 1)])61-def test_groupby_tuple_index(env_async, items):62- tmpl = env_async.from_string(63- """64- {%- for grouper, list in items()|groupby(0) -%}65- {{ grouper }}{% for x in list %}:{{ x.1 }}{% endfor %}|66- {%- endfor %}"""67- )68- assert tmpl.render(items=items) == "a:1:2|b:1|"69-70-71-def make_articles():72- Date = namedtuple("Date", "day,month,year")73- Article = namedtuple("Article", "title,date")74- return [75- Article("aha", Date(1, 1, 1970)),76- Article("interesting", Date(2, 1, 1970)),77- Article("really?", Date(3, 1, 1970)),78- Article("totally not", Date(1, 1, 1971)),79- ]80-81-82-@mark_dualiter("articles", make_articles)83-def test_groupby_multidot(env_async, articles):84- tmpl = env_async.from_string(85- """86- {%- for year, list in articles()|groupby('date.year') -%}87- {{ year }}{% for x in list %}[{{ x.title }}]{% endfor %}|88- {%- endfor %}"""89- )90- assert tmpl.render(articles=articles).split("|") == [91- "1970[aha][interesting][really?]",92- "1971[totally not]",93- "",94- ]95-96-97-@mark_dualiter("int_items", lambda: [1, 2, 3])98-def test_join_env_int(env_async, int_items):99- tmpl = env_async.from_string('{{ items()|join("|") }}')100- out = tmpl.render(items=int_items)101- assert out == "1|2|3"102-103-104-@mark_dualiter("string_items", lambda: ["<foo>", Markup("<span>foo</span>")])105-def test_join_string_list(string_items):106- env2 = Environment(autoescape=True, enable_async=True)107- tmpl = env2.from_string('{{ ["<foo>", "<span>foo</span>"|safe]|join }}')108- assert tmpl.render(items=string_items) == "<foo><span>foo</span>"109-110-111-def make_users():112- User = namedtuple("User", "username")113- return map(User, ["foo", "bar"])114-115-116-@mark_dualiter("users", make_users)117-def test_join_attribute(env_async, users):118- tmpl = env_async.from_string("""{{ users()|join(', ', 'username') }}""")119- assert tmpl.render(users=users) == "foo, bar"120-121-122-@mark_dualiter("items", lambda: [1, 2, 3, 4, 5])123-def test_simple_reject(env_async, items):124- tmpl = env_async.from_string('{{ items()|reject("odd")|join("|") }}')125- assert tmpl.render(items=items) == "2|4"126-127-128-@mark_dualiter("items", lambda: [None, False, 0, 1, 2, 3, 4, 5])129-def test_bool_reject(env_async, items):130- tmpl = env_async.from_string('{{ items()|reject|join("|") }}')131- assert tmpl.render(items=items) == "None|False|0"132-133-134-@mark_dualiter("items", lambda: [1, 2, 3, 4, 5])135-def test_simple_select(env_async, items):136- tmpl = env_async.from_string('{{ items()|select("odd")|join("|") }}')137- assert tmpl.render(items=items) == "1|3|5"138-139-140-@mark_dualiter("items", lambda: [None, False, 0, 1, 2, 3, 4, 5])141-def test_bool_select(env_async, items):142- tmpl = env_async.from_string('{{ items()|select|join("|") }}')143- assert tmpl.render(items=items) == "1|2|3|4|5"144-145-146-def make_users(): # type: ignore147- User = namedtuple("User", "name,is_active")148- return [149- User("john", True),150- User("jane", True),151- User("mike", False),152- ]153-154-155-@mark_dualiter("users", make_users)156-def test_simple_select_attr(env_async, users):157- tmpl = env_async.from_string(158- '{{ users()|selectattr("is_active")|map(attribute="name")|join("|") }}'159- )160- assert tmpl.render(users=users) == "john|jane"161-162-163-@mark_dualiter("items", lambda: list("123"))164-def test_simple_map(env_async, items):165- tmpl = env_async.from_string('{{ items()|map("int")|sum }}')166- assert tmpl.render(items=items) == "6"167-168-169-def test_map_sum(env_async): # async map + async filter170- tmpl = env_async.from_string('{{ [[1,2], [3], [4,5,6]]|map("sum")|list }}')171- assert tmpl.render() == "[3, 3, 15]"172-173-174-@mark_dualiter("users", make_users)175-def test_attribute_map(env_async, users):176- tmpl = env_async.from_string('{{ users()|map(attribute="name")|join("|") }}')177- assert tmpl.render(users=users) == "john|jane|mike"178-179-180-def test_empty_map(env_async):181- tmpl = env_async.from_string('{{ none|map("upper")|list }}')182- assert tmpl.render() == "[]"183-184-185-@mark_dualiter("items", lambda: [1, 2, 3, 4, 5, 6])186-def test_sum(env_async, items):187- tmpl = env_async.from_string("""{{ items()|sum }}""")188- assert tmpl.render(items=items) == "21"189-190-191-@mark_dualiter("items", lambda: [{"value": 23}, {"value": 1}, {"value": 18}])192-def test_sum_attributes(env_async, items):193- tmpl = env_async.from_string("""{{ items()|sum('value') }}""")194- assert tmpl.render(items=items)195-196-197-def test_sum_attributes_nested(env_async):198- tmpl = env_async.from_string("""{{ values|sum('real.value') }}""")199- assert (200- tmpl.render(201- values=[202- {"real": {"value": 23}},203- {"real": {"value": 1}},204- {"real": {"value": 18}},205- ]206- )207- == "42"208- )209-210-211-def test_sum_attributes_tuple(env_async):212- tmpl = env_async.from_string("""{{ values.items()|sum('1') }}""")213- assert tmpl.render(values={"foo": 23, "bar": 1, "baz": 18}) == "42"214-215-216-@mark_dualiter("items", lambda: range(10))217-def test_slice(env_async, items):218- tmpl = env_async.from_string(219- "{{ items()|slice(3)|list }}|{{ items()|slice(3, 'X')|list }}"220- )221- out = tmpl.render(items=items)222- assert out == (223- "[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"224- "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]"225- )226-227-228-def test_custom_async_filter(env_async):229- async def customfilter(val):230- return str(val)231-232- env_async.filters["customfilter"] = customfilter233- tmpl = env_async.from_string("{{ 'static'|customfilter }} {{ arg|customfilter }}")234- out = tmpl.render(arg="dynamic")235- assert out == "static dynamic"236-237-238-@mark_dualiter("items", lambda: range(10))239-def test_custom_async_iteratable_filter(env_async, items):240- async def customfilter(iterable):241- items = []242- async for item in auto_aiter(iterable):243- items.append(str(item))244- if len(items) == 3:245- break246- return ",".join(items)247-248- env_async.filters["customfilter"] = customfilter249- tmpl = env_async.from_string(250- "{{ items()|customfilter }} .. {{ [3, 4, 5, 6]|customfilter }}"251- )252- out = tmpl.render(items=items)253- assert out == "0,1,2 .. 3,4,5"modified:CHANGES.rst+4 added
68 unmodified lines69 ``evalcontextfilter``70 - ``pass_environment`` replaces ``environmentfunction`` and71 ``environmentfilter``.72 73+- Async support no longer requires Jinja to patch itself. It must74+ still be enabled with ``Environment(enable_async=True)``.75+ :issue:`1390`76 77+78 Version 2.11.379 --------------80 81 Released 2021-01-31778 unmodified lines