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
Provenance
- Commit
d4e14fc- Tree
d817c60- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
aa188fd
4 files changed+87 added−17 removed
modified:jinja2/asyncsupport.py+43 added
2 unmodified lines3 import inspect4 5 from jinja2.utils import concat, internalcode, concat, Markup6 from jinja2.environment import TemplateModule7+from jinja2.runtime import LoopContextBase, _last_iteration8 9 10 async def concat_async(async_gen):11 rv = []132 unmodified lines144 yield item145 return146 for item in iterable:147 yield item148+149+150+class AsyncLoopContext(LoopContextBase):151+152+ 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 = after156+157+ def __aiter__(self):158+ return AsyncLoopContextIterator(self)159+160+161+class AsyncLoopContextIterator(object):162+ __slots__ = ('context',)163+164+ def __init__(self, context):165+ self.context = context166+167+ def __aiter__(self):168+ return self169+170+ 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, ctx181+182+183+async 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 lines782 if not unoptimize_before_dead_code:783 self.writeline('dummy = lambda *x: None')784 785 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')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 ''340 unmodified lines1132 self.position(node)))1133 1134 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 ')1143 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:17 unmodified lines1164 1165 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(')')1173 1174 if node.recursive:1175 self.write(', loop_render_func, depth):')569 unmodified linesmodified:jinja2/runtime.py+21 added-12 removed
278 unmodified lines279 rv = Markup(rv)280 return rv281 282 283-class LoopContext(object):283+class LoopContextBase(object):284 """A loop context for dynamic iteration."""285 286+ _after = _last_iteration287+ _length = None288+289 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 = depth0293 294 # try to get the length of the iterable early. This must be done20 unmodified lines315 316 def __len__(self):317 return self.length318 318- def __iter__(self):319- return LoopContextIterator(self)320-321- def _safe_next(self):322- try:323- return next(self._iterator)324- except StopIteration:325- return _last_iteration326-319 @internalcode320 def loop(self, iterable):321 if self._recurse is None:322 raise TypeError('Tried to call non recursive loop. Maybe you '25 unmodified lines348 self.length349 )350 351 352+class LoopContext(LoopContextBase):353+354+ 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()358+359+ def __iter__(self):360+ return LoopContextIterator(self)361+362+ def _safe_next(self):363+ try:364+ return next(self._iterator)365+ except StopIteration:366+ return _last_iteration367+368+369 @implements_iterator370 class LoopContextIterator(object):371 """The iterator for a loop context."""372 __slots__ = ('context',)304 unmodified linesmodified:tests/test_async.py+12 added-1 removed
95 unmodified lines96 assert rv == ['1', '2', '3']97 98 99 @pytest.mark.skipif(not have_async_gen, reason='No async generators')100-def test_async_iteration_in_tmeplates():100+def 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 line106 rv = list(t.generate(rng=async_iterator()))107 assert rv == ['1', '2', '3']108 109 110+@pytest.mark.skipif(not have_async_gen, reason='No async generators')111+def 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']119+120+121 @pytest.fixture122 def test_env_async():123 env = Environment(loader=DictLoader(dict(124 module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',130 unmodified lines