loaders.py
This file
Path
src/jinja2/loaders.py
685 lines · 23.2 KiB · Python
Last changed by
drop end of life python versions (#2096)David Lordbefore adoption49c48a0
History of this fileTake it
The walk stopped after 200 commits: lines older than c580dd0 point at it.
update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 1–3why, one step back1"""API and implementations for loading templates from different data2sources.3"""Merge branch '3.1.x'David Lordbefore adoptionde61312
line 4why, one step back4update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 5–6why, one step back5import importlib.util6import osMerge pull request #1621 from pallets/template-safe-pathDavid Lordbefore adoptionede0f98
line 7why, one step back7import posixpathupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 8why, one step back8import sysMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 9why, one step back9import typing as tupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 10–19why, one step back10import weakref11import zipimport12from collections import abc13from hashlib import sha114from importlib import import_module15from types import ModuleType1617from .exceptions import TemplateNotFound18from .utils import internalcode19Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 20–22why, one step back20if t.TYPE_CHECKING:21 from .environment import Environment22 from .environment import Templateupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 23why, one step back23Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 24why, one step back24Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 25why, one step back25def split_template_path(template: str) -> list[str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 26–31why, one step back26 """Split a path into segments and perform a sanity check. If it detects27 '..' in the path it will raise a `TemplateNotFound` error.28 """29 pieces = []30 for piece in template.split("/"):31 if (Replacing os.path.sep with os.sep in loader (#1698)Tilman Klaegerbefore adoption997f7f5
line 32why, one step back32 os.sep in pieceupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 33–74why, one step back33 or (os.path.altsep and os.path.altsep in piece)34 or piece == os.path.pardir35 ):36 raise TemplateNotFound(template)37 elif piece and piece != ".":38 pieces.append(piece)39 return pieces404142class BaseLoader:43 """Baseclass for all loaders. Subclass this and override `get_source` to44 implement a custom loading mechanism. The environment provides a45 `get_template` method that calls the loader's `load` method to get the46 :class:`Template` object.4748 A very basic example for a loader that looks up templates on the file49 system could look like this::5051 from jinja2 import BaseLoader, TemplateNotFound52 from os.path import join, exists, getmtime5354 class MyLoader(BaseLoader):5556 def __init__(self, path):57 self.path = path5859 def get_source(self, environment, template):60 path = join(self.path, template)61 if not exists(path):62 raise TemplateNotFound(template)63 mtime = getmtime(path)64 with open(path) as f:65 source = f.read()66 return source, path, lambda: mtime == getmtime(path)67 """6869 #: if set to `False` it indicates that the loader cannot provide access70 #: to the source of templates.71 #:72 #: .. versionadded:: 2.473 has_source_access = True74Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 75–76why, one step back75 def get_source(76 self, environment: "Environment", template: strdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 77why, one step back77 ) -> tuple[str, str | None, t.Callable[[], bool] | None]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 78–96why, one step back78 """Get the template source, filename and reload helper for a template.79 It's passed the environment and template name and has to return a80 tuple in the form ``(source, filename, uptodate)`` or raise a81 `TemplateNotFound` error if it can't locate the template.8283 The source part of the returned tuple must be the source of the84 template as a string. The filename should be the name of the85 file on the filesystem if it was loaded from there, otherwise86 ``None``. The filename is used by Python for the tracebacks87 if no loader extension is used.8889 The last item in the tuple is the `uptodate` function. If auto90 reloading is enabled it's always called to check if the template91 changed. No arguments are passed so the function must store the92 old state somewhere (for example in a closure). If it returns `False`93 the template will be reloaded.94 """95 if not self.has_source_access:96 raise RuntimeError(Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 97why, one step back97 f"{type(self).__name__} cannot provide access to the source"update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 98–100why, one step back98 )99 raise TemplateNotFound(template)100Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 101why, one step back101 def list_templates(self) -> list[str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 102–107why, one step back102 """Iterates over all templates. If the loader does not support that103 it should raise a :exc:`TypeError` which is the default behavior.104 """105 raise TypeError("this loader cannot iterate over all templates")106107 @internalcodeMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 108–111why, one step back108 def load(109 self,110 environment: "Environment",111 name: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 112why, one step back112 globals: t.MutableMapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 113why, one step back113 ) -> "Template":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 114–178why, one step back114 """Loads a template. This method looks up the template in the cache115 or loads one by calling :meth:`get_source`. Subclasses should not116 override this method as loaders working on collections of other117 loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)118 will not call this method but `get_source` directly.119 """120 code = None121 if globals is None:122 globals = {}123124 # first we try to get the source for this template together125 # with the filename and the uptodate function.126 source, filename, uptodate = self.get_source(environment, name)127128 # try to load the code from the bytecode cache if there is a129 # bytecode cache configured.130 bcc = environment.bytecode_cache131 if bcc is not None:132 bucket = bcc.get_bucket(environment, name, filename, source)133 code = bucket.code134135 # if we don't have code so far (not cached, no longer up to136 # date) etc. we compile the template137 if code is None:138 code = environment.compile(source, name, filename)139140 # if the bytecode cache is available and the bucket doesn't141 # have a code so far, we give the bucket the new code and put142 # it back to the bytecode cache.143 if bcc is not None and bucket.code is None:144 bucket.code = code145 bcc.set_bucket(bucket)146147 return environment.template_class.from_code(148 environment, code, globals, uptodate149 )150151152class FileSystemLoader(BaseLoader):153 """Load templates from a directory in the file system.154155 The path can be relative or absolute. Relative paths are relative to156 the current working directory.157158 .. code-block:: python159160 loader = FileSystemLoader("templates")161162 A list of paths can be given. The directories will be searched in163 order, stopping at the first matching template.164165 .. code-block:: python166167 loader = FileSystemLoader(["/override/templates", "/default/templates"])168169 :param searchpath: A path, or list of paths, to the directory that170 contains the templates.171 :param encoding: Use this encoding to read the text from template172 files.173 :param followlinks: Follow symbolic links in the path.174175 .. versionchanged:: 2.8176 Added the ``followlinks`` parameter.177 """178Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 179–180why, one step back179 def __init__(180 self,switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81
lines 181–183why, one step back181 searchpath: t.Union[182 str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]183 ],Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 184–186why, one step back184 encoding: str = "utf-8",185 followlinks: bool = False,186 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 187–189why, one step back187 if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):188 searchpath = [searchpath]189Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 190why, one step back190 self.searchpath = [os.fspath(p) for p in searchpath]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 191–193why, one step back191 self.encoding = encoding192 self.followlinks = followlinks193Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 194–195why, one step back194 def get_source(195 self, environment: "Environment", template: strUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 196why, one step back196 ) -> tuple[str, str, t.Callable[[], bool]]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 197why, one step back197 pieces = split_template_path(template)Merge branch '3.1.x'David Lordbefore adoption94fd2d9
line 198why, one step back198update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 199why, one step back199 for searchpath in self.searchpath:Merge pull request #1621 from pallets/template-safe-pathDavid Lordbefore adoptionede0f98
lines 200–202why, one step back200 # Use posixpath even on Windows to avoid "drive:" or UNC201 # segments breaking out of the search directory.202 filename = posixpath.join(searchpath, *pieces)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 203why, one step back203Merge branch '3.1.x'David Lordbefore adoption94fd2d9
lines 204–206why, one step back204 if os.path.isfile(filename):205 break206 else:Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 207–212why, one step back207 plural = "path" if len(self.searchpath) == 1 else "paths"208 paths_str = ", ".join(repr(p) for p in self.searchpath)209 raise TemplateNotFound(210 template,211 f"{template!r} not found in search {plural}: {paths_str}",212 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 213why, one step back213Merge branch '3.1.x'David Lordbefore adoption94fd2d9
lines 214–215why, one step back214 with open(filename, encoding=self.encoding) as f:215 contents = f.read()update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 216why, one step back216Merge branch '3.1.x'David Lordbefore adoption94fd2d9
lines 217–226why, one step back217 mtime = os.path.getmtime(filename)218219 def uptodate() -> bool:220 try:221 return os.path.getmtime(filename) == mtime222 except OSError:223 return False224225 # Use normpath to convert Windows altsep to sep.226 return contents, os.path.normpath(filename), uptodateupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 227why, one step back227Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 228why, one step back228 def list_templates(self) -> list[str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 229–235why, one step back229 found = set()230 for searchpath in self.searchpath:231 walk_dir = os.walk(searchpath, followlinks=self.followlinks)232 for dirpath, _, filenames in walk_dir:233 for filename in filenames:234 template = (235 os.path.join(dirpath, filename)[len(searchpath) :]Replacing os.path.sep with os.sep in loader (#1698)Tilman Klaegerbefore adoption997f7f5
lines 236–237why, one step back236 .strip(os.sep)237 .replace(os.sep, "/")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 238–245why, one step back238 )239 if template[:2] == "./":240 template = template[2:]241 if template not in found:242 found.add(template)243 return sorted(found)244245Merge branch '3.1.x'David Lordbefore adoption7f0fc0a
lines 246–247why, one step back246if sys.version_info >= (3, 13):247Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 248why, one step back248 def _get_zipimporter_files(z: t.Any) -> dict[str, object]:Merge branch '3.1.x'David Lordbefore adoption7f0fc0a
lines 249–252why, one step back249 try:250 get_files = z._get_files251 except AttributeError as e:252 raise TypeError(Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 253why, one step back253 "This zip import does not have the required metadata to list templates."Merge branch '3.1.x'David Lordbefore adoption7f0fc0a
lines 254–255why, one step back254 ) from e255 return get_files()Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 256why, one step back256Merge branch '3.1.x'David Lordbefore adoption7f0fc0a
lines 257–258why, one step back257else:258Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 259why, one step back259 def _get_zipimporter_files(z: t.Any) -> dict[str, object]:Merge branch '3.1.x'David Lordbefore adoption7f0fc0a
lines 260–263why, one step back260 try:261 files = z._files262 except AttributeError as e:263 raise TypeError(Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 264why, one step back264 "This zip import does not have the required metadata to list templates."Merge branch '3.1.x'David Lordbefore adoption7f0fc0a
lines 265–268why, one step back265 ) from e266 return files # type: ignore[no-any-return]267268update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 269–301why, one step back269class PackageLoader(BaseLoader):270 """Load templates from a directory in a Python package.271272 :param package_name: Import name of the package that contains the273 template directory.274 :param package_path: Directory within the imported package that275 contains the templates.276 :param encoding: Encoding of template files.277278 The following example looks up templates in the ``pages`` directory279 within the ``project.ui`` package.280281 .. code-block:: python282283 loader = PackageLoader("project.ui", "pages")284285 Only packages installed as directories (standard pip behavior) or286 zip/egg files (less common) are supported. The Python API for287 introspecting data in packages is too limited to support other288 installation methods the way this loader requires.289290 There is limited support for :pep:`420` namespace packages. The291 template directory is assumed to only be in one namespace292 contributor. Zip files contributing to a namespace are not293 supported.294295 .. versionchanged:: 3.0296 No longer uses ``setuptools`` as a dependency.297298 .. versionchanged:: 3.0299 Limited PEP 420 namespace package support.300 """301Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 302–307why, one step back302 def __init__(303 self,304 package_name: str,305 package_path: "str" = "templates",306 encoding: str = "utf-8",307 ) -> None:Replacing os.path.sep with os.sep in loader (#1698)Tilman Klaegerbefore adoption997f7f5
line 308why, one step back308 package_path = os.path.normpath(package_path).rstrip(os.sep)Merge branch '3.0.x'David Lordbefore adoptionf20a9c9
lines 309–310why, one step back309310 # normpath preserves ".", which isn't valid in zip paths.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 311–312why, one step back311 if package_path == os.path.curdir:312 package_path = ""Replacing os.path.sep with os.sep in loader (#1698)Tilman Klaegerbefore adoption997f7f5
line 313why, one step back313 elif package_path[:2] == os.path.curdir + os.sep:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 314–323why, one step back314 package_path = package_path[2:]315316 self.package_path = package_path317 self.package_name = package_name318 self.encoding = encoding319320 # Make sure the package exists. This also makes namespace321 # packages work, otherwise get_loader returns None.322 import_module(package_name)323 spec = importlib.util.find_spec(package_name)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 324–327why, one step back324 assert spec is not None, "An import spec was not found for the package."325 loader = spec.loader326 assert loader is not None, "A loader was not found for the package."327 self._loader = loaderupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 328–331why, one step back328 self._archive = None329330 if isinstance(loader, zipimport.zipimporter):331 self._archive = loader.archiveMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 332why, one step back332 pkgdir = next(iter(spec.submodule_search_locations)) # type: ignoreReplacing os.path.sep with os.sep in loader (#1698)Tilman Klaegerbefore adoption997f7f5
line 333why, one step back333 template_root = os.path.join(pkgdir, package_path).rstrip(os.sep)Merge branch '3.0.x'David Lordbefore adoptiona42b291
line 334why, one step back334 else:Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 335why, one step back335 roots: list[str] = []Merge branch '3.0.x'David Lordbefore adoptiona42b291
lines 336–344why, one step back336337 # One element for regular packages, multiple for namespace338 # packages, or None for single module file.339 if spec.submodule_search_locations:340 roots.extend(spec.submodule_search_locations)341 # A single module file, use the parent directory instead.342 elif spec.origin is not None:343 roots.append(os.path.dirname(spec.origin))344Merge branch 'stable'David Lordbefore adoption6aeab5d
lines 345–350why, one step back345 if not roots:346 raise ValueError(347 f"The {package_name!r} package was not installed in a"348 " way that PackageLoader understands."349 )350Merge branch '3.0.x'David Lordbefore adoptiona42b291
line 351why, one step back351 for root in roots:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 352–354why, one step back352 root = os.path.join(root, package_path)353354 if os.path.isdir(root):Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 355why, one step back355 template_root = rootupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 356why, one step back356 breakMerge branch 'stable'David Lordbefore adoption6aeab5d
lines 357–361why, one step back357 else:358 raise ValueError(359 f"PackageLoader could not find a {package_path!r} directory"360 f" in the {package_name!r} package."361 )update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 362why, one step back362Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 363–366why, one step back363 self._template_root = template_root364365 def get_source(366 self, environment: "Environment", template: strdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 367why, one step back367 ) -> tuple[str, str, t.Callable[[], bool] | None]:Merge pull request #1621 from pallets/template-safe-pathDavid Lordbefore adoptionede0f98
line 368why, one step back368 # Use posixpath even on Windows to avoid "drive:" or UNCMerge branch '3.1.x'David Lordbefore adoption6f79daa
lines 369–373why, one step back369 # segments breaking out of the search directory. Use normpath to370 # convert Windows altsep to sep.371 p = os.path.normpath(372 posixpath.join(self._template_root, *split_template_path(template))373 )drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 374why, one step back374 up_to_date: t.Callable[[], bool] | Noneupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 375–385why, one step back375376 if self._archive is None:377 # Package is a directory.378 if not os.path.isfile(p):379 raise TemplateNotFound(template)380381 with open(p, "rb") as f:382 source = f.read()383384 mtime = os.path.getmtime(p)385Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 386why, one step back386 def up_to_date() -> bool:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 387–391why, one step back387 return os.path.isfile(p) and os.path.getmtime(p) == mtime388389 else:390 # Package is a zip file.391 try:Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 392why, one step back392 source = self._loader.get_data(p) # type: ignoreMerge branch '3.0.x'David Lordbefore adoptione20a52e
lines 393–394why, one step back393 except OSError as e:394 raise TemplateNotFound(template) from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 395–402why, one step back395396 # Could use the zip's mtime for all template mtimes, but397 # would need to safely reload the module if it's out of398 # date, so just report it as always current.399 up_to_date = None400401 return source.decode(self.encoding), p, up_to_date402Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
lines 403–404why, one step back403 def list_templates(self) -> list[str]:404 results: list[str] = []update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 405–410why, one step back405406 if self._archive is None:407 # Package is a directory.408 offset = len(self._template_root)409410 for dirpath, _, filenames in os.walk(self._template_root):Replacing os.path.sep with os.sep in loader (#1698)Tilman Klaegerbefore adoption997f7f5
line 411why, one step back411 dirpath = dirpath[offset:].lstrip(os.sep)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 412why, one step back412 results.extend(Replacing os.path.sep with os.sep in loader (#1698)Tilman Klaegerbefore adoption997f7f5
line 413why, one step back413 os.path.join(dirpath, name).replace(os.sep, "/")update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 414–416why, one step back414 for name in filenames415 )416 else:Merge branch '3.1.x'David Lordbefore adoption7f0fc0a
line 417why, one step back417 files = _get_zipimporter_files(self._loader)update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 418–419why, one step back418419 # Package is a zip file.Replacing os.path.sep with os.sep in loader (#1698)Tilman Klaegerbefore adoption997f7f5
line 420why, one step back420 prefix = self._template_root[len(self._archive) :].lstrip(os.sep) + os.sepupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 421–422why, one step back421 offset = len(prefix)422Merge branch '3.1.x'David Lordbefore adoption7f0fc0a
line 423why, one step back423 for name in files:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 424why, one step back424 # Find names under the templates directory that aren't directories.Replacing os.path.sep with os.sep in loader (#1698)Tilman Klaegerbefore adoption997f7f5
lines 425–426why, one step back425 if name.startswith(prefix) and name[-1] != os.sep:426 results.append(name[offset:].replace(os.sep, "/"))update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 427–437why, one step back427428 results.sort()429 return results430431432class DictLoader(BaseLoader):433 """Loads a template from a Python dict mapping template names to434 template source. This loader is useful for unittesting:435436 >>> loader = DictLoader({'index.html': 'source here'})437Merge branch 'stable'David Lordbefore adoption6aeab5d
line 438why, one step back438 Because auto reloading is rarely useful this is disabled by default.update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 439–440why, one step back439 """440Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 441why, one step back441 def __init__(self, mapping: t.Mapping[str, str]) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 442–443why, one step back442 self.mapping = mapping443Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 444–445why, one step back444 def get_source(445 self, environment: "Environment", template: strUpdated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 446why, one step back446 ) -> tuple[str, None, t.Callable[[], bool]]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 447–451why, one step back447 if template in self.mapping:448 source = self.mapping[template]449 return source, None, lambda: source == self.mapping.get(template)450 raise TemplateNotFound(template)451Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 452why, one step back452 def list_templates(self) -> list[str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 453–473why, one step back453 return sorted(self.mapping)454455456class FunctionLoader(BaseLoader):457 """A loader that is passed a function which does the loading. The458 function receives the name of the template and has to return either459 a string with the template source, a tuple in the form ``(source,460 filename, uptodatefunc)`` or `None` if the template does not exist.461462 >>> def load_template(name):463 ... if name == 'index.html':464 ... return '...'465 ...466 >>> loader = FunctionLoader(load_template)467468 The `uptodatefunc` is a function that is called if autoreload is enabled469 and has to return `True` if the template is still up to date. For more470 details have a look at :meth:`BaseLoader.get_source` which has the same471 return value.472 """473Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 474–477why, one step back474 def __init__(475 self,476 load_func: t.Callable[477 [str],drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 478why, one step back478 str | tuple[str, str | None, t.Callable[[], bool] | None] | None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 479–480why, one step back479 ],480 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 481–482why, one step back481 self.load_func = load_func482Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 483–484why, one step back483 def get_source(484 self, environment: "Environment", template: strdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 485why, one step back485 ) -> tuple[str, str | None, t.Callable[[], bool] | None]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 486why, one step back486 rv = self.load_func(template)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 487why, one step back487update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 488–489why, one step back488 if rv is None:489 raise TemplateNotFound(template)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 490–491why, one step back490491 if isinstance(rv, str):update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 492why, one step back492 return rv, None, NoneMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 493why, one step back493update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 494–511why, one step back494 return rv495496497class PrefixLoader(BaseLoader):498 """A loader that is passed a dict of loaders where each loader is bound499 to a prefix. The prefix is delimited from the template by a slash per500 default, which can be changed by setting the `delimiter` argument to501 something else::502503 loader = PrefixLoader({504 'app1': PackageLoader('mypackage.app1'),505 'app2': PackageLoader('mypackage.app2')506 })507508 By loading ``'app1/index.html'`` the file from the app1 package is loaded,509 by loading ``'app2/index.html'`` the file from the second.510 """511Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 512–514why, one step back512 def __init__(513 self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/"514 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 515–517why, one step back515 self.mapping = mapping516 self.delimiter = delimiter517Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 518why, one step back518 def get_loader(self, template: str) -> tuple[BaseLoader, str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 519–521why, one step back519 try:520 prefix, name = template.split(self.delimiter, 1)521 loader = self.mapping[prefix]Merge branch '3.0.x'David Lordbefore adoptione20a52e
lines 522–523why, one step back522 except (ValueError, KeyError) as e:523 raise TemplateNotFound(template) from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 524–525why, one step back524 return loader, name525Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 526–527why, one step back526 def get_source(527 self, environment: "Environment", template: strdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 528why, one step back528 ) -> tuple[str, str | None, t.Callable[[], bool] | None]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 529–531why, one step back529 loader, name = self.get_loader(template)530 try:531 return loader.get_source(environment, name)Merge branch '3.0.x'David Lordbefore adoptione20a52e
line 532why, one step back532 except TemplateNotFound as e:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 533–534why, one step back533 # re-raise the exception with the correct filename here.534 # (the one that includes the prefix)Merge branch '3.0.x'David Lordbefore adoptione20a52e
line 535why, one step back535 raise TemplateNotFound(template) from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 536–537why, one step back536537 @internalcodeMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 538–541why, one step back538 def load(539 self,540 environment: "Environment",541 name: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 542why, one step back542 globals: t.MutableMapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 543why, one step back543 ) -> "Template":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 544–546why, one step back544 loader, local_name = self.get_loader(name)545 try:546 return loader.load(environment, local_name, globals)Merge branch '3.0.x'David Lordbefore adoptione20a52e
line 547why, one step back547 except TemplateNotFound as e:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 548–549why, one step back548 # re-raise the exception with the correct filename here.549 # (the one that includes the prefix)Merge branch '3.0.x'David Lordbefore adoptione20a52e
line 550why, one step back550 raise TemplateNotFound(name) from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
line 551why, one step back551Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 552why, one step back552 def list_templates(self) -> list[str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 553–573why, one step back553 result = []554 for prefix, loader in self.mapping.items():555 for template in loader.list_templates():556 result.append(prefix + self.delimiter + template)557 return result558559560class ChoiceLoader(BaseLoader):561 """This loader works like the `PrefixLoader` just that no prefix is562 specified. If a template could not be found by one loader the next one563 is tried.564565 >>> loader = ChoiceLoader([566 ... FileSystemLoader('/path/to/user/templates'),567 ... FileSystemLoader('/path/to/system/templates')568 ... ])569570 This is useful if you want to allow users to override builtin templates571 from a different location.572 """573Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 574why, one step back574 def __init__(self, loaders: t.Sequence[BaseLoader]) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 575–576why, one step back575 self.loaders = loaders576Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 577–578why, one step back577 def get_source(578 self, environment: "Environment", template: strdrop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 579why, one step back579 ) -> tuple[str, str | None, t.Callable[[], bool] | None]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 580–587why, one step back580 for loader in self.loaders:581 try:582 return loader.get_source(environment, template)583 except TemplateNotFound:584 pass585 raise TemplateNotFound(template)586587 @internalcodeMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 588–591why, one step back588 def load(589 self,590 environment: "Environment",591 name: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 592why, one step back592 globals: t.MutableMapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 593why, one step back593 ) -> "Template":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 594–600why, one step back594 for loader in self.loaders:595 try:596 return loader.load(environment, name, globals)597 except TemplateNotFound:598 pass599 raise TemplateNotFound(name)600Updated dependency management to uv (#2093)David Lordbefore adoption05f5d74
line 601why, one step back601 def list_templates(self) -> list[str]:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 602–616why, one step back602 found = set()603 for loader in self.loaders:604 found.update(loader.list_templates())605 return sorted(found)606607608class _TemplateModule(ModuleType):609 """Like a normal module but with support for weak references"""610611612class ModuleLoader(BaseLoader):613 """This loader loads templates from precompiled templates.614615 Example usage:616Merge branch 'stable'David Lordbefore adoption6aeab5d
line 617why, one step back617 >>> loader = ModuleLoader('/path/to/compiled/templates')update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 618–623why, one step back618619 Templates can be precompiled with :meth:`Environment.compile_templates`.620 """621622 has_source_access = False623Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 624why, one step back624 def __init__(switch to pyproject.toml (#1793)David Lordbefore adoption05a5f81
lines 625–628why, one step back625 self,626 path: t.Union[627 str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]628 ],Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 629why, one step back629 ) -> None:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 630–638why, one step back630 package_name = f"_jinja2_module_templates_{id(self):x}"631632 # create a fake module that looks for the templates in the633 # path given.634 mod = _TemplateModule(package_name)635636 if not isinstance(path, abc.Iterable) or isinstance(path, str):637 path = [path]638Merge branch '3.0.x'David Lordbefore adoption896a621
line 639why, one step back639 mod.__path__ = [os.fspath(p) for p in path]update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 640–651why, one step back640641 sys.modules[package_name] = weakref.proxy(642 mod, lambda x: sys.modules.pop(package_name, None)643 )644645 # the only strong reference, the sys.modules entry is weak646 # so that the garbage collector can remove it once the647 # loader that created it goes out of business.648 self.module = mod649 self.package_name = package_name650651 @staticmethodMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 652why, one step back652 def get_template_key(name: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 653–655why, one step back653 return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()654655 @staticmethodMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 656why, one step back656 def get_module_filename(name: str) -> str:update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 657–659why, one step back657 return ModuleLoader.get_template_key(name) + ".py"658659 @internalcodeMerge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 660–663why, one step back660 def load(661 self,662 environment: "Environment",663 name: str,drop end of life python versions (#2096)David Lordbefore adoption49c48a0
line 664why, one step back664 globals: t.MutableMapping[str, t.Any] | None = None,Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 665why, one step back665 ) -> "Template":update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 666–668why, one step back666 key = self.get_template_key(name)667 module = f"{self.package_name}.{key}"668 mod = getattr(self.module, module, None)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
line 669why, one step back669update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 670–672why, one step back670 if mod is None:671 try:672 mod = __import__(module, None, None, ["root"])Merge branch '3.0.x'David Lordbefore adoptione20a52e
lines 673–674why, one step back673 except ImportError as e:674 raise TemplateNotFound(name) from eupdate building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 675–678why, one step back675676 # remove the entry from sys.modules, we only want the attribute677 # on the module object we have stored on the loader.678 sys.modules.pop(module, None)Merge pull request #1412 from pallets/typingDavid Lordbefore adoption1a3342b
lines 679–681why, one step back679680 if globals is None:681 globals = {}update building docs instructions in contributing guide (#1235)sixtyfathomsbefore adoptionc580dd0
lines 682–685why, one step back682683 return environment.template_class.from_module_dict(684 environment, mod.__dict__, globals685 )