Skip to content
Myr

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

5 files+258 added−38 removed

modified:jinja2/asyncsupport.py+30 added-5 removed
151 unmodified lines
152 return await value153 return value154155156async def auto_iter(iterable):156async def auto_aiter(iterable):157 if hasattr(iterable, '__aiter__'):158 async for item in iterable:159 yield item160 return
2 unmodified lines
163164165class AsyncLoopContext(LoopContextBase):166167 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 = length173174 @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._length180181 def __aiter__(self):182 return AsyncLoopContextIterator(self)183184
19 unmodified lines
204 return next_elem, ctx205206207async 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 lines
783 self.writeline('dummy = lambda *x: None')784785 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')788789 # 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 lines
11431144 # 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 line
1165 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 lines
1207 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 lines
modified:jinja2/environment.py+18 added
990 unmodified lines
991 exc_info = sys.exc_info()992 return self.environment.handle_exception(exc_info, True)993994 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.998999 Example usage::10001001 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 lines
1028 return1029 yield self.environment.handle_exception(exc_info, True)10301031 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 lines
1056 """1057 return TemplateModule(self, self.new_context(vars, shared, locals))10581059 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 lines
1083 >>> str(t.module)1084 '23'1085 >>> t.module.foo() == u'42'1086 True10871088 This attribute is not available if async mode is enabled.1089 """1090 return self._get_default_module()10911092 def get_corresponding_lineno(self, lineno):
168 unmodified lines
modified:jinja2/runtime.py+24 added-24 removed
284 unmodified lines
285286 _after = _last_iteration287 _length = None288289 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 = depth0293294 # 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 = None302294 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 lines
318 # the the loop without or with too many arguments.319 __call__ = loop320 del loop321331 @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._length343322 def __repr__(self):323 return '<%s %r/%r>' % (324 self.__class__.__name__,325 self.index,
3 unmodified lines
329330class LoopContext(LoopContextBase):331332 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)335336 # 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()345346 @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._length358359 def __iter__(self):360 return LoopContextIterator(self)361362 def _safe_next(self):
314 unmodified lines
modified:tests/test_async.py+176 added-1 removed
1 unmodified line
2import asyncio34from jinja2 import Template, Environment, DictLoader5from jinja2.utils import have_async_gen6from jinja2.exceptions import TemplateNotFound, TemplatesNotFound6from jinja2.exceptions import TemplateNotFound, TemplatesNotFound, \7 UndefinedError8910def run(coro):11 loop = asyncio.get_event_loop()
240 unmodified lines
252 {% endmacro %}253 {{ outer("FOO") }}254 """)255 assert t.render().strip() == '(FOO)'256257258@pytest.mark.skipif(not have_async_gen, reason='No async generators')259@pytest.mark.core_tags260@pytest.mark.for_loop261class TestAsyncForLoop(object):262263 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'266267 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() == '...'271272 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() == '<>'275276 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('|')288289 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'296297 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>' * 4303304 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 output308309 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'316317 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)320321 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]>]'330331 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]>]'340341 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]>]'350351 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]'359360 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'365366 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() == ''373374 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]'382383 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]'389390 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'397398 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=[])) == ''403404 def test_call_in_loop(self, test_env_async):405 t = test_env_async.from_string('''406 {%- macro do_something() -%}407 [{{ caller() }}]408 {%- endmacro %}409410 {%- for i in [1, 2, 3] %}411 {%- call do_something() -%}412 {{ i }}413 {%- endcall %}414 {%- endfor -%}415 ''')416 assert t.render() == '[1][2][3]'417418 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...'425426 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'