async templates await attribute access
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 24d86a9 · Browse files · 4 files·+49 added−25 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+49 added−25 removed
- tests:+24 added−20 removed
- other:+25 added−5 removed
Provenance
- Commit
4d0949b- Tree
da55a67- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
24d86a9
4 files changed+49 added−25 removed
modified:jinja2/compiler.py+12 added
1549 unmodified lines1550 self.visit(node.expr, frame)1551 1552 @optimizeconst1553 def visit_Getattr(self, node, frame):1554+ if self.environment.is_async:1555+ self.write("await auto_await(")1556+1557 self.write('environment.getattr(')1558 self.visit(node.node, frame)1559 self.write(', %r)' % node.attr)1560 1561+ if self.environment.is_async:1562+ self.write(")")1563+1564 @optimizeconst1565 def visit_Getitem(self, node, frame):1566 # slices bypass the environment getitem method.1567 if isinstance(node.arg, nodes.Slice):1 unmodified line1569 self.write('[')1570 self.visit(node.arg, frame)1571 self.write(']')1572 else:1573+ if self.environment.is_async:1574+ self.write("await auto_await(")1575+1576 self.write('environment.getitem(')1577 self.visit(node.node, frame)1578 self.write(', ')1579 self.visit(node.arg, frame)1580 self.write(')')1581 1582+ if self.environment.is_async:1583+ self.write(")")1584+1585 def visit_Slice(self, node, frame):1586 if node.start is not None:1587 self.visit(node.start, frame)1588 self.write(':')157 unmodified linesmodified:tests/test_async.py+12 added-20 removed
1 import pytest2 import asyncio3 4 from jinja2 import Template, Environment, DictLoader5+from jinja2.asyncsupport import auto_aiter6 from jinja2.exceptions import TemplateNotFound, TemplatesNotFound, \7 UndefinedError8 9 264 unmodified lines274 def test_empty_blocks(self, test_env_async):275 tmpl = test_env_async.from_string('<{% for item in seq %}{% else %}{% endfor %}>')276 assert tmpl.render() == '<>'277 277- def test_context_vars(self, test_env_async):278- slist = [42, 24]279- for seq in [slist, iter(slist), reversed(slist), (_ for _ in slist)]:280- tmpl = test_env_async.from_string('''{% for item in seq -%}281- {{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{282- loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{283- loop.length }}###{% endfor %}''')284- one, two, _ = tmpl.render(seq=seq).split('###')285- (one_index, one_index0, one_revindex, one_revindex0, one_first,286- one_last, one_length) = one.split('|')287- (two_index, two_index0, two_revindex, two_revindex0, two_first,288- two_last, two_length) = two.split('|')278+ @pytest.mark.parametrize(279+ "transform", [lambda x: x, iter, reversed, lambda x: (i for i in x), auto_aiter]280+ )281+ def test_context_vars(self, test_env_async, transform):282+ t = test_env_async.from_string(283+ "{% for item in seq %}{{ loop.index }}|{{ loop.index0 }}"284+ "|{{ loop.revindex }}|{{ loop.revindex0 }}|{{ loop.first }}"285+ "|{{ loop.last }}|{{ loop.length }}\n{% endfor %}"286+ )287+ out = t.render(seq=transform([42, 24]))288+ assert out == "1|0|2|1|True|False|2\n2|1|1|0|False|True|2\n"289 290- assert int(one_index) == 1 and int(two_index) == 2291- assert int(one_index0) == 0 and int(two_index0) == 1292- assert int(one_revindex) == 2 and int(two_revindex) == 1293- assert int(one_revindex0) == 1 and int(two_revindex0) == 0294- assert one_first == 'True' and two_first == 'False'295- assert one_last == 'False' and two_last == 'True'296- assert one_length == two_length == '2'297-290 def test_cycling(self, test_env_async):291 tmpl = test_env_async.from_string('''{% for item in seq %}{{292 loop.cycle('<1>', '<2>') }}{% endfor %}{%293 for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')209 unmodified linesmodified:tests/test_runtime.py+12 added
1+import itertools2+3 from jinja2 import Template4 from jinja2.runtime import LoopContext5 6 40 unmodified lines47 def test_loopcontext2():48 in_lst = [10, 11]49 l = LoopContext(reversed(in_lst), None)50 assert l.length == len(in_lst)51+52+53+def test_iterator_not_advanced_early():54+ t = Template("{% for _, g in gs %}{{ loop.index }} {{ g|list }}\n{% endfor %}")55+ out = t.render(gs=itertools.groupby(56+ [(1, "a"), (1, "b"), (2, "c"), (3, "d")], lambda x: x[0]57+ ))58+ # groupby groups depend on the current position of the iterator. If59+ # it was advanced early, the lists would appear empty.60+ assert out == "1 [(1, 'a'), (1, 'b')]\n2 [(2, 'c')]\n3 [(3, 'd')]\n"modified:CHANGES.rst+13 added-5 removed
3 unmodified lines4 --------------5 6 Unreleased7 8-- Async support is only loaded the first time an9- :class:`~environment.Environment` enables it, in order to avoid a10- slow initial import. :issue:`765`11-- Python 2.6 and 3.3 are not supported anymore.8+- Python 2.6, 3.3, and 3.4 are not supported anymore.12-- The ``map`` filter in async mode now automatically awaits9 - Added a new ``ChainableUndefined`` class to support getitem and10 getattr on an undefined object. :issue:`977`11 - Allow ``{%+`` syntax (with NOP behavior) when ``lstrip_blocks`` is12 disabled. :issue:`748`29 unmodified lines42 :class:`StrictUndefined`). :issue:`710`, :pr:`1079`43 - Fix behavior of ``loop`` control variables such as ``length`` and44 ``revindex0`` when looping over a generator. :issue:`459, 751, 794`,45 :pr:`993`46+- Async support is only loaded the first time an environment enables47+ it, in order to avoid a slow initial import. :issue:`765`48+- In async environments, the ``|map`` filter will await the filter49+ call if needed. :pr:`913`50+- In for loops that access ``loop`` attributes, the iterator is not51+ advanced ahead of the current iteration unless ``length``,52+ ``revindex``, ``nextitem``, or ``last`` are accessed. This makes it53+ less likely to break ``groupby`` results. :issue:`555`, :pr:`1101`54+- In async environments, the ``loop`` attributes ``length`` and55+ ``revindex`` work for async iterators. :pr:`1101`56+- In async environments, values from attribute/property access will57+ be awaited if needed. :pr:`1101`58 - ``PackageLoader`` doesn't depend on setuptools or pkg_resources.59 :issue:`970`60 - Support :class:`os.PathLike` objects in61 :class:`~loader.FileSystemLoader` and :class:`~loader.ModuleLoader`.649 unmodified lines