Skip to content
Myr

support pathlib in FileSystemLoader and ModuleLoader

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Alex Chan · committed by David Lord · parent 29d1ff4 · Browse files · 6 files+114 added−14 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

6 files+114 added−14 removed

  • tests:+95 added−8 removed
  • other:+19 added−6 removed

6 files+114 added−14 removed

modified:jinja2/_compat.py+5 added
22 unmodified lines
23 text_type = str24 string_types = (str,)25 integer_types = (int,)2627 import pathlib28 path_types = (str, pathlib.PurePath)2930 iterkeys = lambda d: iter(d.keys())31 itervalues = lambda d: iter(d.values())32 iteritems = lambda d: iter(d.items())33
21 unmodified lines
55 range_type = xrange56 string_types = (str, unicode)57 integer_types = (int, long)5859 path_types = string_types6061 iterkeys = lambda d: d.iterkeys()62 itervalues = lambda d: d.itervalues()63 iteritems = lambda d: d.iteritems()64
46 unmodified lines
modified:jinja2/loaders.py+11 added-6 removed
15 unmodified lines
16from os import path17from hashlib import sha118from jinja2.exceptions import TemplateNotFound19from jinja2.utils import open_if_exists, internalcode20from jinja2._compat import string_types, iteritems20from jinja2._compat import string_types, path_types, iteritems212223def split_template_path(template):24 """Split a path into segments and perform a sanity check. If it detects
133 unmodified lines
158 The *followlinks* parameter was added.159 """160161 def __init__(self, searchpath, encoding='utf-8', followlinks=False):162 if isinstance(searchpath, string_types):162 if isinstance(searchpath, path_types):163 searchpath = [searchpath]164 self.searchpath = list(searchpath)164165 # In Python 3.5, os.path.join only supports strings, not instances166 # of pathlib.Path. This line can be simplified to list(searchpath)167 # when support for Python 3.5 is dropped.168 self.searchpath = [str(path) for path in searchpath]169170 self.encoding = encoding171 self.followlinks = followlinks172173 def get_source(self, environment, template):
314 unmodified lines
488489 # create a fake module that looks for the templates in the490 # path given.491 mod = _TemplateModule(package_name)487 if isinstance(path, string_types):488 path = [path]492 if isinstance(path, path_types):493 path = [str(path)]494 else:490 path = list(path)495 path = [str(p) for p in path]496 mod.__path__ = path497498 sys.modules[package_name] = weakref.proxy(mod,499 lambda x: sys.modules.pop(package_name, None))
32 unmodified lines
added:tests/res/templates/variable_encoding.txt+1 added
1tech
modified:tests/conftest.py+1 added
30 unmodified lines
31 'debug',32 'escapeUrlizeTarget',33 'ext',34 'extended',35 'filesystemloader',36 'filter',37 'for_loop',38 'helpers',39 'if_condition',
82 unmodified lines
modified:tests/test_loader.py+93 added-8 removed
9 unmodified lines
10"""11import os12import shutil13import sys14import time15import tempfile16import weakref1718import pytest
20 unmodified lines
39 tmpl = env.get_template('test.html')40 assert tmpl.render().strip() == 'BAR'41 pytest.raises(TemplateNotFound, env.get_template, 'missing.html')4242 def test_filesystem_loader(self, filesystem_loader):43 env = Environment(loader=filesystem_loader)44 tmpl = env.get_template('test.html')45 assert tmpl.render().strip() == 'BAR'46 tmpl = env.get_template('foo/test.html')47 assert tmpl.render().strip() == 'FOO'48 pytest.raises(TemplateNotFound, env.get_template, 'missing.html')4943 def test_filesystem_loader_overlapping_names(self, filesystem_loader):44 res = os.path.dirname(filesystem_loader.searchpath[0])45 t2_dir = os.path.join(res, "templates2")46 # Make "foo" show up before "foo/test.html".
78 unmodified lines
125 pytest.raises(TemplateNotFound, split_template_path, '../foo')126127128@pytest.mark.loaders129@pytest.mark.filesystemloader130class TestFileSystemLoader(object):131 searchpath = os.path.dirname(os.path.abspath(__file__)) + '/res/templates'132133 @staticmethod134 def _test_common(env):135 tmpl = env.get_template('test.html')136 assert tmpl.render().strip() == 'BAR'137 tmpl = env.get_template('foo/test.html')138 assert tmpl.render().strip() == 'FOO'139 pytest.raises(TemplateNotFound, env.get_template, 'missing.html')140141 def test_searchpath_as_str(self):142 filesystem_loader = loaders.FileSystemLoader(self.searchpath)143144 env = Environment(loader=filesystem_loader)145 self._test_common(env)146147 @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')148 def test_searchpath_as_pathlib(self):149 import pathlib150 searchpath = pathlib.Path(self.searchpath)151152 filesystem_loader = loaders.FileSystemLoader(searchpath)153154 env = Environment(loader=filesystem_loader)155 self._test_common(env)156157 @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')158 def test_searchpath_as_list_including_pathlib(self):159 import pathlib160 searchpath = pathlib.Path(self.searchpath)161162 filesystem_loader = loaders.FileSystemLoader(['/tmp/templates', searchpath])163164 env = Environment(loader=filesystem_loader)165 self._test_common(env)166167 def test_caches_template_based_on_mtime(self):168 filesystem_loader = loaders.FileSystemLoader(self.searchpath)169170 env = Environment(loader=filesystem_loader)171 tmpl1 = env.get_template('test.html')172 tmpl2 = env.get_template('test.html')173 assert tmpl1 is tmpl2174175 os.utime(176 os.path.join(self.searchpath, "test.html"),177 (time.time(), time.time())178 )179 tmpl3 = env.get_template('test.html')180 assert tmpl1 is not tmpl3181182 @pytest.mark.parametrize('encoding, expected_text', [183 ('utf-8', u'tech'),184 ('utf-16', u'整档'),185 ])186 def test_uses_specified_encoding(self, encoding, expected_text):187 filesystem_loader = loaders.FileSystemLoader(self.searchpath, encoding=encoding)188 env = Environment(loader=filesystem_loader)189 tmpl = env.get_template('variable_encoding.txt')190 assert tmpl.render().strip() == expected_text191192193@pytest.mark.loaders194@pytest.mark.moduleloader195class TestModuleLoader(object):196 archive = None197
105 unmodified lines
303 assert tmpl1.render() == 'BAR'304 tmpl2 = self.mod_env.get_template('DICT/test.html')305 assert tmpl2.render() == 'DICT_TEMPLATE'306307 @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')308 def test_path_as_pathlib(self, prefix_loader):309 self.compile_down(prefix_loader)310311 mod_path = self.mod_env.loader.module.__path__[0]312313 import pathlib314 mod_loader = loaders.ModuleLoader(pathlib.Path(mod_path))315 self.mod_env = Environment(loader=mod_loader)316317 self._test_common()318319 @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')320 def test_supports_pathlib_in_list_of_paths(self, prefix_loader):321 self.compile_down(prefix_loader)322323 mod_path = self.mod_env.loader.module.__path__[0]324325 import pathlib326 mod_loader = loaders.ModuleLoader([327 pathlib.Path(mod_path),328 '/tmp/templates'329 ])330 self.mod_env = Environment(loader=mod_loader)331332 self._test_common()333334335@pytest.fixture()336def package_dir_loader(monkeypatch):337 monkeypatch.syspath_prepend(os.path.dirname(__file__))338 return PackageLoader("res")
43 unmodified lines
modified:CHANGES.rst+3 added
47 unmodified lines
48 ``revindex0`` when looping over a generator. :issue:`459, 751, 794`,49 :pr:`993`50- ``PackageLoader`` doesn't depend on setuptools or pkg_resources.51 :issue:`970`52- Allow passing ``pathlib.Path`` as the search path in53 :class:`~loader.FileSystemLoader` and54 :class:`~loader.ModuleLoader`. :issue:`870`555657Version 2.10.358--------------
629 unmodified lines