Skip to content
Myr

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

4 files+152 added−54 removed

modified:jinja2/loaders.py+92 added-47 removed
7 unmodified lines
8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import os12import pkgutil13import sys14import weakref15from types import ModuleType16from os import path
186 unmodified lines
203 return sorted(found)204205206class 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.208210 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.214212 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.217214 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:: python219220 loader = PackageLoader("project.ui", "pages")221222 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.226227 .. versionchanged:: 2.11.0228 No longer uses ``setuptools`` as a dependency.229 """230220 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:]236237 package_path = os.path.normpath(package_path)238239 self.package_name = package_name240 self.package_path = package_path241 self.encoding = encoding242243 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)249250 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))252237 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)257247 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()260261 mtime = os.path.getmtime(p)262263 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)271272 # 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 = None276277 return source.decode(self.encoding), p, up_to_date278279 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)281282 if self._archive is None:283 # Package is a directory.284 offset = len(self._template_root)285286 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 )298299 # 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)305306 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, "/"))310311 results.sort()312 return results313314
212 unmodified lines
added:tests/res/package.zipbinary

A binary file, added.

modified:tests/test_loader.py+58 added-7 removed
7 unmodified lines
8 :copyright: (c) 2017 by the Jinja Team.9 :license: BSD, see LICENSE for more details.10"""11import os12import shutil13import sys14import tempfile14import shutil15import pytest15import weakref1618from jinja2 import Environment, loaders19from jinja2._compat import PYPY, PY220from jinja2.loaders import split_template_path17import pytest1819from jinja2 import Environment20from jinja2 import loaders21from jinja2 import PackageLoader22from jinja2._compat import PY223from jinja2._compat import PYPY24from jinja2.exceptions import TemplateNotFound25from jinja2.loaders import split_template_path262728@pytest.mark.loaders29class TestLoaders(object):2630 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 lines
56 e.get_template("foo")57 # This would raise NotADirectoryError if "t2/foo" wasn't skipped.58 e.get_template("foo/test.html")595760 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 lines
244 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'248249250@pytest.fixture()251def package_dir_loader(monkeypatch):252 monkeypatch.syspath_prepend(os.path.dirname(__file__))253 return PackageLoader("res")254255256@pytest.mark.parametrize(257 ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]258)259def 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()264265266def 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 templates270271272@pytest.fixture()273def 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")278279280@pytest.mark.parametrize(281 ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]282)283def 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 None288289290@pytest.mark.xfail(291 PYPY,292 reason="PyPy's zipimporter doesn't have a _files attribute.",293 raises=TypeError,294)295def 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 lines
46 :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`525354Version 2.10.355--------------
629 unmodified lines