Support the same set of loop functions for async mode
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Armin Ronacher · committed by Armin Ronacher · parent efa5d31 · Browse files · 5 files·+258 added−38 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
5 files+258 added−38 removed
- tests:+176 added−1 removed
- other:+82 added−37 removed
Provenance
- Commit
acab87a- Tree
9c8db70- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
efa5d31
5 files changed+258 added−38 removed
modified:jinja2/asyncsupport.py+30 added-5 removed
151 unmodified lines152 return await value153 return value154 155 156-async def auto_iter(iterable):156+async def auto_aiter(iterable):157 if hasattr(iterable, '__aiter__'):158 async for item in iterable:159 yield item160 return2 unmodified lines163 164 165 class AsyncLoopContext(LoopContextBase):166 167- def __init__(self, async_iterator, iterable, after, recurse=None, depth0=0):167+ def __init__(self, async_iterator, after, length, recurse=None,168+ depth0=0):169+ LoopContextBase.__init__(self, recurse, depth0)170 self._async_iterator = async_iterator169- LoopContextBase.__init__(self, iterable, recurse, depth0)171 self._after = after172+ self._length = length173 174+ @property175+ def length(self):176+ if self._length is None:177+ raise TypeError('Loop length for some iterators cannot be '178+ 'lazily calculated in async mode')179+ return self._length180+181 def __aiter__(self):182 return AsyncLoopContextIterator(self)183 184 19 unmodified lines204 return next_elem, ctx205 206 207 async def make_async_loop_context(iterable, recurse=None, depth0=0):199- async_iterator = auto_iter(iterable)208+ # Length is more complicated and less efficient in async mode. The209+ # reason for this is that we cannot know if length will be used210+ # upfront but because length is a property we cannot lazily execute it211+ # later. This means that we need to buffer it up and measure :(212+ #213+ # We however only do this for actual iterators, not for async214+ # iterators as blocking here does not seem like the best idea in the215+ # world.216 try:217+ length = len(iterable)218+ except (TypeError, AttributeError):219+ if not hasattr(iterable, '__aiter__'):220+ iterable = tuple(iterable)221+ length = len(iterable)222+ else:223+ length = None224+ async_iterator = auto_aiter(iterable)225+ try:226 after = await async_iterator.__anext__()227 except StopAsyncIteration:228 after = _last_iteration204- return AsyncLoopContext(async_iterator, iterable, after, recurse, depth0)229+ return AsyncLoopContext(async_iterator, after, length, recurse, depth0)modified:jinja2/compiler.py+10 added-8 removed
782 unmodified lines783 self.writeline('dummy = lambda *x: None')784 785 if self.environment._async:786 self.writeline('from jinja2.asyncsupport import auto_await, '787- 'auto_iter, make_async_loop_context')787+ 'auto_aiter, make_async_loop_context')788 789 # if we want a deferred initialization we cannot move the790 # environment into a local name791 envenv = not self.defer_init and ', environment=environment' or ''351 unmodified lines1143 1144 # if we have an extened loop and a node test, we filter in the1145 # "outer frame".1146 if extended_loop and node.test is not None:1147- if self.environment._async:1148- self.fail('loop filters in async mode are unavailable if the '1149- 'loop uses the special "loop" variable or is '1150- 'recursive.', node.lineno)1147 self.write('(')1148 self.visit(node.target, loop_frame)1153- self.write(' for ')1149+ self.write(self.environment._async and ' async for ' or ' for ')1150 self.visit(node.target, loop_frame)1151 self.write(' in ')1152 if node.recursive:1153 self.write('reciter')1154 else:1155+ if self.environment._async:1156+ self.write('auto_aiter(')1157 self.visit(node.iter, loop_frame)1158+ if self.environment._async:1159+ self.write(')')1160 self.write(' if (')1161 test_frame = loop_frame.copy()1162 self.visit(node.test, test_frame)1163 self.write('))')1 unmodified line1165 elif node.recursive:1166 self.write('reciter')1167 else:1168 if self.environment._async and not extended_loop:1169- self.write('auto_iter(')1169+ self.write('auto_aiter(')1170 self.visit(node.iter, loop_frame)1171 if self.environment._async and not extended_loop:1172 self.write(')')1173 33 unmodified lines1207 if node.recursive:1208 self.return_buffer_contents(loop_frame)1209 self.outdent()1210 self.start_write(frame, node)1211+ if self.environment._async:1212+ self.write('await ')1213 self.write('loop(')1214 if self.environment._async:1213- self.write('auto_iter(')1215+ self.write('auto_aiter(')1216 self.visit(node.iter, frame)1217 if self.environment._async:1218 self.write(')')1219 self.write(', loop)')527 unmodified linesmodified:jinja2/environment.py+18 added
990 unmodified lines991 exc_info = sys.exc_info()992 return self.environment.handle_exception(exc_info, True)993 994 def render_async(self, *args, **kwargs):995+ """This works similar to :meth:`render` but returns a coroutine996+ that when awaited returns the entire rendered template string. This997+ requires the async feature to be enabled.998+999+ Example usage::1000+1001+ await template.render_async(knights='that say nih; asynchronously')1002+ """1003 # see asyncsupport for the actual implementation1004 raise NotImplementedError('This feature is not available for this '1005 'version of Python')1006 21 unmodified lines1028 return1029 yield self.environment.handle_exception(exc_info, True)1030 1031 def generate_async(self, *args, **kwargs):1032+ """An async version of :meth:`generate`. Works very similarly but1033+ returns an async iterator instead.1034+ """1035 # see asyncsupport for the actual implementation1036 raise NotImplementedError('This feature is not available for this '1037 'version of Python')1038 17 unmodified lines1056 """1057 return TemplateModule(self, self.new_context(vars, shared, locals))1058 1059 def make_module_async(self, vars=None, shared=False, locals=None):1060+ """As template module creation can invoke template code for1061+ asynchronous exections this method must be used instead of the1062+ normal :meth:`make_module` one. Likewise the module attribute1063+ becomes unavailable in async mode.1064+ """1065 # see asyncsupport for the actual implementation1066 raise NotImplementedError('This feature is not available for this '1067 'version of Python')1068 14 unmodified lines1083 >>> str(t.module)1084 '23'1085 >>> t.module.foo() == u'42'1086 True1087+1088+ This attribute is not available if async mode is enabled.1089 """1090 return self._get_default_module()1091 1092 def get_corresponding_lineno(self, lineno):168 unmodified linesmodified:jinja2/runtime.py+24 added-24 removed
284 unmodified lines285 286 _after = _last_iteration287 _length = None288 289- def __init__(self, iterable, recurse=None, depth0=0):289+ def __init__(self, recurse=None, depth0=0):290 self._recurse = recurse291 self.index0 = -1292 self.depth0 = depth0293 294- # try to get the length of the iterable early. This must be done295- # here because there are some broken iterators around where there296- # __len__ is the number of iterations left (i'm looking at your297- # listreverseiterator!).298- try:299- self._length = len(iterable)300- except (TypeError, AttributeError):301- self._length = None302-294 def cycle(self, *args):295 """Cycles among the arguments with the current loop index."""296 if not args:297 raise TypeError('no items for cycling given')20 unmodified lines318 # the the loop without or with too many arguments.319 __call__ = loop320 del loop321 331- @property332- def length(self):333- if self._length is None:334- # if was not possible to get the length of the iterator when335- # the loop context was created (ie: iterating over a generator)336- # we have to convert the iterable into a sequence and use the337- # length of that + the number of iterations so far.338- iterable = tuple(self._iterator)339- self._iterator = iter(iterable)340- iterations_done = self.index0 + 2341- self._length = len(iterable) + iterations_done342- return self._length343-322 def __repr__(self):323 return '<%s %r/%r>' % (324 self.__class__.__name__,325 self.index,3 unmodified lines329 330 class LoopContext(LoopContextBase):331 332 def __init__(self, iterable, recurse=None, depth0=0):333+ LoopContextBase.__init__(self, recurse, depth0)334 self._iterator = iter(iterable)356- LoopContextBase.__init__(self, iterable, recurse, depth0)335+336+ # try to get the length of the iterable early. This must be done337+ # here because there are some broken iterators around where there338+ # __len__ is the number of iterations left (i'm looking at your339+ # listreverseiterator!).340+ try:341+ self._length = len(iterable)342+ except (TypeError, AttributeError):343+ self._length = None344 self._after = self._safe_next()345 346+ @property347+ def length(self):348+ if self._length is None:349+ # if was not possible to get the length of the iterator when350+ # the loop context was created (ie: iterating over a generator)351+ # we have to convert the iterable into a sequence and use the352+ # length of that + the number of iterations so far.353+ iterable = tuple(self._iterator)354+ self._iterator = iter(iterable)355+ iterations_done = self.index0 + 2356+ self._length = len(iterable) + iterations_done357+ return self._length358+359 def __iter__(self):360 return LoopContextIterator(self)361 362 def _safe_next(self):314 unmodified linesmodified:tests/test_async.py+176 added-1 removed
1 unmodified line2 import asyncio3 4 from jinja2 import Template, Environment, DictLoader5 from jinja2.utils import have_async_gen6-from jinja2.exceptions import TemplateNotFound, TemplatesNotFound6+from jinja2.exceptions import TemplateNotFound, TemplatesNotFound, \7+ UndefinedError8 9 10 def run(coro):11 loop = asyncio.get_event_loop()240 unmodified lines252 {% endmacro %}253 {{ outer("FOO") }}254 """)255 assert t.render().strip() == '(FOO)'256+257+258+@pytest.mark.skipif(not have_async_gen, reason='No async generators')259+@pytest.mark.core_tags260+@pytest.mark.for_loop261+class TestAsyncForLoop(object):262+263+ def test_simple(self, test_env_async):264+ tmpl = test_env_async.from_string('{% for item in seq %}{{ item }}{% endfor %}')265+ assert tmpl.render(seq=list(range(10))) == '0123456789'266+267+ def test_else(self, test_env_async):268+ tmpl = test_env_async.from_string(269+ '{% for item in seq %}XXX{% else %}...{% endfor %}')270+ assert tmpl.render() == '...'271+272+ def test_empty_blocks(self, test_env_async):273+ tmpl = test_env_async.from_string('<{% for item in seq %}{% else %}{% endfor %}>')274+ assert tmpl.render() == '<>'275+276+ def test_context_vars(self, test_env_async):277+ slist = [42, 24]278+ for seq in [slist, iter(slist), reversed(slist), (_ for _ in slist)]:279+ tmpl = test_env_async.from_string('''{% for item in seq -%}280+ {{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{281+ loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{282+ loop.length }}###{% endfor %}''')283+ one, two, _ = tmpl.render(seq=seq).split('###')284+ (one_index, one_index0, one_revindex, one_revindex0, one_first,285+ one_last, one_length) = one.split('|')286+ (two_index, two_index0, two_revindex, two_revindex0, two_first,287+ two_last, two_length) = two.split('|')288+289+ assert int(one_index) == 1 and int(two_index) == 2290+ assert int(one_index0) == 0 and int(two_index0) == 1291+ assert int(one_revindex) == 2 and int(two_revindex) == 1292+ assert int(one_revindex0) == 1 and int(two_revindex0) == 0293+ assert one_first == 'True' and two_first == 'False'294+ assert one_last == 'False' and two_last == 'True'295+ assert one_length == two_length == '2'296+297+ def test_cycling(self, test_env_async):298+ tmpl = test_env_async.from_string('''{% for item in seq %}{{299+ loop.cycle('<1>', '<2>') }}{% endfor %}{%300+ for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')301+ output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))302+ assert output == '<1><2>' * 4303+304+ def test_scope(self, test_env_async):305+ tmpl = test_env_async.from_string('{% for item in seq %}{% endfor %}{{ item }}')306+ output = tmpl.render(seq=list(range(10)))307+ assert not output308+309+ def test_varlen(self, test_env_async):310+ def inner():311+ for item in range(5):312+ yield item313+ tmpl = test_env_async.from_string('{% for item in iter %}{{ item }}{% endfor %}')314+ output = tmpl.render(iter=inner())315+ assert output == '01234'316+317+ def test_noniter(self, test_env_async):318+ tmpl = test_env_async.from_string('{% for item in none %}...{% endfor %}')319+ pytest.raises(TypeError, tmpl.render)320+321+ def test_recursive(self, test_env_async):322+ tmpl = test_env_async.from_string('''{% for item in seq recursive -%}323+ [{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]324+ {%- endfor %}''')325+ assert tmpl.render(seq=[326+ dict(a=1, b=[dict(a=1), dict(a=2)]),327+ dict(a=2, b=[dict(a=1), dict(a=2)]),328+ dict(a=3, b=[dict(a='a')])329+ ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'330+331+ def test_recursive_depth0(self, test_env_async):332+ tmpl = test_env_async.from_string('''{% for item in seq recursive -%}333+ [{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]334+ {%- endfor %}''')335+ assert tmpl.render(seq=[336+ dict(a=1, b=[dict(a=1), dict(a=2)]),337+ dict(a=2, b=[dict(a=1), dict(a=2)]),338+ dict(a=3, b=[dict(a='a')])339+ ]) == '[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]'340+341+ def test_recursive_depth(self, test_env_async):342+ tmpl = test_env_async.from_string('''{% for item in seq recursive -%}343+ [{{ loop.depth }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]344+ {%- endfor %}''')345+ assert tmpl.render(seq=[346+ dict(a=1, b=[dict(a=1), dict(a=2)]),347+ dict(a=2, b=[dict(a=1), dict(a=2)]),348+ dict(a=3, b=[dict(a='a')])349+ ]) == '[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]'350+351+ def test_looploop(self, test_env_async):352+ tmpl = test_env_async.from_string('''{% for row in table %}353+ {%- set rowloop = loop -%}354+ {% for cell in row -%}355+ [{{ rowloop.index }}|{{ loop.index }}]356+ {%- endfor %}357+ {%- endfor %}''')358+ assert tmpl.render(table=['ab', 'cd']) == '[1|1][1|2][2|1][2|2]'359+360+ def test_reversed_bug(self, test_env_async):361+ tmpl = test_env_async.from_string('{% for i in items %}{{ i }}'362+ '{% if not loop.last %}'363+ ',{% endif %}{% endfor %}')364+ assert tmpl.render(items=reversed([3, 2, 1])) == '1,2,3'365+366+ def test_loop_errors(self, test_env_async):367+ tmpl = test_env_async.from_string('''{% for item in [1] if loop.index368+ == 0 %}...{% endfor %}''')369+ pytest.raises(UndefinedError, tmpl.render)370+ tmpl = test_env_async.from_string('''{% for item in [] %}...{% else371+ %}{{ loop }}{% endfor %}''')372+ assert tmpl.render() == ''373+374+ def test_loop_filter(self, test_env_async):375+ tmpl = test_env_async.from_string('{% for item in range(10) if item '376+ 'is even %}[{{ item }}]{% endfor %}')377+ assert tmpl.render() == '[0][2][4][6][8]'378+ tmpl = test_env_async.from_string('''379+ {%- for item in range(10) if item is even %}[{{380+ loop.index }}:{{ item }}]{% endfor %}''')381+ assert tmpl.render() == '[1:0][2:2][3:4][4:6][5:8]'382+383+ def test_scoped_special_var(self, test_env_async):384+ t = test_env_async.from_string(385+ '{% for s in seq %}[{{ loop.first }}{% for c in s %}'386+ '|{{ loop.first }}{% endfor %}]{% endfor %}')387+ assert t.render(seq=('ab', 'cd')) \388+ == '[True|True|False][False|True|False]'389+390+ def test_scoped_loop_var(self, test_env_async):391+ t = test_env_async.from_string('{% for x in seq %}{{ loop.first }}'392+ '{% for y in seq %}{% endfor %}{% endfor %}')393+ assert t.render(seq='ab') == 'TrueFalse'394+ t = test_env_async.from_string('{% for x in seq %}{% for y in seq %}'395+ '{{ loop.first }}{% endfor %}{% endfor %}')396+ assert t.render(seq='ab') == 'TrueFalseTrueFalse'397+398+ def test_recursive_empty_loop_iter(self, test_env_async):399+ t = test_env_async.from_string('''400+ {%- for item in foo recursive -%}{%- endfor -%}401+ ''')402+ assert t.render(dict(foo=[])) == ''403+404+ def test_call_in_loop(self, test_env_async):405+ t = test_env_async.from_string('''406+ {%- macro do_something() -%}407+ [{{ caller() }}]408+ {%- endmacro %}409+410+ {%- for i in [1, 2, 3] %}411+ {%- call do_something() -%}412+ {{ i }}413+ {%- endcall %}414+ {%- endfor -%}415+ ''')416+ assert t.render() == '[1][2][3]'417+418+ def test_scoping_bug(self, test_env_async):419+ t = test_env_async.from_string('''420+ {%- for item in foo %}...{{ item }}...{% endfor %}421+ {%- macro item(a) %}...{{ a }}...{% endmacro %}422+ {{- item(2) -}}423+ ''')424+ assert t.render(foo=(1,)) == '...1......2...'425+426+ def test_unpacking(self, test_env_async):427+ tmpl = test_env_async.from_string('{% for a, b, c in [[1, 2, 3]] %}'428+ '{{ a }}|{{ b }}|{{ c }}{% endfor %}')429+ assert tmpl.render() == '1|2|3'