Merge pull request #1082 from pallets/pkgutil-loader
Before adoption: this commit came in with the history the project adopted, so no landing records it.
PackageLoader doesn't depend on setuptools
authored by David Lord · committed by GitHub · parents 81b3224, 4b6077a · Browse files · 4 files·+152 added−54 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+152 added−54 removed
- tests:+58 added−7 removed
- other:+94 added−47 removed
Provenance
- Commit
1949a5c- Tree
0c3e612- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
81b3224- Parent 2
4b6077a
4 files changed+152 added−54 removed
modified:jinja2/loaders.py+92 added-47 removed
7 unmodified lines8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11 import os12+import pkgutil13 import sys14 import weakref15 from types import ModuleType16 from os import path186 unmodified lines203 return sorted(found)204 205 206 class PackageLoader(BaseLoader):206- """Load templates from python eggs or packages. It is constructed with207- the name of the python package and the path to the templates in that208- package::207+ """Load templates from a directory in a Python package.208 210- loader = PackageLoader('mypackage', 'views')209+ :param package_name: Import name of the package that contains the210+ template directory.211+ :param package_path: Directory within the imported package that212+ contains the templates.213+ :param encoding: Encoding of template files.214 212- If the package path is not given, ``'templates'`` is assumed.215+ The following example looks up templates in the ``pages`` directory216+ within the ``project.ui`` package.217 214- Per default the template encoding is ``'utf-8'`` which can be changed215- by setting the `encoding` parameter to something else. Due to the nature216- of eggs it's only possible to reload templates if the package was loaded217- from the file system and not a zip file.218+ .. code-block:: python219+220+ loader = PackageLoader("project.ui", "pages")221+222+ Only packages installed as directories (standard pip behavior) or223+ zip/egg files (less common) are supported. The Python API for224+ introspecting data in packages is too limited to support other225+ installation methods the way this loader requires.226+227+ .. versionchanged:: 2.11.0228+ No longer uses ``setuptools`` as a dependency.229 """230 220- def __init__(self, package_name, package_path='templates',221- encoding='utf-8'):222- from pkg_resources import DefaultProvider, ResourceManager, \223- get_provider224- provider = get_provider(package_name)225- self.encoding = encoding226- self.manager = ResourceManager()227- self.filesystem_bound = isinstance(provider, DefaultProvider)228- self.provider = provider231+ def __init__(self, package_name, package_path="templates", encoding="utf-8"):232+ if package_path == os.path.curdir:233+ package_path = ""234+ elif package_path[:2] == os.path.curdir + os.path.sep:235+ package_path = package_path[2:]236+237+ package_path = os.path.normpath(package_path)238+239+ self.package_name = package_name240 self.package_path = package_path241+ self.encoding = encoding242 243+ self._loader = pkgutil.get_loader(package_name)244+ # Zip loader's archive attribute points at the zip.245+ self._archive = getattr(self._loader, "archive", None)246+ self._template_root = os.path.join(247+ os.path.dirname(self._loader.get_filename(package_name)), package_path248+ ).rstrip(os.path.sep)249+250 def get_source(self, environment, template):232- pieces = split_template_path(template)233- p = '/'.join((self.package_path,) + tuple(pieces))234- if not self.provider.has_resource(p):235- raise TemplateNotFound(template)251+ p = os.path.join(self._template_root, *split_template_path(template))252 237- filename = uptodate = None238- if self.filesystem_bound:239- filename = self.provider.get_resource_filename(self.manager, p)240- mtime = path.getmtime(filename)241- def uptodate():242- try:243- return path.getmtime(filename) == mtime244- except OSError:245- return False253+ if self._archive is None:254+ # Package is a directory.255+ if not os.path.isfile(p):256+ raise TemplateNotFound(template)257 247- source = self.provider.get_resource_string(self.manager, p)248- return source.decode(self.encoding), filename, uptodate258+ with open(p, "rb") as f:259+ source = f.read()260 261+ mtime = os.path.getmtime(p)262+263+ def up_to_date():264+ return os.path.isfile(p) and os.path.getmtime(p) == mtime265+ else:266+ # Package is a zip file.267+ try:268+ source = self._loader.get_data(p)269+ except OSError:270+ raise TemplateNotFound(template)271+272+ # Could use the zip's mtime for all template mtimes, but273+ # would need to safely reload the module if it's out of274+ # date, so just report it as always current.275+ up_to_date = None276+277+ return source.decode(self.encoding), p, up_to_date278+279 def list_templates(self):251- path = self.package_path252- if path[:2] == './':253- path = path[2:]254- elif path == '.':255- path = ''256- offset = len(path)280 results = []258- def _walk(path):259- for filename in self.provider.resource_listdir(path):260- fullname = path + '/' + filename261- if self.provider.resource_isdir(fullname):262- _walk(fullname)263- else:264- results.append(fullname[offset:].lstrip('/'))265- _walk(path)281+282+ if self._archive is None:283+ # Package is a directory.284+ offset = len(self._template_root)285+286+ for dirpath, _, filenames in os.walk(self._template_root):287+ dirpath = dirpath[offset:].lstrip(os.path.sep)288+ results.extend(289+ os.path.join(dirpath, name).replace(os.path.sep, "/")290+ for name in filenames291+ )292+ else:293+ if not hasattr(self._loader, "_files"):294+ raise TypeError(295+ "This zip import does not have the required"296+ " metadata to list templates."297+ )298+299+ # Package is a zip file.300+ prefix = (301+ self._template_root[len(self._archive):].lstrip(os.path.sep)302+ + os.path.sep303+ )304+ offset = len(prefix)305+306+ for name in self._loader._files.keys():307+ # Find names under the templates directory that aren't directories.308+ if name.startswith(prefix) and name[-1] != os.path.sep:309+ results.append(name[offset:].replace(os.path.sep, "/"))310+311 results.sort()312 return results313 314 212 unmodified linesadded:tests/res/package.zipbinary
A binary file, added.
modified:tests/test_loader.py+58 added-7 removed
7 unmodified lines8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10 """11 import os12+import shutil13 import sys14 import tempfile14-import shutil15-import pytest15 import weakref16 18-from jinja2 import Environment, loaders19-from jinja2._compat import PYPY, PY220-from jinja2.loaders import split_template_path17+import pytest18+19+from jinja2 import Environment20+from jinja2 import loaders21+from jinja2 import PackageLoader22+from jinja2._compat import PY223+from jinja2._compat import PYPY24 from jinja2.exceptions import TemplateNotFound25+from jinja2.loaders import split_template_path26 27 28 @pytest.mark.loaders29 class TestLoaders(object):26-30 def test_dict_loader(self, dict_loader):31 env = Environment(loader=dict_loader)32 tmpl = env.get_template('justdict.html')33 assert tmpl.render().strip() == 'FOO'22 unmodified lines56 e.get_template("foo")57 # This would raise NotADirectoryError if "t2/foo" wasn't skipped.58 e.get_template("foo/test.html")59 57-60 def test_choice_loader(self, choice_loader):61 env = Environment(loader=choice_loader)62 tmpl = env.get_template('justdict.html')63 assert tmpl.render().strip() == 'FOO'180 unmodified lines244 tmpl1 = self.mod_env.get_template('MOD/a/test.html')245 assert tmpl1.render() == 'BAR'246 tmpl2 = self.mod_env.get_template('DICT/test.html')247 assert tmpl2.render() == 'DICT_TEMPLATE'248+249+250+@pytest.fixture()251+def package_dir_loader(monkeypatch):252+ monkeypatch.syspath_prepend(os.path.dirname(__file__))253+ return PackageLoader("res")254+255+256+@pytest.mark.parametrize(257+ ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]258+)259+def test_package_dir_source(package_dir_loader, template, expect):260+ source, name, up_to_date = package_dir_loader.get_source(None, template)261+ assert source.rstrip() == expect262+ assert name.endswith(os.path.join(*split_template_path(template)))263+ assert up_to_date()264+265+266+def test_package_dir_list(package_dir_loader):267+ templates = package_dir_loader.list_templates()268+ assert "foo/test.html" in templates269+ assert "test.html" in templates270+271+272+@pytest.fixture()273+def package_zip_loader(monkeypatch):274+ monkeypatch.syspath_prepend(275+ os.path.join(os.path.dirname(__file__), "res", "package.zip")276+ )277+ return PackageLoader("t_pack")278+279+280+@pytest.mark.parametrize(281+ ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]282+)283+def test_package_zip_source(package_zip_loader, template, expect):284+ source, name, up_to_date = package_zip_loader.get_source(None, template)285+ assert source.rstrip() == expect286+ assert name.endswith(os.path.join(*split_template_path(template)))287+ assert up_to_date is None288+289+290+@pytest.mark.xfail(291+ PYPY,292+ reason="PyPy's zipimporter doesn't have a _files attribute.",293+ raises=TypeError,294+)295+def test_package_zip_list(package_zip_loader):296+ assert package_zip_loader.list_templates() == ["foo/test.html", "test.html"]modified:CHANGES.rst+2 added
45 unmodified lines46 :class:`StrictUndefined`). :issue:`710`, :pr:`1079`47 - Fix behavior of ``loop`` control variables such as ``length`` and48 ``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 53 54 Version 2.10.355 --------------629 unmodified lines