Merge branch '3.0.x'
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by David Lord · committed by David Lord · parents ab78403, 738644d · Browse files · 8 files·+79 added−62 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
8 files+79 added−62 removed
- tests:+39 added−49 removed
- other:+40 added−13 removed
Provenance
- Commit
cdbda09- Tree
608ac84- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent 1
ab78403- Parent 2
738644d
8 files changed+79 added−62 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/conftest.py+3 added-3 removed
1-import os1+from pathlib import Path2 3 import pytest4 5 from jinja2 import loaders20 unmodified lines26 27 @pytest.fixture28 def filesystem_loader():29 """returns FileSystemLoader initialized to res/templates directory"""30- here = os.path.dirname(os.path.abspath(__file__))31- return loaders.FileSystemLoader(here + "/res/templates")30+ here = Path(__file__).parent.resolve()31+ return loaders.FileSystemLoader(here / "res" / "templates")32 33 34 @pytest.fixture35 def function_loader():14 unmodified linesmodified:tests/test_api.py+4 added-5 removed
1-import os1 import shutil2 import tempfile3+from pathlib import Path4 5 import pytest6 7 from jinja2 import ChainableUndefined233 unmodified lines241 stream.disable_buffering()242 assert not stream.buffered243 244 def test_dump_stream(self, env):245- tmp = tempfile.mkdtemp()245+ tmp = Path(tempfile.mkdtemp())246 try:247 tmpl = env.from_string("\u2713")248 stream = tmpl.stream()249- stream.dump(os.path.join(tmp, "dump.txt"), "utf-8")250- with open(os.path.join(tmp, "dump.txt"), "rb") as f:251- assert f.read() == b"\xe2\x9c\x93"249+ stream.dump(str(tmp / "dump.txt"), "utf-8")250+ assert (tmp / "dump.txt").read_bytes() == b"\xe2\x9c\x93"251 finally:252 shutil.rmtree(tmp)253 254 179 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:tests/test_loader.py+14 added-27 removed
6 unmodified lines7 import sys8 import tempfile9 import time10 import weakref11+from pathlib import Path12 13 import pytest14 15 from jinja2 import Environment16 unmodified lines32 assert tmpl.render().strip() == "BAR"33 pytest.raises(TemplateNotFound, env.get_template, "missing.html")34 35 def test_filesystem_loader_overlapping_names(self, filesystem_loader):35- res = os.path.dirname(filesystem_loader.searchpath[0])36- t2_dir = os.path.join(res, "templates2")36+ t2_dir = Path(filesystem_loader.searchpath[0]) / ".." / "templates2"37 # Make "foo" show up before "foo/test.html".38 filesystem_loader.searchpath.insert(0, t2_dir)39 e = Environment(loader=filesystem_loader)40 e.get_template("foo")76 unmodified lines117 pytest.raises(TemplateNotFound, split_template_path, "../foo")118 119 120 class TestFileSystemLoader:121- searchpath = os.path.join(122- os.path.dirname(os.path.abspath(__file__)), "res", "templates"123- )121+ searchpath = (Path(__file__) / ".." / "res" / "templates").resolve()122 123 @staticmethod124 def _test_common(env):125 tmpl = env.get_template("test.html")2 unmodified lines128 assert tmpl.render().strip() == "FOO"129 pytest.raises(TemplateNotFound, env.get_template, "missing.html")130 131 def test_searchpath_as_str(self):134- filesystem_loader = loaders.FileSystemLoader(self.searchpath)132+ filesystem_loader = loaders.FileSystemLoader(str(self.searchpath))133 134 env = Environment(loader=filesystem_loader)135 self._test_common(env)136 137 def test_searchpath_as_pathlib(self):140- import pathlib141-142- searchpath = pathlib.Path(self.searchpath)143- filesystem_loader = loaders.FileSystemLoader(searchpath)138+ filesystem_loader = loaders.FileSystemLoader(self.searchpath)139 env = Environment(loader=filesystem_loader)140 self._test_common(env)141 142 def test_searchpath_as_list_including_pathlib(self):148- import pathlib149-150- searchpath = pathlib.Path(self.searchpath)151- filesystem_loader = loaders.FileSystemLoader(["/tmp/templates", searchpath])143+ filesystem_loader = loaders.FileSystemLoader(144+ ["/tmp/templates", self.searchpath]145+ )146 env = Environment(loader=filesystem_loader)147 self._test_common(env)148 149 def test_caches_template_based_on_mtime(self):3 unmodified lines153 tmpl1 = env.get_template("test.html")154 tmpl2 = env.get_template("test.html")155 assert tmpl1 is tmpl2156 163- os.utime(os.path.join(self.searchpath, "test.html"), (time.time(), time.time()))157+ os.utime(self.searchpath / "test.html", (time.time(), time.time()))158 tmpl3 = env.get_template("test.html")159 assert tmpl1 is not tmpl3160 161 @pytest.mark.parametrize(113 unmodified lines275 def test_path_as_pathlib(self, prefix_loader):276 self.compile_down(prefix_loader)277 278 mod_path = self.mod_env.loader.module.__path__[0]285-286- import pathlib287-288- mod_loader = loaders.ModuleLoader(pathlib.Path(mod_path))279+ mod_loader = loaders.ModuleLoader(Path(mod_path))280 self.mod_env = Environment(loader=mod_loader)281 282 self._test_common()283 284 def test_supports_pathlib_in_list_of_paths(self, prefix_loader):285 self.compile_down(prefix_loader)286 287 mod_path = self.mod_env.loader.module.__path__[0]297-298- import pathlib299-300- mod_loader = loaders.ModuleLoader([pathlib.Path(mod_path), "/tmp/templates"])288+ mod_loader = loaders.ModuleLoader([Path(mod_path), "/tmp/templates"])289 self.mod_env = Environment(loader=mod_loader)290 291 self._test_common()292 293 294 @pytest.fixture()295 def package_dir_loader(monkeypatch):308- monkeypatch.syspath_prepend(os.path.dirname(__file__))296+ monkeypatch.syspath_prepend(Path(__file__).parent)297 return PackageLoader("res")298 299 300 @pytest.mark.parametrize(13 unmodified lines314 315 316 @pytest.fixture()317 def package_zip_loader(monkeypatch):330- monkeypatch.syspath_prepend(331- os.path.join(os.path.dirname(__file__), "res", "package.zip")332- )318+ package_zip = (Path(__file__) / ".." / "res" / "package.zip").resolve()319+ monkeypatch.syspath_prepend(package_zip)320 return PackageLoader("t_pack")321 322 323 @pytest.mark.parametrize(47 unmodified linesmodified:tests/test_utils.py+6 added-11 removed
21 unmodified lines22 d["b"] = 223 d["c"] = 324 d["a"]25 d["d"] = 426- assert len(d) == 327- assert "a" in d and "c" in d and "d" in d and "b" not in d26+ assert d.keys() == ["d", "a", "c"]27 29- def test_itervalues(self):28+ def test_values(self):29 cache = LRUCache(3)30 cache["b"] = 131 cache["a"] = 233- values = [v for v in cache.values()]34- assert len(values) == 235- assert 1 in values36- assert 2 in values32+ assert cache.values() == [2, 1]33 38- def test_itervalues_empty(self):34+ def test_values_empty(self):35 cache = LRUCache(2)40- values = [v for v in cache.values()]41- assert len(values) == 036+ assert cache.values() == []37 38 def test_pickleable(self):39 cache = LRUCache(2)40 cache["foo"] = 4214 unmodified lines55 copy = copy_func(cache)56 assert copy._queue == cache._queue57 copy["c"] = 358 assert copy._queue != cache._queue64- assert "a" not in copy and "b" in copy and "c" in copy59+ assert copy.keys() == ["c", "b"]60 61 def test_clear(self):62 d = LRUCache(3)63 d["a"] = 1122 unmodified linesmodified:CHANGES.rst+10 added-1 removed
4 unmodified lines5 6 Unreleased7 8 9-Version 3.0.19+Version 3.0.210 -------------11 12 Unreleased13 14+15+Version 3.0.116+-------------17+18+Released 2021-05-1819+20 - Update MarkupSafe dependency to >= 2.0. :pr:`1418`21 - Mark top-level names as exported so type checking understands22 imports in user projects. :issue:`1426`23 - Fix some types that weren't available in Python 3.6.0. :issue:`1433`24 - The deprecation warning for unneeded ``autoescape`` and ``with_``25 extensions shows more relevant context. :issue:`1429`26 - Fixed calling deprecated ``jinja2.Markup`` without an argument.27 Use ``markupsafe.Markup`` instead. :issue:`1438`28+- Calling sync ``render`` for an async template uses ``asyncio.run``29+ on Python >= 3.7. This fixes a deprecation that Python 3.1030+ introduces. :issue:`1443`31 32 33 Version 3.0.034 -------------858 unmodified lines