Skip to content

Commit 079e831

Browse files
authored
use asyncio.run in Template.render (#1952)
2 parents 2fcabb5 + 5bc613e commit 079e831

File tree

3 files changed

+6
-19
lines changed

3 files changed

+6
-19
lines changed

CHANGES.rst

Lines changed: 5 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,9 @@ Version 3.1.5
55

66
Unreleased
77

8+
- Calling sync ``render`` for an async template uses ``asyncio.run``.
9+
:pr:`1952`
10+
811

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

145147

146148
Version 3.0.0

docs/api.rst

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -515,9 +515,6 @@ environment to compile different code behind the scenes in order to
515515
handle async and sync code in an asyncio event loop. This has the
516516
following implications:
517517

518-
- Template rendering requires an event loop to be available to the
519-
current thread. :func:`asyncio.get_running_loop` must return an
520-
event loop.
521518
- The compiled code uses ``await`` for functions and attributes, and
522519
uses ``async for`` loops. In order to support using both async and
523520
sync functions in this context, a small wrapper is placed around

src/jinja2/environment.py

Lines changed: 1 addition & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -1282,19 +1282,7 @@ def render(self, *args: t.Any, **kwargs: t.Any) -> str:
12821282
if self.environment.is_async:
12831283
import asyncio
12841284

1285-
close = False
1286-
1287-
try:
1288-
loop = asyncio.get_running_loop()
1289-
except RuntimeError:
1290-
loop = asyncio.new_event_loop()
1291-
close = True
1292-
1293-
try:
1294-
return loop.run_until_complete(self.render_async(*args, **kwargs))
1295-
finally:
1296-
if close:
1297-
loop.close()
1285+
return asyncio.run(self.render_async(*args, **kwargs))
12981286

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

0 commit comments

Comments
 (0)