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
Provenance
- Commit
b11056d- Tree
8806a69- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e908a58
6 files changed+95 added−12 removed
modified:jinja2/__init__.py+11 added
66 unmodified lines67 'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape',68 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined',69 'evalcontextfilter', 'evalcontextfunction', 'make_logging_undefined',70 ]71+72+73+def _patch_async():74+ from jinja2.utils import have_async_gen75+ if have_async_gen:76+ from jinja2.asyncsupport import patch_all77+ patch_all()78+79+80+_patch_async()81+del _patch_asyncadded:jinja2/asyncsupport.py+43 added
1+import sys2+import asyncio3+4+from jinja2.utils import concat5+6+7+async 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.')11+12+ 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)18+19+ 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)25+26+27+def 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 render34+35+36+def patch_template():37+ from jinja2 import Template38+ Template.render_async = render_async39+ Template.render = wrap_render_func(Template.render)40+41+42+def patch_all():43+ patch_template()modified:jinja2/compiler.py+10 added-11 removed
45 unmodified lines46 code_features.append('generator_stop')47 except SyntaxError:48 pass49 50-# does this python version support async for in and async generators?51-try:52- exec('async def _():\n async for _ in ():\n yield _')53- have_async_gen = True54-except SyntaxError:55- have_async_gen = False50 57-51 # does if 0: dummy(x) get us x into the scope?52 def unoptimize_before_dead_code():53 x = 4254 def f():592 unmodified lines647 # scopes can trigger a SyntaxError:648 # a = 42; b = lambda: a; del a649 self.writeline(' = '.join(to_delete) + ' = missing')650 651+ def func(self, name):652+ if self.environment._async:653+ return 'async def %s' % name654+ return 'def %s' % name655+656 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 in76 unmodified lines736 # 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 lines811 # add the load name812 self.writeline('name = %r' % self.name)813 814 # 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)816 817 # process the root818 frame = Frame(eval_ctx)819 frame.inspect(node.body)26 unmodified lines846 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 lines1076 aliases = self.push_scope(loop_frame, ('loop',))1077 1078 # 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 linesmodified:jinja2/environment.py+2 added-1 removed
26 unmodified lines27 from jinja2.runtime import Undefined, new_context, Context28 from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \29 TemplatesNotFound, TemplateRuntimeError30 from jinja2.utils import import_string, LRUCache, Markup, missing, \31- concat, consume, internalcode31+ concat, consume, internalcode, have_async_gen32 from jinja2._compat import imap, ifilter, string_types, iteritems, \33 text_type, reraise, implements_iterator, implements_to_string, \34 encode_filename, PY2, PYPY35 284 unmodified lines320 # load extensions321 self.extensions = load_extensions(self, extensions)322 323 self.enable_async = enable_async324+ self._async = self.enable_async and have_async_gen325 326 _environment_sanity_check(self)327 328 def add_extension(self, extension):888 unmodified linesmodified:jinja2/utils.py+8 added
525 unmodified lines526 return u''527 return self.sep528 529 530+# does this python version support async for in and async generators?531+try:532+ exec('async def _():\n async for _ in ():\n yield _')533+ have_async_gen = True534+except SyntaxError:535+ have_async_gen = False536+537+538 # Imported here because that's where it was in the past539 from markupsafe import Markup, escape, soft_unicodeadded:tests/test_async.py+21 added
1+import pytest2+import asyncio3+4+from jinja2 import Template5+from jinja2.utils import have_async_gen6+7+8+def run(func):9+ loop = asyncio.get_event_loop()10+ return loop.run_until_complete(func())11+12+13+@pytest.mark.skipif(not have_async_gen, reason='No async generators')14+def 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()19+20+ rv = run(func)21+ assert rv == '[1][2][3]'