Skip to content
Myr

Added support for async loop context

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 aa188fd · Browse files · 4 files+87 added−17 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+87 added−17 removed

  • tests:+12 added−1 removed
  • other:+75 added−16 removed

4 files+87 added−17 removed

modified:jinja2/asyncsupport.py+43 added
2 unmodified lines
3import inspect45from jinja2.utils import concat, internalcode, concat, Markup6from jinja2.environment import TemplateModule7from jinja2.runtime import LoopContextBase, _last_iteration8910async def concat_async(async_gen):11 rv = []
132 unmodified lines
144 yield item145 return146 for item in iterable:147 yield item148149150class AsyncLoopContext(LoopContextBase):151152 def __init__(self, async_iterator, iterable, after, recurse=None, depth0=0):153 self._async_iterator = async_iterator154 LoopContextBase.__init__(self, iterable, recurse, depth0)155 self._after = after156157 def __aiter__(self):158 return AsyncLoopContextIterator(self)159160161class AsyncLoopContextIterator(object):162 __slots__ = ('context',)163164 def __init__(self, context):165 self.context = context166167 def __aiter__(self):168 return self169170 async def __anext__(self):171 ctx = self.context172 ctx.index0 += 1173 if ctx._after is _last_iteration:174 raise StopAsyncIteration()175 next_elem = ctx._after176 try:177 ctx._after = await ctx._async_iterator.__anext__()178 except StopAsyncIteration:179 ctx._after = _last_iteration180 return next_elem, ctx181182183async def make_async_loop_context(iterable, recurse=None, depth0=0):184 async_iterator = auto_iter(iterable)185 try:186 after = await async_iterator.__anext__()187 except StopAsyncIteration:188 after = _last_iteration189 return AsyncLoopContext(async_iterator, iterable, after, recurse, depth0)
modified:jinja2/compiler.py+11 added-4 removed
781 unmodified lines
782 if not unoptimize_before_dead_code:783 self.writeline('dummy = lambda *x: None')784785 if self.environment._async:786 self.writeline('from jinja2.asyncsupport import auto_await, auto_iter')786 self.writeline('from jinja2.asyncsupport import auto_await, '787 'auto_iter, 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 ''
340 unmodified lines
1132 self.position(node)))11331134 self.writeline(self.environment._async and 'async for ' or 'for ', node)1135 self.visit(node.target, loop_frame)1135 self.write(extended_loop and ', l_loop in LoopContext(' or ' in ')1136 if extended_loop:1137 if self.environment._async:1138 self.write(', l_loop in await make_async_loop_context(')1139 else:1140 self.write(', l_loop in LoopContext(')1141 else:1142 self.write(' in ')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:
17 unmodified lines
11641165 elif node.recursive:1166 self.write('reciter')1167 else:1161 if self.environment._async:1168 if self.environment._async and not extended_loop:1169 self.write('auto_iter(')1170 self.visit(node.iter, loop_frame)1164 if self.environment._async:1171 if self.environment._async and not extended_loop:1172 self.write(')')11731174 if node.recursive:1175 self.write(', loop_render_func, depth):')
569 unmodified lines
modified:jinja2/runtime.py+21 added-12 removed
278 unmodified lines
279 rv = Markup(rv)280 return rv281282283class LoopContext(object):283class LoopContextBase(object):284 """A loop context for dynamic iteration."""285286 _after = _last_iteration287 _length = None288289 def __init__(self, iterable, recurse=None, depth0=0):287 self._iterator = iter(iterable)290 self._recurse = recurse289 self._after = self._safe_next()291 self.index0 = -1292 self.depth0 = depth0293294 # try to get the length of the iterable early. This must be done
20 unmodified lines
315316 def __len__(self):317 return self.length318318 def __iter__(self):319 return LoopContextIterator(self)320321 def _safe_next(self):322 try:323 return next(self._iterator)324 except StopIteration:325 return _last_iteration326319 @internalcode320 def loop(self, iterable):321 if self._recurse is None:322 raise TypeError('Tried to call non recursive loop. Maybe you '
25 unmodified lines
348 self.length349 )350351352class LoopContext(LoopContextBase):353354 def __init__(self, iterable, recurse=None, depth0=0):355 self._iterator = iter(iterable)356 LoopContextBase.__init__(self, iterable, recurse, depth0)357 self._after = self._safe_next()358359 def __iter__(self):360 return LoopContextIterator(self)361362 def _safe_next(self):363 try:364 return next(self._iterator)365 except StopIteration:366 return _last_iteration367368369@implements_iterator370class LoopContextIterator(object):371 """The iterator for a loop context."""372 __slots__ = ('context',)
304 unmodified lines
modified:tests/test_async.py+12 added-1 removed
95 unmodified lines
96 assert rv == ['1', '2', '3']979899@pytest.mark.skipif(not have_async_gen, reason='No async generators')100def test_async_iteration_in_tmeplates():100def test_async_iteration_in_templates():101 t = Template('{% for x in rng %}{{ x }}{% endfor %}',102 enable_async=True)103 async def async_iterator():104 for item in [1, 2, 3]:
1 unmodified line
106 rv = list(t.generate(rng=async_iterator()))107 assert rv == ['1', '2', '3']108109110@pytest.mark.skipif(not have_async_gen, reason='No async generators')111def test_async_iteration_in_templates_extended():112 t = Template('{% for x in rng %}{{ loop.index0 }}/{{ x }}{% endfor %}',113 enable_async=True)114 async def async_iterator():115 for item in [1, 2, 3]:116 yield item117 rv = list(t.generate(rng=async_iterator()))118 assert rv == ['0/1', '1/2', '2/3']119120121@pytest.fixture122def test_env_async():123 env = Environment(loader=DictLoader(dict(124 module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',
130 unmodified lines