Skip to content
Myr

Initial support for async rendering

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 e908a58 · Browse files · 6 files+95 added−12 removed
This commit

State

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

Diff stats

6 files+95 added−12 removed

  • tests:+21 added−0 removed
  • other:+74 added−12 removed

6 files+95 added−12 removed

modified:jinja2/__init__.py+11 added
66 unmodified lines
67 'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape',68 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined',69 'evalcontextfilter', 'evalcontextfunction', 'make_logging_undefined',70]717273def _patch_async():74 from jinja2.utils import have_async_gen75 if have_async_gen:76 from jinja2.asyncsupport import patch_all77 patch_all()787980_patch_async()81del _patch_async
added:jinja2/asyncsupport.py+43 added
1import sys2import asyncio34from jinja2.utils import concat567async def render_async(self, *args, **kwargs):8 if not self.environment._async:9 raise RuntimeError('The environment was not created with async mode '10 'enabled.')1112 vars = dict(*args, **kwargs)13 ctx = self.new_context(vars)14 rv = []15 async def collect():16 async for event in self.root_render_func(ctx):17 rv.append(event)1819 try:20 await collect()21 return concat(rv)22 except Exception:23 exc_info = sys.exc_info()24 return self.environment.handle_exception(exc_info, True)252627def wrap_render_func(original_render):28 def render(self, *args, **kwargs):29 if not self.environment._async:30 return original_render(self, *args, **kwargs)31 loop = asyncio.get_event_loop()32 return loop.run_until_complete(self.render_async(self, *args, **kwargs))33 return render343536def patch_template():37 from jinja2 import Template38 Template.render_async = render_async39 Template.render = wrap_render_func(Template.render)404142def patch_all():43 patch_template()
modified:jinja2/compiler.py+10 added-11 removed
45 unmodified lines
46 code_features.append('generator_stop')47except SyntaxError:48 pass4950# does this python version support async for in and async generators?51try:52 exec('async def _():\n async for _ in ():\n yield _')53 have_async_gen = True54except SyntaxError:55 have_async_gen = False505751# does if 0: dummy(x) get us x into the scope?52def unoptimize_before_dead_code():53 x = 4254 def f():
592 unmodified lines
647 # scopes can trigger a SyntaxError:648 # a = 42; b = lambda: a; del a649 self.writeline(' = '.join(to_delete) + ' = missing')650651 def func(self, name):652 if self.environment._async:653 return 'async def %s' % name654 return 'def %s' % name655656 def function_scoping(self, node, frame, children=None,657 find_special=True):658 """In Jinja a few statements require the help of anonymous659 functions. Those are currently macros and call blocks and in
76 unmodified lines
736 # leaking into a new python frame and might be used both unassigned737 # and assigned.738 if 'loop' in frame.identifiers.declared:739 args = args + ['l_loop=l_loop']742 self.writeline('def macro(%s):' % ', '.join(args), node)740 self.writeline('%s(%s):' % (self.func('macro'), ', '.join(args)), node)741 self.indent()742 self.buffer(frame)743 self.pull_locals(frame)744 self.blockvisit(node.body, frame)
66 unmodified lines
811 # add the load name812 self.writeline('name = %r' % self.name)813814 # generate the root render function.817 self.writeline('def root(context%s):' % envenv, extra=1)815 self.writeline('%s(context%s):' % (self.func('root'), envenv), extra=1)816817 # process the root818 frame = Frame(eval_ctx)819 frame.inspect(node.body)
26 unmodified lines
846 for name, block in iteritems(self.blocks):847 block_frame = Frame(eval_ctx)848 block_frame.inspect(block.body)849 block_frame.block = name852 self.writeline('def block_%s(context%s):' % (name, envenv),850 self.writeline('%s(context%s):' % (self.func('block_' + name), envenv),851 block, 1)852 self.indent()853 undeclared = find_undeclared(block.body, ('self', 'super'))854 if 'self' in undeclared:
221 unmodified lines
1076 aliases = self.push_scope(loop_frame, ('loop',))10771078 # otherwise we set up a buffer and add a function def1079 else:1082 self.writeline('def loop(reciter, loop_render_func, depth=0):', node)1080 self.writeline('%s(reciter, loop_render_func, depth=0):' %1081 self.func('loop'), node)1082 self.indent()1083 self.buffer(loop_frame)1084 aliases = {}1085
616 unmodified lines
modified:jinja2/environment.py+2 added-1 removed
26 unmodified lines
27from jinja2.runtime import Undefined, new_context, Context28from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \29 TemplatesNotFound, TemplateRuntimeError30from jinja2.utils import import_string, LRUCache, Markup, missing, \31 concat, consume, internalcode31 concat, consume, internalcode, have_async_gen32from jinja2._compat import imap, ifilter, string_types, iteritems, \33 text_type, reraise, implements_iterator, implements_to_string, \34 encode_filename, PY2, PYPY35
284 unmodified lines
320 # load extensions321 self.extensions = load_extensions(self, extensions)322323 self.enable_async = enable_async324 self._async = self.enable_async and have_async_gen325326 _environment_sanity_check(self)327328 def add_extension(self, extension):
888 unmodified lines
modified:jinja2/utils.py+8 added
525 unmodified lines
526 return u''527 return self.sep528529530# does this python version support async for in and async generators?531try:532 exec('async def _():\n async for _ in ():\n yield _')533 have_async_gen = True534except SyntaxError:535 have_async_gen = False536537538# Imported here because that's where it was in the past539from markupsafe import Markup, escape, soft_unicode
added:tests/test_async.py+21 added
1import pytest2import asyncio34from jinja2 import Template5from jinja2.utils import have_async_gen678def run(func):9 loop = asyncio.get_event_loop()10 return loop.run_until_complete(func())111213@pytest.mark.skipif(not have_async_gen, reason='No async generators')14def test_basic_async():15 t = Template('{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}',16 enable_async=True)17 async def func():18 return await t.render_async()1920 rv = run(func)21 assert rv == '[1][2][3]'