Use importlib machinery to fix PEP 451 import hooks
Before adoption: this commit came in with the history the project adopted, so no landing records it.
authored by Anthony Sottile · committed by David Lord · parent 0a37031 · Browse files · 2 files·+54 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
2 files+54 added−14 removed
- tests:+41 added−0 removed
- other:+13 added−14 removed
Provenance
- Commit
a524e77- Tree
8db1359- Author
Anthony Sottile <asottile@umich.edu>- Committer
David Lord <davidism@gmail.com>- Parent
0a37031
2 files changed+54 added−14 removed
modified:src/jinja2/loaders.py+13 added-14 removed
1 """API and implementations for loading templates from different data2 sources.3 """4+import importlib.util5 import os5-import pkgutil6 import sys7 import weakref8+import zipimport9 from collections import abc10 from hashlib import sha111 from importlib import import_module12 from types import ModuleType240 unmodified lines253 254 # Make sure the package exists. This also makes namespace255 # packages work, otherwise get_loader returns None.256 import_module(package_name)256- self._loader = loader = pkgutil.get_loader(package_name)257+ spec = importlib.util.find_spec(package_name)258+ self._loader = spec.loader259 258- # Zip loader's archive attribute points at the zip.259- self._archive = getattr(loader, "archive", None)260+ self._archive = None261 self._template_root = None261-262- if hasattr(loader, "get_filename"):263- # A standard directory package, or a zip package.264- self._template_root = os.path.join(265- os.path.dirname(loader.get_filename(package_name)), package_path266- )267- elif hasattr(loader, "_path"):268- # A namespace package, limited support. Find the first269- # contributor with the template directory.270- for root in loader._path:262+ if isinstance(spec.loader, zipimport.zipimporter):263+ self._archive = spec.loader.archive264+ pkgdir = next(iter(spec.submodule_search_locations))265+ self._template_root = os.path.join(pkgdir, package_path)266+ elif spec.submodule_search_locations:267+ # this will be one element for "packages" and multiple for268+ # namespace packages269+ for root in spec.submodule_search_locations:270 root = os.path.join(root, package_path)271 272 if os.path.isdir(root):273 self._template_root = root288 unmodified linesmodified:tests/test_loader.py+41 added
1+import importlib.abc2+import importlib.machinery3+import importlib.util4 import os5 import platform6 import shutil7 import sys341 unmodified lines349 raises=TypeError,350 )351 def test_package_zip_list(package_zip_loader):352 assert package_zip_loader.list_templates() == ["foo/test.html", "test.html"]353+354+355+def test_pep_451_import_hook(tmp_path):356+ package_name = "_my_pep451_pkg"357+ pkg = tmp_path.joinpath(package_name)358+ pkg.mkdir()359+ pkg.joinpath("__init__.py").touch()360+ templates = pkg.joinpath("templates")361+ templates.mkdir()362+ templates.joinpath("foo.html").write_text("hello world")363+364+ class ImportHook(importlib.abc.MetaPathFinder, importlib.abc.Loader):365+ def find_spec(self, name, path=None, target=None):366+ if name != package_name:367+ return None368+ path = [str(tmp_path)]369+ spec = importlib.machinery.PathFinder.find_spec(name, path=path)370+ return importlib.util.spec_from_file_location(371+ name,372+ spec.origin,373+ loader=self,374+ submodule_search_locations=spec.submodule_search_locations,375+ )376+377+ def create_module(self, spec):378+ return None # default behaviour is fine379+380+ def exec_module(self, module):381+ return None # we need this to satisfy the interface, it's wrong382+383+ # ensure we restore `sys.meta_path` after putting in our loader384+ before = sys.meta_path[:]385+ try:386+ sys.meta_path.insert(0, ImportHook())387+ package_loader = PackageLoader(package_name)388+ assert package_loader.list_templates() == ["foo.html"]389+ finally:390+ sys.meta_path[:] = before