loaders.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504
  1. # -*- coding: utf-8 -*-
  2. """API and implementations for loading templates from different data
  3. sources.
  4. """
  5. import os
  6. import sys
  7. import weakref
  8. from hashlib import sha1
  9. from os import path
  10. from types import ModuleType
  11. from ._compat import abc
  12. from ._compat import fspath
  13. from ._compat import iteritems
  14. from ._compat import string_types
  15. from .exceptions import TemplateNotFound
  16. from .utils import internalcode
  17. from .utils import open_if_exists
  18. def split_template_path(template):
  19. """Split a path into segments and perform a sanity check. If it detects
  20. '..' in the path it will raise a `TemplateNotFound` error.
  21. """
  22. pieces = []
  23. for piece in template.split("/"):
  24. if (
  25. path.sep in piece
  26. or (path.altsep and path.altsep in piece)
  27. or piece == path.pardir
  28. ):
  29. raise TemplateNotFound(template)
  30. elif piece and piece != ".":
  31. pieces.append(piece)
  32. return pieces
  33. class BaseLoader(object):
  34. """Baseclass for all loaders. Subclass this and override `get_source` to
  35. implement a custom loading mechanism. The environment provides a
  36. `get_template` method that calls the loader's `load` method to get the
  37. :class:`Template` object.
  38. A very basic example for a loader that looks up templates on the file
  39. system could look like this::
  40. from jinja2 import BaseLoader, TemplateNotFound
  41. from os.path import join, exists, getmtime
  42. class MyLoader(BaseLoader):
  43. def __init__(self, path):
  44. self.path = path
  45. def get_source(self, environment, template):
  46. path = join(self.path, template)
  47. if not exists(path):
  48. raise TemplateNotFound(template)
  49. mtime = getmtime(path)
  50. with file(path) as f:
  51. source = f.read().decode('utf-8')
  52. return source, path, lambda: mtime == getmtime(path)
  53. """
  54. #: if set to `False` it indicates that the loader cannot provide access
  55. #: to the source of templates.
  56. #:
  57. #: .. versionadded:: 2.4
  58. has_source_access = True
  59. def get_source(self, environment, template):
  60. """Get the template source, filename and reload helper for a template.
  61. It's passed the environment and template name and has to return a
  62. tuple in the form ``(source, filename, uptodate)`` or raise a
  63. `TemplateNotFound` error if it can't locate the template.
  64. The source part of the returned tuple must be the source of the
  65. template as unicode string or a ASCII bytestring. The filename should
  66. be the name of the file on the filesystem if it was loaded from there,
  67. otherwise `None`. The filename is used by python for the tracebacks
  68. if no loader extension is used.
  69. The last item in the tuple is the `uptodate` function. If auto
  70. reloading is enabled it's always called to check if the template
  71. changed. No arguments are passed so the function must store the
  72. old state somewhere (for example in a closure). If it returns `False`
  73. the template will be reloaded.
  74. """
  75. if not self.has_source_access:
  76. raise RuntimeError(
  77. "%s cannot provide access to the source" % self.__class__.__name__
  78. )
  79. raise TemplateNotFound(template)
  80. def list_templates(self):
  81. """Iterates over all templates. If the loader does not support that
  82. it should raise a :exc:`TypeError` which is the default behavior.
  83. """
  84. raise TypeError("this loader cannot iterate over all templates")
  85. @internalcode
  86. def load(self, environment, name, globals=None):
  87. """Loads a template. This method looks up the template in the cache
  88. or loads one by calling :meth:`get_source`. Subclasses should not
  89. override this method as loaders working on collections of other
  90. loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)
  91. will not call this method but `get_source` directly.
  92. """
  93. code = None
  94. if globals is None:
  95. globals = {}
  96. # first we try to get the source for this template together
  97. # with the filename and the uptodate function.
  98. source, filename, uptodate = self.get_source(environment, name)
  99. # try to load the code from the bytecode cache if there is a
  100. # bytecode cache configured.
  101. bcc = environment.bytecode_cache
  102. if bcc is not None:
  103. bucket = bcc.get_bucket(environment, name, filename, source)
  104. code = bucket.code
  105. # if we don't have code so far (not cached, no longer up to
  106. # date) etc. we compile the template
  107. if code is None:
  108. code = environment.compile(source, name, filename)
  109. # if the bytecode cache is available and the bucket doesn't
  110. # have a code so far, we give the bucket the new code and put
  111. # it back to the bytecode cache.
  112. if bcc is not None and bucket.code is None:
  113. bucket.code = code
  114. bcc.set_bucket(bucket)
  115. return environment.template_class.from_code(
  116. environment, code, globals, uptodate
  117. )
  118. class FileSystemLoader(BaseLoader):
  119. """Loads templates from the file system. This loader can find templates
  120. in folders on the file system and is the preferred way to load them.
  121. The loader takes the path to the templates as string, or if multiple
  122. locations are wanted a list of them which is then looked up in the
  123. given order::
  124. >>> loader = FileSystemLoader('/path/to/templates')
  125. >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])
  126. Per default the template encoding is ``'utf-8'`` which can be changed
  127. by setting the `encoding` parameter to something else.
  128. To follow symbolic links, set the *followlinks* parameter to ``True``::
  129. >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)
  130. .. versionchanged:: 2.8
  131. The ``followlinks`` parameter was added.
  132. """
  133. def __init__(self, searchpath, encoding="utf-8", followlinks=False):
  134. if not isinstance(searchpath, abc.Iterable) or isinstance(
  135. searchpath, string_types
  136. ):
  137. searchpath = [searchpath]
  138. # In Python 3.5, os.path.join doesn't support Path. This can be
  139. # simplified to list(searchpath) when Python 3.5 is dropped.
  140. self.searchpath = [fspath(p) for p in searchpath]
  141. self.encoding = encoding
  142. self.followlinks = followlinks
  143. def get_source(self, environment, template):
  144. pieces = split_template_path(template)
  145. for searchpath in self.searchpath:
  146. filename = path.join(searchpath, *pieces)
  147. f = open_if_exists(filename)
  148. if f is None:
  149. continue
  150. try:
  151. contents = f.read().decode(self.encoding)
  152. finally:
  153. f.close()
  154. mtime = path.getmtime(filename)
  155. def uptodate():
  156. try:
  157. return path.getmtime(filename) == mtime
  158. except OSError:
  159. return False
  160. return contents, filename, uptodate
  161. raise TemplateNotFound(template)
  162. def list_templates(self):
  163. found = set()
  164. for searchpath in self.searchpath:
  165. walk_dir = os.walk(searchpath, followlinks=self.followlinks)
  166. for dirpath, _, filenames in walk_dir:
  167. for filename in filenames:
  168. template = (
  169. os.path.join(dirpath, filename)[len(searchpath) :]
  170. .strip(os.path.sep)
  171. .replace(os.path.sep, "/")
  172. )
  173. if template[:2] == "./":
  174. template = template[2:]
  175. if template not in found:
  176. found.add(template)
  177. return sorted(found)
  178. class PackageLoader(BaseLoader):
  179. """Load templates from python eggs or packages. It is constructed with
  180. the name of the python package and the path to the templates in that
  181. package::
  182. loader = PackageLoader('mypackage', 'views')
  183. If the package path is not given, ``'templates'`` is assumed.
  184. Per default the template encoding is ``'utf-8'`` which can be changed
  185. by setting the `encoding` parameter to something else. Due to the nature
  186. of eggs it's only possible to reload templates if the package was loaded
  187. from the file system and not a zip file.
  188. """
  189. def __init__(self, package_name, package_path="templates", encoding="utf-8"):
  190. from pkg_resources import DefaultProvider
  191. from pkg_resources import get_provider
  192. from pkg_resources import ResourceManager
  193. provider = get_provider(package_name)
  194. self.encoding = encoding
  195. self.manager = ResourceManager()
  196. self.filesystem_bound = isinstance(provider, DefaultProvider)
  197. self.provider = provider
  198. self.package_path = package_path
  199. def get_source(self, environment, template):
  200. pieces = split_template_path(template)
  201. p = "/".join((self.package_path,) + tuple(pieces))
  202. if not self.provider.has_resource(p):
  203. raise TemplateNotFound(template)
  204. filename = uptodate = None
  205. if self.filesystem_bound:
  206. filename = self.provider.get_resource_filename(self.manager, p)
  207. mtime = path.getmtime(filename)
  208. def uptodate():
  209. try:
  210. return path.getmtime(filename) == mtime
  211. except OSError:
  212. return False
  213. source = self.provider.get_resource_string(self.manager, p)
  214. return source.decode(self.encoding), filename, uptodate
  215. def list_templates(self):
  216. path = self.package_path
  217. if path[:2] == "./":
  218. path = path[2:]
  219. elif path == ".":
  220. path = ""
  221. offset = len(path)
  222. results = []
  223. def _walk(path):
  224. for filename in self.provider.resource_listdir(path):
  225. fullname = path + "/" + filename
  226. if self.provider.resource_isdir(fullname):
  227. _walk(fullname)
  228. else:
  229. results.append(fullname[offset:].lstrip("/"))
  230. _walk(path)
  231. results.sort()
  232. return results
  233. class DictLoader(BaseLoader):
  234. """Loads a template from a python dict. It's passed a dict of unicode
  235. strings bound to template names. This loader is useful for unittesting:
  236. >>> loader = DictLoader({'index.html': 'source here'})
  237. Because auto reloading is rarely useful this is disabled per default.
  238. """
  239. def __init__(self, mapping):
  240. self.mapping = mapping
  241. def get_source(self, environment, template):
  242. if template in self.mapping:
  243. source = self.mapping[template]
  244. return source, None, lambda: source == self.mapping.get(template)
  245. raise TemplateNotFound(template)
  246. def list_templates(self):
  247. return sorted(self.mapping)
  248. class FunctionLoader(BaseLoader):
  249. """A loader that is passed a function which does the loading. The
  250. function receives the name of the template and has to return either
  251. an unicode string with the template source, a tuple in the form ``(source,
  252. filename, uptodatefunc)`` or `None` if the template does not exist.
  253. >>> def load_template(name):
  254. ... if name == 'index.html':
  255. ... return '...'
  256. ...
  257. >>> loader = FunctionLoader(load_template)
  258. The `uptodatefunc` is a function that is called if autoreload is enabled
  259. and has to return `True` if the template is still up to date. For more
  260. details have a look at :meth:`BaseLoader.get_source` which has the same
  261. return value.
  262. """
  263. def __init__(self, load_func):
  264. self.load_func = load_func
  265. def get_source(self, environment, template):
  266. rv = self.load_func(template)
  267. if rv is None:
  268. raise TemplateNotFound(template)
  269. elif isinstance(rv, string_types):
  270. return rv, None, None
  271. return rv
  272. class PrefixLoader(BaseLoader):
  273. """A loader that is passed a dict of loaders where each loader is bound
  274. to a prefix. The prefix is delimited from the template by a slash per
  275. default, which can be changed by setting the `delimiter` argument to
  276. something else::
  277. loader = PrefixLoader({
  278. 'app1': PackageLoader('mypackage.app1'),
  279. 'app2': PackageLoader('mypackage.app2')
  280. })
  281. By loading ``'app1/index.html'`` the file from the app1 package is loaded,
  282. by loading ``'app2/index.html'`` the file from the second.
  283. """
  284. def __init__(self, mapping, delimiter="/"):
  285. self.mapping = mapping
  286. self.delimiter = delimiter
  287. def get_loader(self, template):
  288. try:
  289. prefix, name = template.split(self.delimiter, 1)
  290. loader = self.mapping[prefix]
  291. except (ValueError, KeyError):
  292. raise TemplateNotFound(template)
  293. return loader, name
  294. def get_source(self, environment, template):
  295. loader, name = self.get_loader(template)
  296. try:
  297. return loader.get_source(environment, name)
  298. except TemplateNotFound:
  299. # re-raise the exception with the correct filename here.
  300. # (the one that includes the prefix)
  301. raise TemplateNotFound(template)
  302. @internalcode
  303. def load(self, environment, name, globals=None):
  304. loader, local_name = self.get_loader(name)
  305. try:
  306. return loader.load(environment, local_name, globals)
  307. except TemplateNotFound:
  308. # re-raise the exception with the correct filename here.
  309. # (the one that includes the prefix)
  310. raise TemplateNotFound(name)
  311. def list_templates(self):
  312. result = []
  313. for prefix, loader in iteritems(self.mapping):
  314. for template in loader.list_templates():
  315. result.append(prefix + self.delimiter + template)
  316. return result
  317. class ChoiceLoader(BaseLoader):
  318. """This loader works like the `PrefixLoader` just that no prefix is
  319. specified. If a template could not be found by one loader the next one
  320. is tried.
  321. >>> loader = ChoiceLoader([
  322. ... FileSystemLoader('/path/to/user/templates'),
  323. ... FileSystemLoader('/path/to/system/templates')
  324. ... ])
  325. This is useful if you want to allow users to override builtin templates
  326. from a different location.
  327. """
  328. def __init__(self, loaders):
  329. self.loaders = loaders
  330. def get_source(self, environment, template):
  331. for loader in self.loaders:
  332. try:
  333. return loader.get_source(environment, template)
  334. except TemplateNotFound:
  335. pass
  336. raise TemplateNotFound(template)
  337. @internalcode
  338. def load(self, environment, name, globals=None):
  339. for loader in self.loaders:
  340. try:
  341. return loader.load(environment, name, globals)
  342. except TemplateNotFound:
  343. pass
  344. raise TemplateNotFound(name)
  345. def list_templates(self):
  346. found = set()
  347. for loader in self.loaders:
  348. found.update(loader.list_templates())
  349. return sorted(found)
  350. class _TemplateModule(ModuleType):
  351. """Like a normal module but with support for weak references"""
  352. class ModuleLoader(BaseLoader):
  353. """This loader loads templates from precompiled templates.
  354. Example usage:
  355. >>> loader = ChoiceLoader([
  356. ... ModuleLoader('/path/to/compiled/templates'),
  357. ... FileSystemLoader('/path/to/templates')
  358. ... ])
  359. Templates can be precompiled with :meth:`Environment.compile_templates`.
  360. """
  361. has_source_access = False
  362. def __init__(self, path):
  363. package_name = "_jinja2_module_templates_%x" % id(self)
  364. # create a fake module that looks for the templates in the
  365. # path given.
  366. mod = _TemplateModule(package_name)
  367. if not isinstance(path, abc.Iterable) or isinstance(path, string_types):
  368. path = [path]
  369. mod.__path__ = [fspath(p) for p in path]
  370. sys.modules[package_name] = weakref.proxy(
  371. mod, lambda x: sys.modules.pop(package_name, None)
  372. )
  373. # the only strong reference, the sys.modules entry is weak
  374. # so that the garbage collector can remove it once the
  375. # loader that created it goes out of business.
  376. self.module = mod
  377. self.package_name = package_name
  378. @staticmethod
  379. def get_template_key(name):
  380. return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()
  381. @staticmethod
  382. def get_module_filename(name):
  383. return ModuleLoader.get_template_key(name) + ".py"
  384. @internalcode
  385. def load(self, environment, name, globals=None):
  386. key = self.get_template_key(name)
  387. module = "%s.%s" % (self.package_name, key)
  388. mod = getattr(self.module, module, None)
  389. if mod is None:
  390. try:
  391. mod = __import__(module, None, None, ["root"])
  392. except ImportError:
  393. raise TemplateNotFound(name)
  394. # remove the entry from sys.modules, we only want the attribute
  395. # on the module object we have stored on the loader.
  396. sys.modules.pop(module, None)
  397. return environment.template_class.from_module_dict(
  398. environment, mod.__dict__, globals
  399. )