You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

643 lines
22KB

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