loaders.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652
  1. """API and implementations for loading templates from different data
  2. sources.
  3. """
  4. import importlib.util
  5. import os
  6. import sys
  7. import typing as t
  8. import weakref
  9. import zipimport
  10. from collections import abc
  11. from hashlib import sha1
  12. from importlib import import_module
  13. from types import ModuleType
  14. from .exceptions import TemplateNotFound
  15. from .utils import internalcode
  16. from .utils import open_if_exists
  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[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]],
  148. encoding: str = "utf-8",
  149. followlinks: bool = False,
  150. ) -> None:
  151. if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):
  152. searchpath = [searchpath]
  153. self.searchpath = [os.fspath(p) for p in searchpath]
  154. self.encoding = encoding
  155. self.followlinks = followlinks
  156. def get_source(
  157. self, environment: "Environment", template: str
  158. ) -> t.Tuple[str, str, t.Callable[[], bool]]:
  159. pieces = split_template_path(template)
  160. for searchpath in self.searchpath:
  161. filename = os.path.join(searchpath, *pieces)
  162. f = open_if_exists(filename)
  163. if f is None:
  164. continue
  165. try:
  166. contents = f.read().decode(self.encoding)
  167. finally:
  168. f.close()
  169. mtime = os.path.getmtime(filename)
  170. def uptodate() -> bool:
  171. try:
  172. return os.path.getmtime(filename) == mtime
  173. except OSError:
  174. return False
  175. return contents, filename, uptodate
  176. raise TemplateNotFound(template)
  177. def list_templates(self) -> t.List[str]:
  178. found = set()
  179. for searchpath in self.searchpath:
  180. walk_dir = os.walk(searchpath, followlinks=self.followlinks)
  181. for dirpath, _, filenames in walk_dir:
  182. for filename in filenames:
  183. template = (
  184. os.path.join(dirpath, filename)[len(searchpath) :]
  185. .strip(os.path.sep)
  186. .replace(os.path.sep, "/")
  187. )
  188. if template[:2] == "./":
  189. template = template[2:]
  190. if template not in found:
  191. found.add(template)
  192. return sorted(found)
  193. class PackageLoader(BaseLoader):
  194. """Load templates from a directory in a Python package.
  195. :param package_name: Import name of the package that contains the
  196. template directory.
  197. :param package_path: Directory within the imported package that
  198. contains the templates.
  199. :param encoding: Encoding of template files.
  200. The following example looks up templates in the ``pages`` directory
  201. within the ``project.ui`` package.
  202. .. code-block:: python
  203. loader = PackageLoader("project.ui", "pages")
  204. Only packages installed as directories (standard pip behavior) or
  205. zip/egg files (less common) are supported. The Python API for
  206. introspecting data in packages is too limited to support other
  207. installation methods the way this loader requires.
  208. There is limited support for :pep:`420` namespace packages. The
  209. template directory is assumed to only be in one namespace
  210. contributor. Zip files contributing to a namespace are not
  211. supported.
  212. .. versionchanged:: 3.0
  213. No longer uses ``setuptools`` as a dependency.
  214. .. versionchanged:: 3.0
  215. Limited PEP 420 namespace package support.
  216. """
  217. def __init__(
  218. self,
  219. package_name: str,
  220. package_path: "str" = "templates",
  221. encoding: str = "utf-8",
  222. ) -> None:
  223. package_path = os.path.normpath(package_path).rstrip(os.path.sep)
  224. # normpath preserves ".", which isn't valid in zip paths.
  225. if package_path == os.path.curdir:
  226. package_path = ""
  227. elif package_path[:2] == os.path.curdir + os.path.sep:
  228. package_path = package_path[2:]
  229. self.package_path = package_path
  230. self.package_name = package_name
  231. self.encoding = encoding
  232. # Make sure the package exists. This also makes namespace
  233. # packages work, otherwise get_loader returns None.
  234. import_module(package_name)
  235. spec = importlib.util.find_spec(package_name)
  236. assert spec is not None, "An import spec was not found for the package."
  237. loader = spec.loader
  238. assert loader is not None, "A loader was not found for the package."
  239. self._loader = loader
  240. self._archive = None
  241. template_root = None
  242. if isinstance(loader, zipimport.zipimporter):
  243. self._archive = loader.archive
  244. pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
  245. template_root = os.path.join(pkgdir, package_path)
  246. else:
  247. roots: t.List[str] = []
  248. # One element for regular packages, multiple for namespace
  249. # packages, or None for single module file.
  250. if spec.submodule_search_locations:
  251. roots.extend(spec.submodule_search_locations)
  252. # A single module file, use the parent directory instead.
  253. elif spec.origin is not None:
  254. roots.append(os.path.dirname(spec.origin))
  255. for root in roots:
  256. root = os.path.join(root, package_path)
  257. if os.path.isdir(root):
  258. template_root = root
  259. break
  260. if template_root is None:
  261. raise ValueError(
  262. f"The {package_name!r} package was not installed in a"
  263. " way that PackageLoader understands."
  264. )
  265. self._template_root = template_root
  266. def get_source(
  267. self, environment: "Environment", template: str
  268. ) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:
  269. p = os.path.join(self._template_root, *split_template_path(template))
  270. up_to_date: t.Optional[t.Callable[[], bool]]
  271. if self._archive is None:
  272. # Package is a directory.
  273. if not os.path.isfile(p):
  274. raise TemplateNotFound(template)
  275. with open(p, "rb") as f:
  276. source = f.read()
  277. mtime = os.path.getmtime(p)
  278. def up_to_date() -> bool:
  279. return os.path.isfile(p) and os.path.getmtime(p) == mtime
  280. else:
  281. # Package is a zip file.
  282. try:
  283. source = self._loader.get_data(p) # type: ignore
  284. except OSError as e:
  285. raise TemplateNotFound(template) from e
  286. # Could use the zip's mtime for all template mtimes, but
  287. # would need to safely reload the module if it's out of
  288. # date, so just report it as always current.
  289. up_to_date = None
  290. return source.decode(self.encoding), p, up_to_date
  291. def list_templates(self) -> t.List[str]:
  292. results: t.List[str] = []
  293. if self._archive is None:
  294. # Package is a directory.
  295. offset = len(self._template_root)
  296. for dirpath, _, filenames in os.walk(self._template_root):
  297. dirpath = dirpath[offset:].lstrip(os.path.sep)
  298. results.extend(
  299. os.path.join(dirpath, name).replace(os.path.sep, "/")
  300. for name in filenames
  301. )
  302. else:
  303. if not hasattr(self._loader, "_files"):
  304. raise TypeError(
  305. "This zip import does not have the required"
  306. " metadata to list templates."
  307. )
  308. # Package is a zip file.
  309. prefix = (
  310. self._template_root[len(self._archive) :].lstrip(os.path.sep)
  311. + os.path.sep
  312. )
  313. offset = len(prefix)
  314. for name in self._loader._files.keys(): # type: ignore
  315. # Find names under the templates directory that aren't directories.
  316. if name.startswith(prefix) and name[-1] != os.path.sep:
  317. results.append(name[offset:].replace(os.path.sep, "/"))
  318. results.sort()
  319. return results
  320. class DictLoader(BaseLoader):
  321. """Loads a template from a Python dict mapping template names to
  322. template source. This loader is useful for unittesting:
  323. >>> loader = DictLoader({'index.html': 'source here'})
  324. Because auto reloading is rarely useful this is disabled per default.
  325. """
  326. def __init__(self, mapping: t.Mapping[str, str]) -> None:
  327. self.mapping = mapping
  328. def get_source(
  329. self, environment: "Environment", template: str
  330. ) -> t.Tuple[str, None, t.Callable[[], bool]]:
  331. if template in self.mapping:
  332. source = self.mapping[template]
  333. return source, None, lambda: source == self.mapping.get(template)
  334. raise TemplateNotFound(template)
  335. def list_templates(self) -> t.List[str]:
  336. return sorted(self.mapping)
  337. class FunctionLoader(BaseLoader):
  338. """A loader that is passed a function which does the loading. The
  339. function receives the name of the template and has to return either
  340. a string with the template source, a tuple in the form ``(source,
  341. filename, uptodatefunc)`` or `None` if the template does not exist.
  342. >>> def load_template(name):
  343. ... if name == 'index.html':
  344. ... return '...'
  345. ...
  346. >>> loader = FunctionLoader(load_template)
  347. The `uptodatefunc` is a function that is called if autoreload is enabled
  348. and has to return `True` if the template is still up to date. For more
  349. details have a look at :meth:`BaseLoader.get_source` which has the same
  350. return value.
  351. """
  352. def __init__(
  353. self,
  354. load_func: t.Callable[
  355. [str],
  356. t.Optional[
  357. t.Union[
  358. str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]
  359. ]
  360. ],
  361. ],
  362. ) -> None:
  363. self.load_func = load_func
  364. def get_source(
  365. self, environment: "Environment", template: str
  366. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  367. rv = self.load_func(template)
  368. if rv is None:
  369. raise TemplateNotFound(template)
  370. if isinstance(rv, str):
  371. return rv, None, None
  372. return rv
  373. class PrefixLoader(BaseLoader):
  374. """A loader that is passed a dict of loaders where each loader is bound
  375. to a prefix. The prefix is delimited from the template by a slash per
  376. default, which can be changed by setting the `delimiter` argument to
  377. something else::
  378. loader = PrefixLoader({
  379. 'app1': PackageLoader('mypackage.app1'),
  380. 'app2': PackageLoader('mypackage.app2')
  381. })
  382. By loading ``'app1/index.html'`` the file from the app1 package is loaded,
  383. by loading ``'app2/index.html'`` the file from the second.
  384. """
  385. def __init__(
  386. self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/"
  387. ) -> None:
  388. self.mapping = mapping
  389. self.delimiter = delimiter
  390. def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]:
  391. try:
  392. prefix, name = template.split(self.delimiter, 1)
  393. loader = self.mapping[prefix]
  394. except (ValueError, KeyError) as e:
  395. raise TemplateNotFound(template) from e
  396. return loader, name
  397. def get_source(
  398. self, environment: "Environment", template: str
  399. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  400. loader, name = self.get_loader(template)
  401. try:
  402. return loader.get_source(environment, name)
  403. except TemplateNotFound as e:
  404. # re-raise the exception with the correct filename here.
  405. # (the one that includes the prefix)
  406. raise TemplateNotFound(template) from e
  407. @internalcode
  408. def load(
  409. self,
  410. environment: "Environment",
  411. name: str,
  412. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  413. ) -> "Template":
  414. loader, local_name = self.get_loader(name)
  415. try:
  416. return loader.load(environment, local_name, globals)
  417. except TemplateNotFound as e:
  418. # re-raise the exception with the correct filename here.
  419. # (the one that includes the prefix)
  420. raise TemplateNotFound(name) from e
  421. def list_templates(self) -> t.List[str]:
  422. result = []
  423. for prefix, loader in self.mapping.items():
  424. for template in loader.list_templates():
  425. result.append(prefix + self.delimiter + template)
  426. return result
  427. class ChoiceLoader(BaseLoader):
  428. """This loader works like the `PrefixLoader` just that no prefix is
  429. specified. If a template could not be found by one loader the next one
  430. is tried.
  431. >>> loader = ChoiceLoader([
  432. ... FileSystemLoader('/path/to/user/templates'),
  433. ... FileSystemLoader('/path/to/system/templates')
  434. ... ])
  435. This is useful if you want to allow users to override builtin templates
  436. from a different location.
  437. """
  438. def __init__(self, loaders: t.Sequence[BaseLoader]) -> None:
  439. self.loaders = loaders
  440. def get_source(
  441. self, environment: "Environment", template: str
  442. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  443. for loader in self.loaders:
  444. try:
  445. return loader.get_source(environment, template)
  446. except TemplateNotFound:
  447. pass
  448. raise TemplateNotFound(template)
  449. @internalcode
  450. def load(
  451. self,
  452. environment: "Environment",
  453. name: str,
  454. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  455. ) -> "Template":
  456. for loader in self.loaders:
  457. try:
  458. return loader.load(environment, name, globals)
  459. except TemplateNotFound:
  460. pass
  461. raise TemplateNotFound(name)
  462. def list_templates(self) -> t.List[str]:
  463. found = set()
  464. for loader in self.loaders:
  465. found.update(loader.list_templates())
  466. return sorted(found)
  467. class _TemplateModule(ModuleType):
  468. """Like a normal module but with support for weak references"""
  469. class ModuleLoader(BaseLoader):
  470. """This loader loads templates from precompiled templates.
  471. Example usage:
  472. >>> loader = ChoiceLoader([
  473. ... ModuleLoader('/path/to/compiled/templates'),
  474. ... FileSystemLoader('/path/to/templates')
  475. ... ])
  476. Templates can be precompiled with :meth:`Environment.compile_templates`.
  477. """
  478. has_source_access = False
  479. def __init__(
  480. self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]]
  481. ) -> None:
  482. package_name = f"_jinja2_module_templates_{id(self):x}"
  483. # create a fake module that looks for the templates in the
  484. # path given.
  485. mod = _TemplateModule(package_name)
  486. if not isinstance(path, abc.Iterable) or isinstance(path, str):
  487. path = [path]
  488. mod.__path__ = [os.fspath(p) for p in path] # type: ignore
  489. sys.modules[package_name] = weakref.proxy(
  490. mod, lambda x: sys.modules.pop(package_name, None)
  491. )
  492. # the only strong reference, the sys.modules entry is weak
  493. # so that the garbage collector can remove it once the
  494. # loader that created it goes out of business.
  495. self.module = mod
  496. self.package_name = package_name
  497. @staticmethod
  498. def get_template_key(name: str) -> str:
  499. return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
  500. @staticmethod
  501. def get_module_filename(name: str) -> str:
  502. return ModuleLoader.get_template_key(name) + ".py"
  503. @internalcode
  504. def load(
  505. self,
  506. environment: "Environment",
  507. name: str,
  508. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  509. ) -> "Template":
  510. key = self.get_template_key(name)
  511. module = f"{self.package_name}.{key}"
  512. mod = getattr(self.module, module, None)
  513. if mod is None:
  514. try:
  515. mod = __import__(module, None, None, ["root"])
  516. except ImportError as e:
  517. raise TemplateNotFound(name) from e
  518. # remove the entry from sys.modules, we only want the attribute
  519. # on the module object we have stored on the loader.
  520. sys.modules.pop(module, None)
  521. if globals is None:
  522. globals = {}
  523. return environment.template_class.from_module_dict(
  524. environment, mod.__dict__, globals
  525. )