From 3642ae7fef491222fb81fa3c0ae01bffca25fa41 Mon Sep 17 00:00:00 2001 From: remidebette Date: Tue, 2 Mar 2021 23:12:30 +0100 Subject: [PATCH] NativeEnvironment supports async mode --- CHANGES.rst | 1 + src/jinja2/nativetypes.py | 14 ++++++++++++++ tests/test_async.py | 24 ++++++++++++++++++++++++ 3 files changed, 39 insertions(+) diff --git a/CHANGES.rst b/CHANGES.rst index 45ff1444..dad0d0ef 100644 --- a/CHANGES.rst +++ b/CHANGES.rst @@ -55,6 +55,7 @@ Unreleased - ``Undefined.__contains__`` (``in``) raises an ``UndefinedError`` instead of a ``TypeError``. :issue:`1198` - ``Undefined`` is iterable in an async environment. :issue:`1294` +- ``NativeEnvironment`` supports async mode. :issue:`1362` Version 2.11.3 diff --git a/src/jinja2/nativetypes.py b/src/jinja2/nativetypes.py index 3ac70cf7..8867a316 100644 --- a/src/jinja2/nativetypes.py +++ b/src/jinja2/nativetypes.py @@ -93,5 +93,19 @@ class NativeTemplate(Template): except Exception: return self.environment.handle_exception() + async def render_async(self, *args, **kwargs): + if not self.environment.is_async: + raise RuntimeError( + "The environment was not created with async mode enabled." + ) + + vars = dict(*args, **kwargs) + ctx = self.new_context(vars) + + try: + return native_concat([n async for n in self.root_render_func(ctx)]) + except Exception: + return self.environment.handle_exception() + NativeEnvironment.template_class = NativeTemplate diff --git a/tests/test_async.py b/tests/test_async.py index 44b4bf13..cd243fd8 100644 --- a/tests/test_async.py +++ b/tests/test_async.py @@ -10,6 +10,7 @@ from jinja2.asyncsupport import auto_aiter from jinja2.exceptions import TemplateNotFound from jinja2.exceptions import TemplatesNotFound from jinja2.exceptions import UndefinedError +from jinja2.nativetypes import NativeEnvironment def run(coro): @@ -602,3 +603,26 @@ def test_chainable_undefined_aiter(): assert rv == "" run(_test()) + + +@pytest.fixture +def async_native_env(): + return NativeEnvironment(enable_async=True) + + +def test_native_async(async_native_env): + async def _test(): + t = async_native_env.from_string("{{ x }}") + rv = await t.render_async(x=23) + assert rv == 23 + + run(_test()) + + +def test_native_list_async(async_native_env): + async def _test(): + t = async_native_env.from_string("{{ x }}") + rv = await t.render_async(x=list(range(3))) + assert rv == [0, 1, 2] + + run(_test()) -- 2.47.2