Skip to content
Myr

Automatically await on function calls if necessary

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 b11056d · Browse files · 3 files+35 added−0 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+35 added−0 removed

  • tests:+21 added−0 removed
  • other:+14 added−0 removed

3 files+35 added−0 removed

modified:jinja2/asyncsupport.py+7 added
1import sys2import asyncio3import inspect45from jinja2.utils import concat67
33 unmodified lines
414243def patch_all():44 patch_template()454647async def auto_await(value):48 if inspect.isawaitable(value):49 return await value50 return value
modified:jinja2/compiler.py+7 added
780 unmodified lines
781 self.writeline('from jinja2.runtime import ' + ', '.join(exported))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')787788 # if we want a deferred initialization we cannot move the789 # environment into a local name790 envenv = not self.defer_init and ', environment=environment' or ''791
835 unmodified lines
1627 write_expr2()1628 self.write(')')16291630 def visit_Call(self, node, frame, forward_caller=False):1631 if self.environment._async:1632 self.write('await auto_await(')1633 if self.environment.sandboxed:1634 self.write('environment.call(context, ')1635 else:1636 self.write('context.call(')1637 self.visit(node.node, frame)1638 extra_kwargs = forward_caller and {'caller': 'caller'} or None1639 self.signature(node, frame, extra_kwargs)1640 self.write(')')1641 if self.environment._async:1642 self.write(')')16431644 def visit_Keyword(self, node, frame):1645 self.write(node.key + '=')1646 self.visit(node.value, frame)
62 unmodified lines
modified:tests/test_async.py+21 added
17 unmodified lines
18 return await t.render_async()1920 rv = run(func)21 assert rv == '[1][2][3]'222324@pytest.mark.skipif(not have_async_gen, reason='No async generators')25def test_await_on_calls():26 t = Template('{{ async_func() + normal_func() }}',27 enable_async=True)2829 async def async_func():30 return 423132 def normal_func():33 return 233435 async def func():36 return await t.render_async(37 async_func=async_func,38 normal_func=normal_func39 )4041 rv = run(func)42 assert rv == '65'