loaders.py 24 KB

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