loaders.py 17 KB

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