loaders.py 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695
  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[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]],
  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. package = 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. self._package = package
  245. template_root = None
  246. if isinstance(loader, zipimport.zipimporter):
  247. self._archive = loader.archive
  248. pkgdir = next(iter(spec.submodule_search_locations)) # type: ignore
  249. template_root = os.path.join(pkgdir, package_path).rstrip(os.path.sep)
  250. elif hasattr(loader, "arcadia_source_finder"):
  251. template_root = os.path.dirname(package.__file__).rstrip(os.path.sep)
  252. else:
  253. roots: t.List[str] = []
  254. # One element for regular packages, multiple for namespace
  255. # packages, or None for single module file.
  256. if spec.submodule_search_locations:
  257. roots.extend(spec.submodule_search_locations)
  258. # A single module file, use the parent directory instead.
  259. elif spec.origin is not None:
  260. roots.append(os.path.dirname(spec.origin))
  261. for root in roots:
  262. root = os.path.join(root, package_path)
  263. if os.path.isdir(root):
  264. template_root = root
  265. break
  266. if template_root is None:
  267. raise ValueError(
  268. f"The {package_name!r} package was not installed in a"
  269. " way that PackageLoader understands."
  270. )
  271. self._template_root = template_root
  272. def get_source(
  273. self, environment: "Environment", template: str
  274. ) -> t.Tuple[str, str, t.Optional[t.Callable[[], bool]]]:
  275. # Use posixpath even on Windows to avoid "drive:" or UNC
  276. # segments breaking out of the search directory. Use normpath to
  277. # convert Windows altsep to sep.
  278. p = os.path.normpath(
  279. posixpath.join(self._template_root, *split_template_path(template))
  280. )
  281. up_to_date: t.Optional[t.Callable[[], bool]]
  282. if self._archive is None and hasattr(self, "_package"):
  283. try:
  284. source = pkgutil.get_data(self.package_name, os.path.join(self.package_path, *split_template_path(template)))
  285. except OSError:
  286. raise TemplateNotFound(template)
  287. def up_to_date() -> bool:
  288. return True
  289. elif self._archive is None:
  290. # Package is a directory.
  291. if not os.path.isfile(p):
  292. raise TemplateNotFound(template)
  293. with open(p, "rb") as f:
  294. source = f.read()
  295. mtime = os.path.getmtime(p)
  296. def up_to_date() -> bool:
  297. return os.path.isfile(p) and os.path.getmtime(p) == mtime
  298. else:
  299. # Package is a zip file.
  300. try:
  301. source = self._loader.get_data(p) # type: ignore
  302. except OSError as e:
  303. raise TemplateNotFound(template) from e
  304. # Could use the zip's mtime for all template mtimes, but
  305. # would need to safely reload the module if it's out of
  306. # date, so just report it as always current.
  307. up_to_date = None
  308. return source.decode(self.encoding), p, up_to_date
  309. def list_templates(self) -> t.List[str]:
  310. results: t.List[str] = []
  311. if self._archive is None and hasattr(self, "_package"):
  312. prefix = os.path.join(self._template_root, self.package_path).encode() + b"/"
  313. for name in arcadia_res.resfs_files(prefix):
  314. results.append(name.removeprefix(prefix).decode())
  315. elif self._archive is None:
  316. # Package is a directory.
  317. offset = len(self._template_root)
  318. for dirpath, _, filenames in os.walk(self._template_root):
  319. dirpath = dirpath[offset:].lstrip(os.path.sep)
  320. results.extend(
  321. os.path.join(dirpath, name).replace(os.path.sep, "/")
  322. for name in filenames
  323. )
  324. else:
  325. if not hasattr(self._loader, "_files"):
  326. raise TypeError(
  327. "This zip import does not have the required"
  328. " metadata to list templates."
  329. )
  330. # Package is a zip file.
  331. prefix = (
  332. self._template_root[len(self._archive) :].lstrip(os.path.sep)
  333. + os.path.sep
  334. )
  335. offset = len(prefix)
  336. for name in self._loader._files.keys():
  337. # Find names under the templates directory that aren't directories.
  338. if name.startswith(prefix) and name[-1] != os.path.sep:
  339. results.append(name[offset:].replace(os.path.sep, "/"))
  340. results.sort()
  341. return results
  342. class DictLoader(BaseLoader):
  343. """Loads a template from a Python dict mapping template names to
  344. template source. This loader is useful for unittesting:
  345. >>> loader = DictLoader({'index.html': 'source here'})
  346. Because auto reloading is rarely useful this is disabled per default.
  347. """
  348. def __init__(self, mapping: t.Mapping[str, str]) -> None:
  349. self.mapping = mapping
  350. def get_source(
  351. self, environment: "Environment", template: str
  352. ) -> t.Tuple[str, None, t.Callable[[], bool]]:
  353. if template in self.mapping:
  354. source = self.mapping[template]
  355. return source, None, lambda: source == self.mapping.get(template)
  356. raise TemplateNotFound(template)
  357. def list_templates(self) -> t.List[str]:
  358. return sorted(self.mapping)
  359. class FunctionLoader(BaseLoader):
  360. """A loader that is passed a function which does the loading. The
  361. function receives the name of the template and has to return either
  362. a string with the template source, a tuple in the form ``(source,
  363. filename, uptodatefunc)`` or `None` if the template does not exist.
  364. >>> def load_template(name):
  365. ... if name == 'index.html':
  366. ... return '...'
  367. ...
  368. >>> loader = FunctionLoader(load_template)
  369. The `uptodatefunc` is a function that is called if autoreload is enabled
  370. and has to return `True` if the template is still up to date. For more
  371. details have a look at :meth:`BaseLoader.get_source` which has the same
  372. return value.
  373. """
  374. def __init__(
  375. self,
  376. load_func: t.Callable[
  377. [str],
  378. t.Optional[
  379. t.Union[
  380. str, t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]
  381. ]
  382. ],
  383. ],
  384. ) -> None:
  385. self.load_func = load_func
  386. def get_source(
  387. self, environment: "Environment", template: str
  388. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  389. rv = self.load_func(template)
  390. if rv is None:
  391. raise TemplateNotFound(template)
  392. if isinstance(rv, str):
  393. return rv, None, None
  394. return rv
  395. class PrefixLoader(BaseLoader):
  396. """A loader that is passed a dict of loaders where each loader is bound
  397. to a prefix. The prefix is delimited from the template by a slash per
  398. default, which can be changed by setting the `delimiter` argument to
  399. something else::
  400. loader = PrefixLoader({
  401. 'app1': PackageLoader('mypackage.app1'),
  402. 'app2': PackageLoader('mypackage.app2')
  403. })
  404. By loading ``'app1/index.html'`` the file from the app1 package is loaded,
  405. by loading ``'app2/index.html'`` the file from the second.
  406. """
  407. def __init__(
  408. self, mapping: t.Mapping[str, BaseLoader], delimiter: str = "/"
  409. ) -> None:
  410. self.mapping = mapping
  411. self.delimiter = delimiter
  412. def get_loader(self, template: str) -> t.Tuple[BaseLoader, str]:
  413. try:
  414. prefix, name = template.split(self.delimiter, 1)
  415. loader = self.mapping[prefix]
  416. except (ValueError, KeyError) as e:
  417. raise TemplateNotFound(template) from e
  418. return loader, name
  419. def get_source(
  420. self, environment: "Environment", template: str
  421. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  422. loader, name = self.get_loader(template)
  423. try:
  424. return loader.get_source(environment, name)
  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(template) from e
  429. @internalcode
  430. def load(
  431. self,
  432. environment: "Environment",
  433. name: str,
  434. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  435. ) -> "Template":
  436. loader, local_name = self.get_loader(name)
  437. try:
  438. return loader.load(environment, local_name, globals)
  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(name) from e
  443. def list_templates(self) -> t.List[str]:
  444. result = []
  445. for prefix, loader in self.mapping.items():
  446. for template in loader.list_templates():
  447. result.append(prefix + self.delimiter + template)
  448. return result
  449. class ChoiceLoader(BaseLoader):
  450. """This loader works like the `PrefixLoader` just that no prefix is
  451. specified. If a template could not be found by one loader the next one
  452. is tried.
  453. >>> loader = ChoiceLoader([
  454. ... FileSystemLoader('/path/to/user/templates'),
  455. ... FileSystemLoader('/path/to/system/templates')
  456. ... ])
  457. This is useful if you want to allow users to override builtin templates
  458. from a different location.
  459. """
  460. def __init__(self, loaders: t.Sequence[BaseLoader]) -> None:
  461. self.loaders = loaders
  462. def get_source(
  463. self, environment: "Environment", template: str
  464. ) -> t.Tuple[str, t.Optional[str], t.Optional[t.Callable[[], bool]]]:
  465. for loader in self.loaders:
  466. try:
  467. return loader.get_source(environment, template)
  468. except TemplateNotFound:
  469. pass
  470. raise TemplateNotFound(template)
  471. @internalcode
  472. def load(
  473. self,
  474. environment: "Environment",
  475. name: str,
  476. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  477. ) -> "Template":
  478. for loader in self.loaders:
  479. try:
  480. return loader.load(environment, name, globals)
  481. except TemplateNotFound:
  482. pass
  483. raise TemplateNotFound(name)
  484. def list_templates(self) -> t.List[str]:
  485. found = set()
  486. for loader in self.loaders:
  487. found.update(loader.list_templates())
  488. return sorted(found)
  489. class _TemplateModule(ModuleType):
  490. """Like a normal module but with support for weak references"""
  491. class ModuleLoader(BaseLoader):
  492. """This loader loads templates from precompiled templates.
  493. Example usage:
  494. >>> loader = ChoiceLoader([
  495. ... ModuleLoader('/path/to/compiled/templates'),
  496. ... FileSystemLoader('/path/to/templates')
  497. ... ])
  498. Templates can be precompiled with :meth:`Environment.compile_templates`.
  499. """
  500. has_source_access = False
  501. def __init__(
  502. self, path: t.Union[str, os.PathLike, t.Sequence[t.Union[str, os.PathLike]]]
  503. ) -> None:
  504. package_name = f"_jinja2_module_templates_{id(self):x}"
  505. # create a fake module that looks for the templates in the
  506. # path given.
  507. mod = _TemplateModule(package_name)
  508. if not isinstance(path, abc.Iterable) or isinstance(path, str):
  509. path = [path]
  510. mod.__path__ = [os.fspath(p) for p in path]
  511. sys.modules[package_name] = weakref.proxy(
  512. mod, lambda x: sys.modules.pop(package_name, None)
  513. )
  514. # the only strong reference, the sys.modules entry is weak
  515. # so that the garbage collector can remove it once the
  516. # loader that created it goes out of business.
  517. self.module = mod
  518. self.package_name = package_name
  519. @staticmethod
  520. def get_template_key(name: str) -> str:
  521. return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
  522. @staticmethod
  523. def get_module_filename(name: str) -> str:
  524. return ModuleLoader.get_template_key(name) + ".py"
  525. @internalcode
  526. def load(
  527. self,
  528. environment: "Environment",
  529. name: str,
  530. globals: t.Optional[t.MutableMapping[str, t.Any]] = None,
  531. ) -> "Template":
  532. key = self.get_template_key(name)
  533. module = f"{self.package_name}.{key}"
  534. mod = getattr(self.module, module, None)
  535. if mod is None:
  536. try:
  537. mod = __import__(module, None, None, ["root"])
  538. except ImportError as e:
  539. raise TemplateNotFound(name) from e
  540. # remove the entry from sys.modules, we only want the attribute
  541. # on the module object we have stored on the loader.
  542. sys.modules.pop(module, None)
  543. if globals is None:
  544. globals = {}
  545. return environment.template_class.from_module_dict(
  546. environment, mod.__dict__, globals
  547. )
  548. class ResourceLoader(BaseLoader):
  549. def __init__(self, prefix, module_loader):
  550. self.prefix = prefix
  551. self.module_loader = module_loader
  552. def get_source(self, environment, template):
  553. if self.module_loader is None:
  554. raise TemplateNotFound(template)
  555. try:
  556. return self.module_loader.get_data(os.path.join(self.prefix, template)).decode('utf-8'), None, None
  557. except IOError:
  558. raise TemplateNotFound(template)