Skip to content
Myr

async support doesn't require patching

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by David Lord · committed by David Lord · parent a9b06f4 · 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

15 files+713 added−856 removed

modified:docs/intro.rst+2 added-2 removed
10 unmodified lines
11- 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 debugging
43 unmodified lines
added:src/jinja2/async_utils.py+76 added
1import inspect2import typing as t3from functools import wraps45from .utils import _PassArg6from .utils import pass_eval_context78if t.TYPE_CHECKING:9 V = t.TypeVar("V")101112def async_variant(normal_func):13 def decorator(async_func):14 pass_arg = _PassArg.from_obj(normal_func)15 need_eval_context = pass_arg is None1617 if pass_arg is _PassArg.environment:1819 def is_async(args):20 return args[0].is_async2122 else:2324 def is_async(args):25 return args[0].environment.is_async2627 @wraps(normal_func)28 def wrapper(*args, **kwargs):29 b = is_async(args)3031 if need_eval_context:32 args = args[1:]3334 if b:35 return async_func(*args, **kwargs)3637 return normal_func(*args, **kwargs)3839 if need_eval_context:40 wrapper = pass_eval_context(wrapper)4142 wrapper.jinja_async_variant = True43 return wrapper4445 return decorator464748async def auto_await(value):49 if inspect.isawaitable(value):50 return await value5152 return value535455async 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 item626364async def auto_to_list(65 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",66) -> "t.List[V]":67 seq = []6869 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)7576 return seq
deleted:src/jinja2/asyncfilters.py-261 removed
1import typing2import typing as t3import warnings4from functools import wraps5from itertools import groupby67from . import filters8from .asyncsupport import auto_aiter9from .asyncsupport import auto_await10from .utils import _PassArg11from .utils import pass_eval_context1213if t.TYPE_CHECKING:14 from .environment import Environment15 from .nodes import EvalContext16 from .runtime import Context17 from .runtime import Undefined1819 V = t.TypeVar("V")202122async def auto_to_seq(23 value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]",24) -> "t.List[V]":25 seq = []2627 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)3334 return seq353637async 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 )4950 async for item in auto_aiter(value):51 if func(item):52 yield item535455def dual_filter(normal_func, async_func):56 pass_arg = _PassArg.from_obj(normal_func)57 wrapper_has_eval_context = False5859 if pass_arg is _PassArg.environment:60 wrapper_has_eval_context = False6162 def is_async(args):63 return args[0].is_async6465 else:66 wrapper_has_eval_context = pass_arg is None6768 def is_async(args):69 return args[0].environment.is_async7071 @wraps(normal_func)72 def wrapper(*args, **kwargs):73 b = is_async(args)7475 if wrapper_has_eval_context:76 args = args[1:]7778 if b:79 return async_func(*args, **kwargs)8081 return normal_func(*args, **kwargs)8283 if wrapper_has_eval_context:84 wrapper = pass_eval_context(wrapper)8586 wrapper.jinja_async_variant = True87 return wrapper888990def async_variant(original):91 def decorator(f):92 return dual_filter(original, f)9394 return decorator959697def 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)105106107@async_variant(filters.do_first)108async 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.")115116117@async_variant(filters.do_groupby)118async 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 ]129130131@async_variant(filters.do_join)132async 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)139140141@async_variant(filters.do_list)142async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":143 return await auto_to_seq(value)144145146@async_variant(filters.do_reject)147async 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)154155156@async_variant(filters.do_rejectattr)157async 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)164165166@async_variant(filters.do_select)167async 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)174175176@async_variant(filters.do_selectattr)177async 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)184185186@typing.overload187def 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 ...195196197@typing.overload198def 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 ...206207208@async_variant(filters.do_map)209async def do_map(context, value, *args, **kwargs):210 if value:211 func = filters.prepare_map(context, args, kwargs)212213 async for item in auto_aiter(value):214 yield await auto_await(func(item))215216217@async_variant(filters.do_sum)218async 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 = start225226 if attribute is not None:227 func = filters.make_attrgetter(environment, attribute)228 else:229230 def func(x):231 return x232233 async for item in auto_aiter(iterable):234 rv += func(item)235236 return rv237238239@async_variant(filters.do_slice)240async 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)246247248ASYNC_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."""2import asyncio3import inspect4from functools import update_wrapper56from markupsafe import Markup78from .environment import TemplateModule9from .runtime import LoopContext10from .utils import concat11from .utils import internalcode12from .utils import missing131415async def concat_async(async_gen):16 rv = []1718 async def collect():19 async for event in async_gen:20 rv.append(event)2122 await collect()23 return concat(rv)242526async 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()333435def 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 pass4344 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)4849 return update_wrapper(generate, original_generate)505152async 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.")5556 vars = dict(*args, **kwargs)57 ctx = self.new_context(vars)5859 try:60 return await concat_async(self.root_render_func(ctx))61 except Exception:62 return self.environment.handle_exception()636465def 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))7172 return update_wrapper(render, original_render)737475def 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 rv8283 @internalcode84 def __call__(self):85 if not self._context.environment.is_async:86 return original_call(self)87 return async_call(self)8889 return update_wrapper(__call__, original_call)909192def 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 rv99100 @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)105106 return update_wrapper(_invoke, original_invoke)107108109@internalcode110async 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 rv115116117def 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)123124 return _get_default_module125126127async 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)133134135def patch_template():136 from . import Template137138 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 )147148149def patch_runtime():150 from .runtime import BlockReference, Macro151152 BlockReference.__call__ = wrap_block_reference_call(BlockReference.__call__)153 Macro._invoke = wrap_macro_invoke(Macro._invoke)154155156def patch_filters():157 from .filters import FILTERS158 from .asyncfilters import ASYNC_FILTERS159160 FILTERS.update(ASYNC_FILTERS)161162163def patch_all():164 patch_template()165 patch_runtime()166 patch_filters()167168169async def auto_await(value):170 if inspect.isawaitable(value):171 return await value172 return value173174175async 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 item182183184class AsyncLoopContext(LoopContext):185 _to_iterator = staticmethod(auto_aiter)186187 @property188 async def length(self):189 if self._length is not None:190 return self._length191192 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)198199 return self._length200201 @property202 async def revindex0(self):203 return await self.length - self.index204205 @property206 async def revindex(self):207 return await self.length - self.index0208209 async def _peek_next(self):210 if self._after is not missing:211 return self._after212213 try:214 self._after = await self._iterator.__anext__()215 except StopAsyncIteration:216 self._after = missing217218 return self._after219220 @property221 async def last(self):222 return await self._peek_next() is missing223224 @property225 async def nextitem(self):226 rv = await self._peek_next()227228 if rv is missing:229 return self._undefined("there is no next item")230231 return rv232233 def __aiter__(self):234 return self235236 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__()242243 self.index0 += 1244 self._before = self._current245 self._current = rv246 return rv, self247248249patch_all()
modified:src/jinja2/compiler.py+7 added-8 removed
725 unmodified lines
726 def visit_Template(self, node, frame=None):727 assert frame is None, "no root frame allowed"728 eval_ctx = EvalContext(self.environment, self.name)729730 from .runtime import exported730 from .runtime import exported, async_exported731732 self.writeline("from __future__ import generator_stop") # Python < 3.7733 self.writeline("from jinja2.runtime import " + ", ".join(exported))734732 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)736737 self.writeline("from __future__ import generator_stop") # Python < 3.7738 self.writeline("from jinja2.runtime import " + ", ".join(exported_names))739740 # 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 lines
modified:src/jinja2/environment.py+87 added-44 removed
43 unmodified lines
44from .runtime import Undefined45from .utils import _PassArg46from .utils import concat47from .utils import consume48from .utils import have_async_gen48from .utils import import_string49from .utils import internalcode50from .utils import LRUCache51from .utils import missing
288 unmodified lines
340341 # load extensions342 self.extensions = load_extensions(self, extensions)343345 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: F401350344 self.is_async = enable_async345 _environment_sanity_check(self)346347 def add_extension(self, extension):348 """Adds an extension after the environment was created.
763 unmodified lines
1112 template.render({'knights': 'that say nih'})11131114 This will return the rendered template as a string.1115 """1122 vars = dict(*args, **kwargs)1116 if self.environment.is_async:1117 import asyncio11181119 loop = asyncio.get_event_loop()1120 return loop.run_until_complete(self.render_async(*args, **kwargs))11211122 ctx = self.new_context(dict(*args, **kwargs))11231124 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()11281128 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.11331134 Example usage::11351136 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 )11421143 ctx = self.new_context(dict(*args, **kwargs))11441145 try:1146 return concat([n async for n in self.root_render_func(ctx)])1147 except Exception:1148 return self.environment.handle_exception()11491150 def stream(self, *args, **kwargs):1151 """Works exactly like :meth:`generate` but returns a1152 :class:`TemplateStream`.1153 """
6 unmodified lines
1160 a generator that yields one item after another as strings.11611162 It accepts the same arguments as :meth:`render`.1163 """1156 vars = dict(*args, **kwargs)1164 if self.environment.is_async:1165 import asyncio11661167 loop = asyncio.get_event_loop()1168 async_gen = self.generate_async(*args, **kwargs)11691170 try:1171 while True:1172 yield loop.run_until_complete(async_gen.__anext__())1173 except StopAsyncIteration:1174 return11751176 ctx = self.new_context(dict(*args, **kwargs))11771178 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()11821162 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 )11911192 ctx = self.new_context(dict(*args, **kwargs))11931194 try:1195 async for event in self.root_render_func(ctx):1196 yield event1197 except Exception:1198 yield self.environment.handle_exception()11991200 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 data
11 unmodified lines
1215 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)12211192 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)])12301231 @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.12371210 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.")12461247 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 rv12491250 if keys:1251 return self.make_module({k: ctx.parent[k] for k in keys})12521253 if self._module is None:1254 self._module = self.make_module()12551256 return self._module12571258 async def _get_default_module_async(self, ctx=None):1259 if ctx is not None:1260 keys = ctx.globals_keys - self.globals.keys()12611262 if keys:1263 return await self.make_module_async({k: ctx.parent[k] for k in keys})12641265 if self._module is None:1266 self._module = await self.make_module_async()12671268 return self._module12691270 @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 access
182 unmodified lines
modified:src/jinja2/filters.py+177 added-13 removed
11 unmodified lines
12from markupsafe import escape13from markupsafe import Markup14from markupsafe import soft_str1516from .async_utils import async_variant17from .async_utils import auto_aiter18from .async_utils import auto_await19from .async_utils import auto_to_list20from .exceptions import FilterArgumentError21from .runtime import Undefined22from .utils import htmlsafe_json_dumps23from .utils import pass_context
529 unmodified lines
553 return value554555556@pass_eval_context553def do_join(557def 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 lines
610 # no html involved, to normal joining611 return soft_str(d).join(map(soft_str, value))612613614@async_variant(sync_do_join)615async 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)622623624def 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)627628629@pass_environment616def do_first(630def 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 line
636 except StopIteration:637 return environment.undefined("No first item, sequence was empty.")638639640@async_variant(sync_do_first)641async 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.")648649650@pass_environment651def do_last(652 environment: "Environment", seq: "t.Reversible[V]"653) -> "t.Union[V, Undefined]":
11 unmodified lines
665 except StopIteration:666 return environment.undefined("No last item, sequence was empty.")667668669# No async do_last, it may not be safe in async mode.670671672@pass_context673def do_random(context: "Context", seq: "t.Sequence[V]") -> "t.Union[V, Undefined]":674 """Return a random item from the sequence."""675 try:
356 unmodified lines
10321033 return Markup(str(value)).striptags()103410351009def do_slice(1036def 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 containing
34 unmodified lines
10751076 yield tmp107710781079@async_variant(sync_do_slice)1080async 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)108610871088def do_batch(1089 value: "t.Iterable[V]", linecount: int, fill_with: "t.Optional[V]" = None1090) -> "t.Iterator[t.List[V]]":1091 """
83 unmodified lines
1175 return tuple.__str__(self)117611771178@pass_environment1143def do_groupby(1179def 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 lines
1233 for key, values in groupby(sorted(value, key=expr), expr)1234 ]123512361237@async_variant(sync_do_groupby)1238async 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 ]124912501251@pass_environment1202def do_sum(1252def 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: ignore
17 unmodified lines
12741275 return sum(iterable, start)127612771278@async_variant(sync_do_sum)1279async 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 = start12861287 if attribute is not None:1288 func = make_attrgetter(environment, attribute)1289 else:12901291 def func(x):1292 return x12931294 async for item in auto_aiter(iterable):1295 rv += func(item)12961297 return rv129812991228def do_list(value: "t.Iterable[V]") -> "t.List[V]":1300def 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)130513061307@async_variant(sync_do_list)1308async def do_list(value: "t.Union[t.AsyncIterable[V], t.Iterable[V]]") -> "t.List[V]":1309 return await auto_to_list(value)131013111312def 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 lines
1380 return environment.undefined(obj=obj, name=name)138113821383@typing.overload1307def do_map(1384def sync_do_map(1385 context: "Context", value: t.Iterable, name: str, *args: t.Any, **kwargs: t.Any1386) -> t.Iterable:1387 ...138813891390@typing.overload1314def do_map(1391def sync_do_map(1392 context: "Context",1393 value: t.Iterable,1394 *,1395 attribute: str = ...,
2 unmodified lines
1398 ...139914001401@pass_context1325def do_map(context, value, *args, **kwargs):1402def 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 lines
1445 for item in value:1446 yield func(item)144714481449@typing.overload1450def 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 ...145814591460@typing.overload1461def 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 ...146914701471@async_variant(sync_do_map)1472async def do_map(context, value, *args, **kwargs):1473 if value:1474 func = prepare_map(context, args, kwargs)14751476 async for item in auto_aiter(value):1477 yield await auto_await(func(item))147814791480@pass_context1373def do_select(1481def 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 lines
1507 """1508 return select_or_reject(context, value, args, kwargs, lambda x: x, False)150915101511@async_variant(sync_do_select)1512async 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)151915201521@pass_context1404def do_reject(1522def 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 lines
1543 """1544 return select_or_reject(context, value, args, kwargs, lambda x: not x, False)154515461547@async_variant(sync_do_reject)1548async 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)155515561557@pass_context1430def do_selectattr(1558def 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 the
20 unmodified lines
1583 """1584 return select_or_reject(context, value, args, kwargs, lambda x: x, True)158515861587@async_variant(sync_do_selectattr)1588async 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)159515961597@pass_context1460def do_rejectattr(1598def 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 test
18 unmodified lines
1621 """1622 return select_or_reject(context, value, args, kwargs, lambda x: not x, True)162316241625@async_variant(sync_do_rejectattr)1626async 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)163316341635@pass_eval_context1636def do_tojson(1637 eval_ctx: "EvalContext", value: t.Any, indent: t.Optional[int] = None1638) -> Markup:
99 unmodified lines
1738 if func(item):1739 yield item174017411742async 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)17521753 async for item in auto_aiter(value):1754 if func(item):1755 yield item175617571758FILTERS = {1759 "abs": abs,1760 "attr": do_attr,1761 "batch": do_batch,
51 unmodified lines
modified:src/jinja2/nativetypes.py+3 added-4 removed
84 unmodified lines
85 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))9091 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()9596 async def render_async(self, *args, **kwargs):
1 unmodified line
98 raise RuntimeError(99 "The environment was not created with async mode enabled."100 )101102 vars = dict(*args, **kwargs)103 ctx = self.new_context(vars)102 ctx = self.new_context(dict(*args, **kwargs))103104 try:105 return native_concat([n async for n in self.root_render_func(ctx)])106 except Exception:
4 unmodified lines
modified:src/jinja2/runtime.py+102 added-2 removed
7 unmodified lines
8from markupsafe import escape # noqa: F4019from markupsafe import Markup10from markupsafe import soft_str1112from .async_utils import auto_aiter13from .async_utils import auto_await # noqa: F40114from .exceptions import TemplateNotFound # noqa: F40115from .exceptions import TemplateRuntimeError # noqa: F40116from .exceptions import UndefinedError17from .nodes import EvalContext
25 unmodified lines
43 "Namespace",44 "Undefined",45 "internalcode",46]47async_exported = [48 "AsyncLoopContext",49 "auto_aiter",50 "auto_await",51]525354def identity(x):55 """Returns its argument. Useful for certain things in the
319 unmodified lines
375 )376 return BlockReference(self.name, self._context, self._stack, self._depth + 1)377378 @internalcode379 async def _async_call(self):380 rv = concat([x async for x in self._stack[self._depth](self._context)])381382 if self._context.eval_ctx.autoescape:383 return Markup(rv)384385 return rv386387 @internalcode388 def __call__(self):389 if self._context.environment.is_async:390 return self._async_call()391392 rv = concat(self._stack[self._depth](self._context))393394 if self._context.eval_ctx.autoescape:375 rv = Markup(rv)395 return Markup(rv)396397 return rv398399400class LoopContext:
186 unmodified lines
587 def __repr__(self):588 return f"<{self.__class__.__name__} {self.index}/{self.length}>"589590591class AsyncLoopContext(LoopContext):592 @staticmethod593 def _to_iterator(iterable):594 return auto_aiter(iterable)595596 @property597 async def length(self):598 if self._length is not None:599 return self._length600601 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)607608 return self._length609610 @property611 async def revindex0(self):612 return await self.length - self.index613614 @property615 async def revindex(self):616 return await self.length - self.index0617618 async def _peek_next(self):619 if self._after is not missing:620 return self._after621622 try:623 self._after = await self._iterator.__anext__()624 except StopAsyncIteration:625 self._after = missing626627 return self._after628629 @property630 async def last(self):631 return await self._peek_next() is missing632633 @property634 async def nextitem(self):635 rv = await self._peek_next()636637 if rv is missing:638 return self._undefined("there is no next item")639640 return rv641642 def __aiter__(self):643 return self644645 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__()651652 self.index0 += 1653 self._before = self._current654 self._current = rv655 return rv, self656657658class Macro:659 """Wraps a macro function."""660661 def __init__(
97 unmodified lines
759 )760761 return self._invoke(arguments, autoescape)762763 async def _async_invoke(self, arguments, autoescape):764 rv = await self._func(*arguments)765766 if autoescape:767 return Markup(rv)768769 return rv770771 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)774775 rv = self._func(*arguments)776777 if autoescape:778 rv = Markup(rv)779780 return rv781782 def __repr__(self):783 name = "anonymous" if self.name is None else repr(self.name)
252 unmodified lines
modified:src/jinja2/utils.py-11 removed
18 unmodified lines
1920# special singleton representing missing values for the runtime21missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()2223# internal code23internal_code: t.MutableSet[CodeType] = set()2425concat = "".join2628_slash_escape = "\\/" not in json.dumps("/")273028def 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 lines
828 def __repr__(self):829 return f"<Namespace {self.__attrs!r}>"830831835# does this python version support async for in and async generators?836try:837 exec("async def _():\n async for _ in ():\n yield _")838 have_async_gen = True839except SyntaxError:840 have_async_gen = False841842832class 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 lines
modified:tests/conftest.py+1 added-8 removed
1import os23import pytest45from jinja2 import Environment5from jinja2 import loaders7from jinja2.utils import have_async_gen6from jinja2.environment import Environment7810def pytest_ignore_collect(path):11 if "async" in path.basename and not have_async_gen:12 return True13 return False14159@pytest.fixture10def env():11 """returns a new environment."""12 return Environment()
37 unmodified lines
added:tests/test_async_filters.py+253 added
1from collections import namedtuple23import pytest4from markupsafe import Markup56from jinja2 import Environment7from jinja2.async_utils import auto_aiter8910async def make_aiter(iter):11 for item in iter:12 yield item131415def mark_dualiter(parameter, factory):16 def decorator(f):17 return pytest.mark.parametrize(18 parameter, [lambda: factory(), lambda: make_aiter(factory())]19 )(f)2021 return decorator222324@pytest.fixture25def env_async():26 return Environment(enable_async=True)272829@mark_dualiter("foo", lambda: range(10))30def test_first(env_async, foo):31 tmpl = env_async.from_string("{{ foo()|first }}")32 out = tmpl.render(foo=foo)33 assert out == "0"343536@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)45def 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 ]585960@mark_dualiter("items", lambda: [("a", 1), ("a", 2), ("b", 1)])61def 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|"697071def 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 ]808182@mark_dualiter("articles", make_articles)83def 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 ]959697@mark_dualiter("int_items", lambda: [1, 2, 3])98def 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"102103104@mark_dualiter("string_items", lambda: ["<foo>", Markup("<span>foo</span>")])105def 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) == "&lt;foo&gt;<span>foo</span>"109110111def make_users():112 User = namedtuple("User", "username")113 return map(User, ["foo", "bar"])114115116@mark_dualiter("users", make_users)117def test_join_attribute(env_async, users):118 tmpl = env_async.from_string("""{{ users()|join(', ', 'username') }}""")119 assert tmpl.render(users=users) == "foo, bar"120121122@mark_dualiter("items", lambda: [1, 2, 3, 4, 5])123def test_simple_reject(env_async, items):124 tmpl = env_async.from_string('{{ items()|reject("odd")|join("|") }}')125 assert tmpl.render(items=items) == "2|4"126127128@mark_dualiter("items", lambda: [None, False, 0, 1, 2, 3, 4, 5])129def test_bool_reject(env_async, items):130 tmpl = env_async.from_string('{{ items()|reject|join("|") }}')131 assert tmpl.render(items=items) == "None|False|0"132133134@mark_dualiter("items", lambda: [1, 2, 3, 4, 5])135def 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"138139140@mark_dualiter("items", lambda: [None, False, 0, 1, 2, 3, 4, 5])141def 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"144145146def 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 ]153154155@mark_dualiter("users", make_users)156def 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"161162163@mark_dualiter("items", lambda: list("123"))164def test_simple_map(env_async, items):165 tmpl = env_async.from_string('{{ items()|map("int")|sum }}')166 assert tmpl.render(items=items) == "6"167168169def 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]"172173174@mark_dualiter("users", make_users)175def 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"178179180def test_empty_map(env_async):181 tmpl = env_async.from_string('{{ none|map("upper")|list }}')182 assert tmpl.render() == "[]"183184185@mark_dualiter("items", lambda: [1, 2, 3, 4, 5, 6])186def test_sum(env_async, items):187 tmpl = env_async.from_string("""{{ items()|sum }}""")188 assert tmpl.render(items=items) == "21"189190191@mark_dualiter("items", lambda: [{"value": 23}, {"value": 1}, {"value": 18}])192def test_sum_attributes(env_async, items):193 tmpl = env_async.from_string("""{{ items()|sum('value') }}""")194 assert tmpl.render(items=items)195196197def 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 )209210211def 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"214215216@mark_dualiter("items", lambda: range(10))217def 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 )226227228def test_custom_async_filter(env_async):229 async def customfilter(val):230 return str(val)231232 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"236237238@mark_dualiter("items", lambda: range(10))239def 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)247248 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 lines
5from jinja2 import ChainableUndefined6from jinja2 import DictLoader7from jinja2 import Environment8from jinja2 import Template9from jinja2.asyncsupport import auto_aiter9from jinja2.async_utils import auto_aiter10from jinja2.exceptions import TemplateNotFound11from jinja2.exceptions import TemplatesNotFound12from jinja2.exceptions import UndefinedError13from jinja2.nativetypes import NativeEnvironment
615 unmodified lines
deleted:tests/test_asyncfilters.py-253 removed
1from collections import namedtuple23import pytest4from markupsafe import Markup56from jinja2 import Environment7from jinja2.asyncsupport import auto_aiter8910async def make_aiter(iter):11 for item in iter:12 yield item131415def mark_dualiter(parameter, factory):16 def decorator(f):17 return pytest.mark.parametrize(18 parameter, [lambda: factory(), lambda: make_aiter(factory())]19 )(f)2021 return decorator222324@pytest.fixture25def env_async():26 return Environment(enable_async=True)272829@mark_dualiter("foo", lambda: range(10))30def test_first(env_async, foo):31 tmpl = env_async.from_string("{{ foo()|first }}")32 out = tmpl.render(foo=foo)33 assert out == "0"343536@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)45def 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 ]585960@mark_dualiter("items", lambda: [("a", 1), ("a", 2), ("b", 1)])61def 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|"697071def 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 ]808182@mark_dualiter("articles", make_articles)83def 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 ]959697@mark_dualiter("int_items", lambda: [1, 2, 3])98def 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"102103104@mark_dualiter("string_items", lambda: ["<foo>", Markup("<span>foo</span>")])105def 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) == "&lt;foo&gt;<span>foo</span>"109110111def make_users():112 User = namedtuple("User", "username")113 return map(User, ["foo", "bar"])114115116@mark_dualiter("users", make_users)117def test_join_attribute(env_async, users):118 tmpl = env_async.from_string("""{{ users()|join(', ', 'username') }}""")119 assert tmpl.render(users=users) == "foo, bar"120121122@mark_dualiter("items", lambda: [1, 2, 3, 4, 5])123def test_simple_reject(env_async, items):124 tmpl = env_async.from_string('{{ items()|reject("odd")|join("|") }}')125 assert tmpl.render(items=items) == "2|4"126127128@mark_dualiter("items", lambda: [None, False, 0, 1, 2, 3, 4, 5])129def test_bool_reject(env_async, items):130 tmpl = env_async.from_string('{{ items()|reject|join("|") }}')131 assert tmpl.render(items=items) == "None|False|0"132133134@mark_dualiter("items", lambda: [1, 2, 3, 4, 5])135def 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"138139140@mark_dualiter("items", lambda: [None, False, 0, 1, 2, 3, 4, 5])141def 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"144145146def 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 ]153154155@mark_dualiter("users", make_users)156def 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"161162163@mark_dualiter("items", lambda: list("123"))164def test_simple_map(env_async, items):165 tmpl = env_async.from_string('{{ items()|map("int")|sum }}')166 assert tmpl.render(items=items) == "6"167168169def 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]"172173174@mark_dualiter("users", make_users)175def 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"178179180def test_empty_map(env_async):181 tmpl = env_async.from_string('{{ none|map("upper")|list }}')182 assert tmpl.render() == "[]"183184185@mark_dualiter("items", lambda: [1, 2, 3, 4, 5, 6])186def test_sum(env_async, items):187 tmpl = env_async.from_string("""{{ items()|sum }}""")188 assert tmpl.render(items=items) == "21"189190191@mark_dualiter("items", lambda: [{"value": 23}, {"value": 1}, {"value": 18}])192def test_sum_attributes(env_async, items):193 tmpl = env_async.from_string("""{{ items()|sum('value') }}""")194 assert tmpl.render(items=items)195196197def 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 )209210211def 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"214215216@mark_dualiter("items", lambda: range(10))217def 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 )226227228def test_custom_async_filter(env_async):229 async def customfilter(val):230 return str(val)231232 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"236237238@mark_dualiter("items", lambda: range(10))239def 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)247248 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 lines
69 ``evalcontextfilter``70 - ``pass_environment`` replaces ``environmentfunction`` and71 ``environmentfilter``.7273- Async support no longer requires Jinja to patch itself. It must74 still be enabled with ``Environment(enable_async=True)``.75 :issue:`1390`767778Version 2.11.379--------------8081Released 2021-01-31
778 unmodified lines