Merge pull request #1182 from pallets/revert-package-loader
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Revert dropping pkg_resources from PackageLoader for 2.11
authored by David Lord · committed by GitHub · parents 41ed50c, 35a2ba5 · Browse files · 4 files·+53 added−165 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+53 added−165 removed
- tests:+0 added−50 removed
- other:+53 added−115 removed
Provenance
- Commit
07b5c01- Tree
ecfe4d0- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
41ed50c- Parent 2
35a2ba5
4 files changed+53 added−165 removed
modified:src/jinja2/loaders.py+47 added-115 removed
1 unmodified line2 """API and implementations for loading templates from different data3 sources.4 """5 import os6-import pkgutil6 import sys7 import weakref8 from hashlib import sha110-from importlib import import_module9 from os import path10 from types import ModuleType11 12 from ._compat import abc201 unmodified lines214 return sorted(found)215 216 217 class PackageLoader(BaseLoader):220- """Load templates from a directory in a Python package.218+ """Load templates from python eggs or packages. It is constructed with219+ the name of the python package and the path to the templates in that220+ package::221 222- :param package_name: Import name of the package that contains the223- template directory.224- :param package_path: Directory within the imported package that225- contains the templates.226- :param encoding: Encoding of template files.222+ loader = PackageLoader('mypackage', 'views')223 228- The following example looks up templates in the ``pages`` directory229- within the ``project.ui`` package.224+ If the package path is not given, ``'templates'`` is assumed.225 231- .. code-block:: python232-233- loader = PackageLoader("project.ui", "pages")234-235- Only packages installed as directories (standard pip behavior) or236- zip/egg files (less common) are supported. The Python API for237- introspecting data in packages is too limited to support other238- installation methods the way this loader requires.239-240- There is limited support for :pep:`420` namespace packages. The241- template directory is assumed to only be in one namespace242- contributor. Zip files contributing to a namespace are not243- supported.244-245- .. versionchanged:: 2.11.0246- No longer uses ``setuptools`` as a dependency.247-248- .. versionchanged:: 2.11.0249- Limited PEP 420 namespace package support.226+ Per default the template encoding is ``'utf-8'`` which can be changed227+ by setting the `encoding` parameter to something else. Due to the nature228+ of eggs it's only possible to reload templates if the package was loaded229+ from the file system and not a zip file.230 """231 232 def __init__(self, package_name, package_path="templates", encoding="utf-8"):253- if package_path == os.path.curdir:254- package_path = ""255- elif package_path[:2] == os.path.curdir + os.path.sep:256- package_path = package_path[2:]233+ from pkg_resources import DefaultProvider234+ from pkg_resources import get_provider235+ from pkg_resources import ResourceManager236 258- package_path = os.path.normpath(package_path).rstrip(os.path.sep)259- self.package_path = package_path260- self.package_name = package_name237+ provider = get_provider(package_name)238 self.encoding = encoding239+ self.manager = ResourceManager()240+ self.filesystem_bound = isinstance(provider, DefaultProvider)241+ self.provider = provider242+ self.package_path = package_path243 263- # Make sure the package exists. This also makes namespace264- # packages work, otherwise get_loader returns None.265- import_module(package_name)266- self._loader = loader = pkgutil.get_loader(package_name)267-268- # Zip loader's archive attribute points at the zip.269- self._archive = getattr(loader, "archive", None)270- self._template_root = None271-272- if hasattr(loader, "get_filename"):273- # A standard directory package, or a zip package.274- self._template_root = os.path.join(275- os.path.dirname(loader.get_filename(package_name)), package_path276- )277- elif hasattr(loader, "_path"):278- # A namespace package, limited support. Find the first279- # contributor with the template directory.280- for root in loader._path:281- root = os.path.join(root, package_path)282-283- if os.path.isdir(root):284- self._template_root = root285- break286-287- if self._template_root is None:288- raise ValueError(289- "The %r package was not installed in a way that"290- " PackageLoader understands." % package_name291- )292-244 def get_source(self, environment, template):294- p = os.path.join(self._template_root, *split_template_path(template))245+ pieces = split_template_path(template)246+ p = "/".join((self.package_path,) + tuple(pieces))247 296- if self._archive is None:297- # Package is a directory.298- if not os.path.isfile(p):299- raise TemplateNotFound(template)248+ if not self.provider.has_resource(p):249+ raise TemplateNotFound(template)250 301- with open(p, "rb") as f:302- source = f.read()251+ filename = uptodate = None252 304- mtime = os.path.getmtime(p)253+ if self.filesystem_bound:254+ filename = self.provider.get_resource_filename(self.manager, p)255+ mtime = path.getmtime(filename)256 306- def up_to_date():307- return os.path.isfile(p) and os.path.getmtime(p) == mtime257+ def uptodate():258+ try:259+ return path.getmtime(filename) == mtime260+ except OSError:261+ return False262 309- else:310- # Package is a zip file.311- try:312- source = self._loader.get_data(p)313- except OSError:314- raise TemplateNotFound(template)263+ source = self.provider.get_resource_string(self.manager, p)264+ return source.decode(self.encoding), filename, uptodate265 316- # Could use the zip's mtime for all template mtimes, but317- # would need to safely reload the module if it's out of318- # date, so just report it as always current.319- up_to_date = None266+ def list_templates(self):267+ path = self.package_path268 321- return source.decode(self.encoding), p, up_to_date269+ if path[:2] == "./":270+ path = path[2:]271+ elif path == ".":272+ path = ""273 323- def list_templates(self):274+ offset = len(path)275 results = []276 326- if self._archive is None:327- # Package is a directory.328- offset = len(self._template_root)277+ def _walk(path):278+ for filename in self.provider.resource_listdir(path):279+ fullname = path + "/" + filename280 330- for dirpath, _, filenames in os.walk(self._template_root):331- dirpath = dirpath[offset:].lstrip(os.path.sep)332- results.extend(333- os.path.join(dirpath, name).replace(os.path.sep, "/")334- for name in filenames335- )336- else:337- if not hasattr(self._loader, "_files"):338- raise TypeError(339- "This zip import does not have the required"340- " metadata to list templates."341- )281+ if self.provider.resource_isdir(fullname):282+ _walk(fullname)283+ else:284+ results.append(fullname[offset:].lstrip("/"))285 343- # Package is a zip file.344- prefix = (345- self._template_root[len(self._archive) :].lstrip(os.path.sep)346- + os.path.sep347- )348- offset = len(prefix)349-350- for name in self._loader._files.keys():351- # Find names under the templates directory that aren't directories.352- if name.startswith(prefix) and name[-1] != os.path.sep:353- results.append(name[offset:].replace(os.path.sep, "/"))354-286+ _walk(path)287 results.sort()288 return results289 290 214 unmodified linesdeleted:tests/res/package.zipbinary
A binary file, deleted.
modified:tests/test_loader.py-50 removed
8 unmodified lines9 import pytest10 11 from jinja2 import Environment12 from jinja2 import loaders13-from jinja2 import PackageLoader13 from jinja2._compat import PY214 from jinja2._compat import PYPY15 from jinja2.exceptions import TemplateNotFound16 from jinja2.loaders import split_template_path302 unmodified lines319 mod_loader = loaders.ModuleLoader([pathlib.Path(mod_path), "/tmp/templates"])320 self.mod_env = Environment(loader=mod_loader)321 322 self._test_common()324-325-326-@pytest.fixture()327-def package_dir_loader(monkeypatch):328- monkeypatch.syspath_prepend(os.path.dirname(__file__))329- return PackageLoader("res")330-331-332-@pytest.mark.parametrize(333- ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]334-)335-def test_package_dir_source(package_dir_loader, template, expect):336- source, name, up_to_date = package_dir_loader.get_source(None, template)337- assert source.rstrip() == expect338- assert name.endswith(os.path.join(*split_template_path(template)))339- assert up_to_date()340-341-342-def test_package_dir_list(package_dir_loader):343- templates = package_dir_loader.list_templates()344- assert "foo/test.html" in templates345- assert "test.html" in templates346-347-348-@pytest.fixture()349-def package_zip_loader(monkeypatch):350- monkeypatch.syspath_prepend(351- os.path.join(os.path.dirname(__file__), "res", "package.zip")352- )353- return PackageLoader("t_pack")354-355-356-@pytest.mark.parametrize(357- ("template", "expect"), [("foo/test.html", "FOO"), ("test.html", "BAR")]358-)359-def test_package_zip_source(package_zip_loader, template, expect):360- source, name, up_to_date = package_zip_loader.get_source(None, template)361- assert source.rstrip() == expect362- assert name.endswith(os.path.join(*split_template_path(template)))363- assert up_to_date is None364-365-366-@pytest.mark.xfail(367- PYPY,368- reason="PyPy's zipimporter doesn't have a _files attribute.",369- raises=TypeError,370-)371-def test_package_zip_list(package_zip_loader):372- assert package_zip_loader.list_templates() == ["foo/test.html", "test.html"]modified:CHANGES.rst+6 added
13 unmodified lines14 :issue:`1162`15 - Showing an undefined error for an object that raises16 ``AttributeError`` on access doesn't cause a recursion error.17 :issue:`1177`18+- Revert changes to :class:`~loaders.PackageLoader` from 2.10 which19+ removed the dependency on setuptools and pkg_resources, and added20+ limited support for namespace packages. The changes caused issues21+ when using Pytest. Due to the difficulty in supporting Python 2 and22+ :pep:`451` simultaneously, the changes are reverted until 3.0.23+ :pr:`1182`24 25 26 Version 2.11.127 --------------737 unmodified lines