loaders.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667
  1. """API and implementations for loading templates from different data
  2. sources.
  3. """
  4. import importlib.util
  5. import os
  6. import posixpath
  7. import sys
  8. import typing as t
  9. import weakref
  10. import zipimport
  11. from collections import abc
  12. from hashlib import sha1
  13. from importlib import import_module
  14. from types import ModuleType
  15. from .exceptions import TemplateNotFound
  16. from .utils import internalcode
  17. if t.TYPE_CHECKING:
  18. from .environment import Environment
  19. from .environment import Template
  20. def split_template_path(template: str) -> t.List[str]:
  21. """Split a path into segments and perform a sanity check. If it detects
  22. '..' in the path it will raise a `TemplateNotFound` error.
  23. """
  24. pieces = []
  25. for piece in template.split("/"):
  26. if (
  27. os.path.sep in piece
  28. or (os.path.altsep and os.path.altsep in piece)
  29. or piece == os.path.pardir
  30. ):
  31. raise TemplateNotFound(template)
  32. elif piece and piece != ".":
  33. pieces.append(piece)
  34. return pieces
  35. class BaseLoader:
  36. """Baseclass for all loaders. Subclass this and override `get_source` to
  37. implement a custom loading mechanism. The environment provides a
  38. `get_template` method that calls the loader's `load` method to get the
  39. :class:`Template` object.
  40. A very basic example for a loader that looks up templates on the file
  41. system could look like this::
  42. from jinja2 import BaseLoader, TemplateNotFound
  43. from os.path import join, exists, getmtime
  44. class MyLoader(BaseLoader):
  45. def __init__(self, path):
  46. self.path = path
  47. def get_source(self, environment, template):
  48. path = join(self.path, template)
  49. if not exists(path):
  50. raise TemplateNotFound(template)
  51. mtime = getmtime(path)
  52. with open(path) as f:
  53. source = f.read()
  54. return source, path, lambda: mtime == getmtime(path)
  55. """
  56. #: if set to `False` it indicates that the loader cannot provide access
  57. #: to the source of templates.
  58. #:
  59. #: .. versionadded:: 2.4
  60. has_source_access = True
  61. def get_source(
  62. self, environment: "Environment", template: str
  63. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  64. """Get the template source, filename and reload helper for a template.
  65. It's passed the environment and template name and has to return a
  66. tuple in the form ``(source, filename, uptodate)`` or raise a
  67. `TemplateNotFound` error if it can't locate the template.
  68. The source part of the returned tuple must be the source of the
  69. template as a string. The filename should be the name of the
  70. file on the filesystem if it was loaded from there, otherwise
  71. ``None``. The filename is used by Python for the tracebacks
  72. if no loader extension is used.
  73. The last item in the tuple is the `uptodate` function. If auto
  74. reloading is enabled it's always called to check if the template
  75. changed. No arguments are passed so the function must store the
  76. old state somewhere (for example in a closure). If it returns `False`
  77. the template will be reloaded.
  78. """
  79. if not self.has_source_access:
  80. raise RuntimeError(
  81. f"{type(self).__name__} cannot provide access to the source"
  82. )
  83. raise TemplateNotFound(template)
  84. def list_templates(self) -> t.List[str]:
  85. """Iterates over all templates. If the loader does not support that
  86. it should raise a :exc:`TypeError` which is the default behavior.
  87. """
  88. raise TypeError("this loader cannot iterate over all templates")
  89. @internalcode
  90. def load(
  91. self,
  92. environment: "Environment",
  93. name: str,
  94. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  95. ) -> "Template":
  96. """Loads a template. This method looks up the template in the cache
  97. or loads one by calling :meth:`get_source`. Subclasses should not
  98. override this method as loaders working on collections of other
  99. loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
  100. will not call this method but `get_source` directly.
  101. """
  102. code = None
  103. if globals is None:
  104. globals = {}
  105. # first we try to get the source for this template together
  106. # with the filename and the uptodate function.
  107. source, filename, uptodate = self.get_source(environment, name)
  108. # try to load the code from the bytecode cache if there is a
  109. # bytecode cache configured.
  110. bcc = environment.bytecode_cache
  111. if bcc is not None:
  112. bucket = bcc.get_bucket(environment, name, filename, source)
  113. code = bucket.code
  114. # if we don't have code so far (not cached, no longer up to
  115. # date) etc. we compile the template
  116. if code is None:
  117. code = environment.compile(source, name, filename)
  118. # if the bytecode cache is available and the bucket doesn't
  119. # have a code so far, we give the bucket the new code and put
  120. # it back to the bytecode cache.
  121. if bcc is not None and bucket.code is None:
  122. bucket.code = code
  123. bcc.set_bucket(bucket)
  124. return environment.template_class.from_code(
  125. environment, code, globals, uptodate
  126. )
  127. class FileSystemLoader(BaseLoader):
  128. """Load templates from a directory in the file system.
  129. The path can be relative or absolute. Relative paths are relative to
  130. the current working directory.
  131. .. code-block:: python
  132. loader = FileSystemLoader("templates")
  133. A list of paths can be given. The directories will be searched in
  134. order, stopping at the first matching template.
  135. .. code-block:: python
  136. loader = FileSystemLoader(["/override/templates", "/default/templates"])
  137. :param searchpath: A path, or list of paths, to the directory that
  138. contains the templates.
  139. :param encoding: Use this encoding to read the text from template
  140. files.
  141. :param followlinks: Follow symbolic links in the path.
  142. .. versionchanged:: 2.8
  143. Added the ``followlinks`` parameter.
  144. """
  145. def __init__(
  146. self,
  147. searchpath: t.Union[
  148. str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]
  149. ],
  150. encoding: str = "utf-8",
  151. followlinks: bool = False,
  152. ) -> None:
  153. if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):
  154. searchpath = [searchpath]
  155. self.searchpath = [os.fspath(p) for p in searchpath]
  156. self.encoding = encoding
  157. self.followlinks = followlinks
  158. def get_source(
  159. self, environment: "Environment", template: str
  160. ) -> t.Tuple[str, str, t.Callable[[], bool]]:
  161. pieces = split_template_path(template)
  162. for searchpath in self.searchpath:
  163. # Use posixpath even on Windows to avoid "drive:" or UNC
  164. # segments breaking out of the search directory.
  165. filename = posixpath.join(searchpath, *pieces)
  166. if os.path.isfile(filename):
  167. break
  168. else:
  169. raise TemplateNotFound(template)
  170. with open(filename, encoding=self.encoding) as f:
  171. contents = f.read()
  172. mtime = os.path.getmtime(filename)
  173. def uptodate() -> bool:
  174. try:
  175. return os.path.getmtime(filename) == mtime
  176. except OSError:
  177. return False
  178. # Use normpath to convert Windows altsep to sep.
  179. return contents, os.path.normpath(filename), uptodate
  180. def list_templates(self) -> t.List[str]:
  181. found = set()
  182. for searchpath in self.searchpath:
  183. walk_dir = os.walk(searchpath, followlinks=self.followlinks)
  184. for dirpath, _, filenames in walk_dir:
  185. for filename in filenames:
  186. template = (
  187. os.path.join(dirpath, filename)[len(searchpath) :]
  188. .strip(os.path.sep)
  189. .replace(os.path.sep, "/")
  190. )
  191. if template[:2] == "./":
  192. template = template[2:]
  193. if template not in found:
  194. found.add(template)
  195. return sorted(found)
  196. class PackageLoader(BaseLoader):
  197. """Load templates from a directory in a Python package.
  198. :param package_name: Import name of the package that contains the
  199. template directory.
  200. :param package_path: Directory within the imported package that
  201. contains the templates.
  202. :param encoding: Encoding of template files.
  203. The following example looks up templates in the ``pages`` directory
  204. within the ``project.ui`` package.
  205. .. code-block:: python
  206. loader = PackageLoader("project.ui", "pages")
  207. Only packages installed as directories (standard pip behavior) or
  208. zip/egg files (less common) are supported. The Python API for
  209. introspecting data in packages is too limited to support other
  210. installation methods the way this loader requires.
  211. There is limited support for :pep:`420` namespace packages. The
  212. template directory is assumed to only be in one namespace
  213. contributor. Zip files contributing to a namespace are not
  214. supported.
  215. .. versionchanged:: 3.0
  216. No longer uses ``setuptools`` as a dependency.
  217. .. versionchanged:: 3.0
  218. Limited PEP 420 namespace package support.
  219. """
  220. def __init__(
  221. self,
  222. package_name: str,
  223. package_path: "str" = "templates",
  224. encoding: str = "utf-8",
  225. ) -> None:
  226. package_path = os.path.normpath(package_path).rstrip(os.path.sep)
  227. # normpath preserves ".", which isn't valid in zip paths.
  228. if package_path == os.path.curdir:
  229. package_path = ""
  230. elif package_path[:2] == os.path.curdir + os.path.sep:
  231. package_path = package_path[2:]
  232. self.package_path = package_path
  233. self.package_name = package_name
  234. self.encoding = encoding
  235. # Make sure the package exists. This also makes namespace
  236. # packages work, otherwise get_loader returns None.
  237. import_module(package_name)
  238. spec = importlib.util.find_spec(package_name)
  239. assert spec is not None, "An import spec was not found for the package."
  240. loader = spec.loader
  241. assert loader is not None, "A loader was not found for the package."
  242. self._loader = loader
  243. self._archive = None
  244. template_root = None
  245. if isinstance(loader, zipimport.zipimporter):
  246. self._archive = loader.archive
  247. pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
  248. template_root = os.path.join(pkgdir, package_path).rstrip(os.path.sep)
  249. else:
  250. roots: t.List[str] = []
  251. # One element for regular packages, multiple for namespace
  252. # packages, or None for single module file.
  253. if spec.submodule_search_locations:
  254. roots.extend(spec.submodule_search_locations)
  255. # A single module file, use the parent directory instead.
  256. elif spec.origin is not None:
  257. roots.append(os.path.dirname(spec.origin))
  258. for root in roots:
  259. root = os.path.join(root, package_path)
  260. if os.path.isdir(root):
  261. template_root = root
  262. break
  263. if template_root is None:
  264. raise ValueError(
  265. f"The {package_name!r} package was not installed in a"
  266. " way that PackageLoader understands."
  267. )
  268. self._template_root = template_root
  269. def get_source(
  270. self, environment: "Environment", template: str
  271. ) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:
  272. # Use posixpath even on Windows to avoid "drive:" or UNC
  273. # segments breaking out of the search directory. Use normpath to
  274. # convert Windows altsep to sep.
  275. p = os.path.normpath(
  276. posixpath.join(self._template_root, *split_template_path(template))
  277. )
  278. up_to_date: t.Optional[t.Callable[[], bool]]
  279. if self._archive is None:
  280. # Package is a directory.
  281. if not os.path.isfile(p):
  282. raise TemplateNotFound(template)
  283. with open(p, "rb") as f:
  284. source = f.read()
  285. mtime = os.path.getmtime(p)
  286. def up_to_date() -> bool:
  287. return os.path.isfile(p) and os.path.getmtime(p) == mtime
  288. else:
  289. # Package is a zip file.
  290. try:
  291. source = self._loader.get_data(p) # type: ignore
  292. except OSError as e:
  293. raise TemplateNotFound(template) from e
  294. # Could use the zip's mtime for all template mtimes, but
  295. # would need to safely reload the module if it's out of
  296. # date, so just report it as always current.
  297. up_to_date = None
  298. return source.decode(self.encoding), p, up_to_date
  299. def list_templates(self) -> t.List[str]:
  300. results: t.List[str] = []
  301. if self._archive is None:
  302. # Package is a directory.
  303. offset = len(self._template_root)
  304. for dirpath, _, filenames in os.walk(self._template_root):
  305. dirpath = dirpath[offset:].lstrip(os.path.sep)
  306. results.extend(
  307. os.path.join(dirpath, name).replace(os.path.sep, "/")
  308. for name in filenames
  309. )
  310. else:
  311. if not hasattr(self._loader, "_files"):
  312. raise TypeError(
  313. "This zip import does not have the required"
  314. " metadata to list templates."
  315. )
  316. # Package is a zip file.
  317. prefix = (
  318. self._template_root[len(self._archive) :].lstrip(os.path.sep)
  319. + os.path.sep
  320. )
  321. offset = len(prefix)
  322. for name in self._loader._files.keys():
  323. # Find names under the templates directory that aren't directories.
  324. if name.startswith(prefix) and name[-1] != os.path.sep:
  325. results.append(name[offset:].replace(os.path.sep, "/"))
  326. results.sort()
  327. return results
  328. class DictLoader(BaseLoader):
  329. """Loads a template from a Python dict mapping template names to
  330. template source. This loader is useful for unittesting:
  331. >>> loader = DictLoader({'index.html': 'source here'})
  332. Because auto reloading is rarely useful this is disabled per default.
  333. """
  334. def __init__(self, mapping: t.Mapping[str, str]) -> None:
  335. self.mapping = mapping
  336. def get_source(
  337. self, environment: "Environment", template: str
  338. ) -> t.Tuple[str, None, t.Callable[[], bool]]:
  339. if template in self.mapping:
  340. source = self.mapping[template]
  341. return source, None, lambda: source == self.mapping.get(template)
  342. raise TemplateNotFound(template)
  343. def list_templates(self) -> t.List[str]:
  344. return sorted(self.mapping)
  345. class FunctionLoader(BaseLoader):
  346. """A loader that is passed a function which does the loading. The
  347. function receives the name of the template and has to return either
  348. a string with the template source, a tuple in the form ``(source,
  349. filename, uptodatefunc)`` or `None` if the template does not exist.
  350. >>> def load_template(name):
  351. ... if name == 'index.html':
  352. ... return '...'
  353. ...
  354. >>> loader = FunctionLoader(load_template)
  355. The `uptodatefunc` is a function that is called if autoreload is enabled
  356. and has to return `True` if the template is still up to date. For more
  357. details have a look at :meth:`BaseLoader.get_source` which has the same
  358. return value.
  359. """
  360. def __init__(
  361. self,
  362. load_func: t.Callable[
  363. [str],
  364. t.Optional[
  365. t.Union[
  366. str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]
  367. ]
  368. ],
  369. ],
  370. ) -> None:
  371. self.load_func = load_func
  372. def get_source(
  373. self, environment: "Environment", template: str
  374. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  375. rv = self.load_func(template)
  376. if rv is None:
  377. raise TemplateNotFound(template)
  378. if isinstance(rv, str):
  379. return rv, None, None
  380. return rv
  381. class PrefixLoader(BaseLoader):
  382. """A loader that is passed a dict of loaders where each loader is bound
  383. to a prefix. The prefix is delimited from the template by a slash per
  384. default, which can be changed by setting the `delimiter` argument to
  385. something else::
  386. loader = PrefixLoader({
  387. 'app1': PackageLoader('mypackage.app1'),
  388. 'app2': PackageLoader('mypackage.app2')
  389. })
  390. By loading ``'app1/index.html'`` the file from the app1 package is loaded,
  391. by loading ``'app2/index.html'`` the file from the second.
  392. """
  393. def __init__(
  394. self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/"
  395. ) -> None:
  396. self.mapping = mapping
  397. self.delimiter = delimiter
  398. def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]:
  399. try:
  400. prefix, name = template.split(self.delimiter, 1)
  401. loader = self.mapping[prefix]
  402. except (ValueError, KeyError) as e:
  403. raise TemplateNotFound(template) from e
  404. return loader, name
  405. def get_source(
  406. self, environment: "Environment", template: str
  407. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  408. loader, name = self.get_loader(template)
  409. try:
  410. return loader.get_source(environment, name)
  411. except TemplateNotFound as e:
  412. # re-raise the exception with the correct filename here.
  413. # (the one that includes the prefix)
  414. raise TemplateNotFound(template) from e
  415. @internalcode
  416. def load(
  417. self,
  418. environment: "Environment",
  419. name: str,
  420. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  421. ) -> "Template":
  422. loader, local_name = self.get_loader(name)
  423. try:
  424. return loader.load(environment, local_name, globals)
  425. except TemplateNotFound as e:
  426. # re-raise the exception with the correct filename here.
  427. # (the one that includes the prefix)
  428. raise TemplateNotFound(name) from e
  429. def list_templates(self) -> t.List[str]:
  430. result = []
  431. for prefix, loader in self.mapping.items():
  432. for template in loader.list_templates():
  433. result.append(prefix + self.delimiter + template)
  434. return result
  435. class ChoiceLoader(BaseLoader):
  436. """This loader works like the `PrefixLoader` just that no prefix is
  437. specified. If a template could not be found by one loader the next one
  438. is tried.
  439. >>> loader = ChoiceLoader([
  440. ... FileSystemLoader('/path/to/user/templates'),
  441. ... FileSystemLoader('/path/to/system/templates')
  442. ... ])
  443. This is useful if you want to allow users to override builtin templates
  444. from a different location.
  445. """
  446. def __init__(self, loaders: t.Sequence[BaseLoader]) -> None:
  447. self.loaders = loaders
  448. def get_source(
  449. self, environment: "Environment", template: str
  450. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  451. for loader in self.loaders:
  452. try:
  453. return loader.get_source(environment, template)
  454. except TemplateNotFound:
  455. pass
  456. raise TemplateNotFound(template)
  457. @internalcode
  458. def load(
  459. self,
  460. environment: "Environment",
  461. name: str,
  462. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  463. ) -> "Template":
  464. for loader in self.loaders:
  465. try:
  466. return loader.load(environment, name, globals)
  467. except TemplateNotFound:
  468. pass
  469. raise TemplateNotFound(name)
  470. def list_templates(self) -> t.List[str]:
  471. found = set()
  472. for loader in self.loaders:
  473. found.update(loader.list_templates())
  474. return sorted(found)
  475. class _TemplateModule(ModuleType):
  476. """Like a normal module but with support for weak references"""
  477. class ModuleLoader(BaseLoader):
  478. """This loader loads templates from precompiled templates.
  479. Example usage:
  480. >>> loader = ChoiceLoader([
  481. ... ModuleLoader('/path/to/compiled/templates'),
  482. ... FileSystemLoader('/path/to/templates')
  483. ... ])
  484. Templates can be precompiled with :meth:`Environment.compile_templates`.
  485. """
  486. has_source_access = False
  487. def __init__(
  488. self,
  489. path: t.Union[
  490. str, "os.PathLike[str]", t.Sequence[t.Union[str, "os.PathLike[str]"]]
  491. ],
  492. ) -> None:
  493. package_name = f"_jinja2_module_templates_{id(self):x}"
  494. # create a fake module that looks for the templates in the
  495. # path given.
  496. mod = _TemplateModule(package_name)
  497. if not isinstance(path, abc.Iterable) or isinstance(path, str):
  498. path = [path]
  499. mod.__path__ = [os.fspath(p) for p in path]
  500. sys.modules[package_name] = weakref.proxy(
  501. mod, lambda x: sys.modules.pop(package_name, None)
  502. )
  503. # the only strong reference, the sys.modules entry is weak
  504. # so that the garbage collector can remove it once the
  505. # loader that created it goes out of business.
  506. self.module = mod
  507. self.package_name = package_name
  508. @staticmethod
  509. def get_template_key(name: str) -> str:
  510. return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
  511. @staticmethod
  512. def get_module_filename(name: str) -> str:
  513. return ModuleLoader.get_template_key(name) + ".py"
  514. @internalcode
  515. def load(
  516. self,
  517. environment: "Environment",
  518. name: str,
  519. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  520. ) -> "Template":
  521. key = self.get_template_key(name)
  522. module = f"{self.package_name}.{key}"
  523. mod = getattr(self.module, module, None)
  524. if mod is None:
  525. try:
  526. mod = __import__(module, None, None, ["root"])
  527. except ImportError as e:
  528. raise TemplateNotFound(name) from e
  529. # remove the entry from sys.modules, we only want the attribute
  530. # on the module object we have stored on the loader.
  531. sys.modules.pop(module, None)
  532. if globals is None:
  533. globals = {}
  534. return environment.template_class.from_module_dict(
  535. environment, mod.__dict__, globals
  536. )