Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

use asyncio.run in Template.render #1952

Merged
merged 1 commit into from
May 11, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
8 changes: 5 additions & 3 deletions CHANGES.rst
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ Version 3.1.5

Unreleased

- Calling sync ``render`` for an async template uses ``asyncio.run``.
:pr:`1952`


Version 3.1.4
-------------
Expand Down Expand Up @@ -138,9 +141,8 @@ Released 2021-05-18
extensions shows more relevant context. :issue:`1429`
- Fixed calling deprecated ``jinja2.Markup`` without an argument.
Use ``markupsafe.Markup`` instead. :issue:`1438`
- Calling sync ``render`` for an async template uses ``asyncio.run``
on Python >= 3.7. This fixes a deprecation that Python 3.10
introduces. :issue:`1443`
- Calling sync ``render`` for an async template uses ``asyncio.new_event_loop``
This fixes a deprecation that Python 3.10 introduces. :issue:`1443`


Version 3.0.0
Expand Down
3 changes: 0 additions & 3 deletions docs/api.rst
Original file line number Diff line number Diff line change
Expand Up @@ -515,9 +515,6 @@ environment to compile different code behind the scenes in order to
handle async and sync code in an asyncio event loop. This has the
following implications:

- Template rendering requires an event loop to be available to the
current thread. :func:`asyncio.get_running_loop` must return an
event loop.
- The compiled code uses ``await`` for functions and attributes, and
uses ``async for`` loops. In order to support using both async and
sync functions in this context, a small wrapper is placed around
Expand Down
14 changes: 1 addition & 13 deletions src/jinja2/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -1282,19 +1282,7 @@ def render(self, *args: t.Any, **kwargs: t.Any) -> str:
if self.environment.is_async:
import asyncio

close = False

try:
loop = asyncio.get_running_loop()
except RuntimeError:
loop = asyncio.new_event_loop()
close = True

try:
return loop.run_until_complete(self.render_async(*args, **kwargs))
finally:
if close:
loop.close()
return asyncio.run(self.render_async(*args, **kwargs))

ctx = self.new_context(dict(*args, **kwargs))

Expand Down