Merge pull request #1444 from pallets/event-loop
Before adoption: this commit came in with the history the project adopted, so no landing records it.
use asyncio.run
authored by David Lord · committed by GitHub · parents 94a6423, 7d0b7ac · Browse files · 4 files·+45 added−15 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
4 files+45 added−15 removed
- tests:+12 added−3 removed
- other:+33 added−12 removed
Provenance
- Commit
77674b9- Tree
74ea646- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
94a6423- Parent 2
7d0b7ac
4 files changed+45 added−15 removed
modified:docs/api.rst+3 added-3 removed
511 unmodified lines512 handle async and sync code in an asyncio event loop. This has the513 following implications:514 515 - Template rendering requires an event loop to be available to the516- current thread. :func:`asyncio.get_event_loop` must return an event517- loop.516+ current thread. :func:`asyncio.get_running_loop` must return an517+ event loop.518 - The compiled code uses ``await`` for functions and attributes, and519 uses ``async for`` loops. In order to support using both async and520 sync functions in this context, a small wrapper is placed around521- all calls and access, which add overhead compared to purely async521+ all calls and access, which adds overhead compared to purely async522 code.523 - Sync methods and filters become wrappers around their corresponding524 async implementations where needed. For example, ``render`` invokes525 ``async_render``, and ``|map`` supports async iterables.406 unmodified linesmodified:src/jinja2/environment.py+27 added-9 removed
1 """Classes for managing templates and their runtime and compile time2 options.3 """4 import os5+import sys6 import typing7 import typing as t8 import weakref9 from collections import ChainMap1268 unmodified lines1278 """1279 if self.environment.is_async:1280 import asyncio1281 1281- loop = asyncio.get_event_loop()1282- return loop.run_until_complete(self.render_async(*args, **kwargs))1282+ close = False1283 1284+ if sys.version_info < (3, 7):1285+ loop = asyncio.get_event_loop()1286+ else:1287+ try:1288+ loop = asyncio.get_running_loop()1289+ except RuntimeError:1290+ loop = asyncio.new_event_loop()1291+ close = True1292+1293+ try:1294+ return loop.run_until_complete(self.render_async(*args, **kwargs))1295+ finally:1296+ if close:1297+ loop.close()1298+1299 ctx = self.new_context(dict(*args, **kwargs))1300 1301 try:1302 return concat(self.root_render_func(ctx)) # type: ignore37 unmodified lines1340 """1341 if self.environment.is_async:1342 import asyncio1343 1329- loop = asyncio.get_event_loop()1330- async_gen = self.generate_async(*args, **kwargs)1344+ async def to_list() -> t.List[str]:1345+ return [x async for x in self.generate_async(*args, **kwargs)]1346 1332- try:1333- while True:1334- yield loop.run_until_complete(async_gen.__anext__())1335- except StopAsyncIteration:1336- return1347+ if sys.version_info < (3, 7):1348+ loop = asyncio.get_event_loop()1349+ out = loop.run_until_complete(to_list())1350+ else:1351+ out = asyncio.run(to_list())1352 1353+ yield from out1354+ return1355+1356 ctx = self.new_context(dict(*args, **kwargs))1357 1358 try:1359 yield from self.root_render_func(ctx) # type: ignore315 unmodified linesmodified:tests/test_async.py+12 added-3 removed
1 import asyncio2+import sys3 4 import pytest5 6 from jinja2 import ChainableUndefined6 unmodified lines13 from jinja2.exceptions import UndefinedError14 from jinja2.nativetypes import NativeEnvironment15 16 16-def run(coro):17- loop = asyncio.get_event_loop()18- return loop.run_until_complete(coro)17+if sys.version_info < (3, 7):18 19+ def run(coro):20+ loop = asyncio.get_event_loop()21+ return loop.run_until_complete(coro)22 23+24+else:25+26+ def run(coro):27+ return asyncio.run(coro)28+29+30 def test_basic_async():31 t = Template(32 "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True33 )604 unmodified linesmodified:CHANGES.rst+3 added
11 unmodified lines12 - The deprecation warning for unneeded ``autoescape`` and ``with_``13 extensions shows more relevant context. :issue:`1429`14 - Fixed calling deprecated ``jinja2.Markup`` without an argument.15 Use ``markupsafe.Markup`` instead. :issue:`1438`16+- Calling sync ``render`` for an async template uses ``asyncio.run``17+ on Python >= 3.7. This fixes a deprecation that Python 3.1018+ introduces. :issue:`1443`19 20 21 Version 3.0.022 -------------858 unmodified lines