lookup.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361
  1. # mako/lookup.py
  2. # Copyright 2006-2025 the Mako authors and contributors <see AUTHORS file>
  3. #
  4. # This module is part of Mako and is released under
  5. # the MIT License: http://www.opensource.org/licenses/mit-license.php
  6. import os
  7. import posixpath
  8. import re
  9. import stat
  10. import threading
  11. from mako import exceptions
  12. from mako import util
  13. from mako.template import Template
  14. class TemplateCollection:
  15. """Represent a collection of :class:`.Template` objects,
  16. identifiable via URI.
  17. A :class:`.TemplateCollection` is linked to the usage of
  18. all template tags that address other templates, such
  19. as ``<%include>``, ``<%namespace>``, and ``<%inherit>``.
  20. The ``file`` attribute of each of those tags refers
  21. to a string URI that is passed to that :class:`.Template`
  22. object's :class:`.TemplateCollection` for resolution.
  23. :class:`.TemplateCollection` is an abstract class,
  24. with the usual default implementation being :class:`.TemplateLookup`.
  25. """
  26. def has_template(self, uri):
  27. """Return ``True`` if this :class:`.TemplateLookup` is
  28. capable of returning a :class:`.Template` object for the
  29. given ``uri``.
  30. :param uri: String URI of the template to be resolved.
  31. """
  32. try:
  33. self.get_template(uri)
  34. return True
  35. except exceptions.TemplateLookupException:
  36. return False
  37. def get_template(self, uri, relativeto=None):
  38. """Return a :class:`.Template` object corresponding to the given
  39. ``uri``.
  40. The default implementation raises
  41. :class:`.NotImplementedError`. Implementations should
  42. raise :class:`.TemplateLookupException` if the given ``uri``
  43. cannot be resolved.
  44. :param uri: String URI of the template to be resolved.
  45. :param relativeto: if present, the given ``uri`` is assumed to
  46. be relative to this URI.
  47. """
  48. raise NotImplementedError()
  49. def filename_to_uri(self, uri, filename):
  50. """Convert the given ``filename`` to a URI relative to
  51. this :class:`.TemplateCollection`."""
  52. return uri
  53. def adjust_uri(self, uri, filename):
  54. """Adjust the given ``uri`` based on the calling ``filename``.
  55. When this method is called from the runtime, the
  56. ``filename`` parameter is taken directly to the ``filename``
  57. attribute of the calling template. Therefore a custom
  58. :class:`.TemplateCollection` subclass can place any string
  59. identifier desired in the ``filename`` parameter of the
  60. :class:`.Template` objects it constructs and have them come back
  61. here.
  62. """
  63. return uri
  64. class TemplateLookup(TemplateCollection):
  65. """Represent a collection of templates that locates template source files
  66. from the local filesystem.
  67. The primary argument is the ``directories`` argument, the list of
  68. directories to search:
  69. .. sourcecode:: python
  70. lookup = TemplateLookup(["/path/to/templates"])
  71. some_template = lookup.get_template("/index.html")
  72. The :class:`.TemplateLookup` can also be given :class:`.Template` objects
  73. programatically using :meth:`.put_string` or :meth:`.put_template`:
  74. .. sourcecode:: python
  75. lookup = TemplateLookup()
  76. lookup.put_string("base.html", '''
  77. <html><body>${self.next()}</body></html>
  78. ''')
  79. lookup.put_string("hello.html", '''
  80. <%include file='base.html'/>
  81. Hello, world !
  82. ''')
  83. :param directories: A list of directory names which will be
  84. searched for a particular template URI. The URI is appended
  85. to each directory and the filesystem checked.
  86. :param collection_size: Approximate size of the collection used
  87. to store templates. If left at its default of ``-1``, the size
  88. is unbounded, and a plain Python dictionary is used to
  89. relate URI strings to :class:`.Template` instances.
  90. Otherwise, a least-recently-used cache object is used which
  91. will maintain the size of the collection approximately to
  92. the number given.
  93. :param filesystem_checks: When at its default value of ``True``,
  94. each call to :meth:`.TemplateLookup.get_template()` will
  95. compare the filesystem last modified time to the time in
  96. which an existing :class:`.Template` object was created.
  97. This allows the :class:`.TemplateLookup` to regenerate a
  98. new :class:`.Template` whenever the original source has
  99. been updated. Set this to ``False`` for a very minor
  100. performance increase.
  101. :param modulename_callable: A callable which, when present,
  102. is passed the path of the source file as well as the
  103. requested URI, and then returns the full path of the
  104. generated Python module file. This is used to inject
  105. alternate schemes for Python module location. If left at
  106. its default of ``None``, the built in system of generation
  107. based on ``module_directory`` plus ``uri`` is used.
  108. All other keyword parameters available for
  109. :class:`.Template` are mirrored here. When new
  110. :class:`.Template` objects are created, the keywords
  111. established with this :class:`.TemplateLookup` are passed on
  112. to each new :class:`.Template`.
  113. """
  114. def __init__(
  115. self,
  116. directories=None,
  117. module_directory=None,
  118. filesystem_checks=True,
  119. collection_size=-1,
  120. format_exceptions=False,
  121. error_handler=None,
  122. output_encoding=None,
  123. encoding_errors="strict",
  124. cache_args=None,
  125. cache_impl="beaker",
  126. cache_enabled=True,
  127. cache_type=None,
  128. cache_dir=None,
  129. cache_url=None,
  130. modulename_callable=None,
  131. module_writer=None,
  132. default_filters=None,
  133. buffer_filters=(),
  134. strict_undefined=False,
  135. imports=None,
  136. future_imports=None,
  137. enable_loop=True,
  138. input_encoding=None,
  139. preprocessor=None,
  140. lexer_cls=None,
  141. include_error_handler=None,
  142. ):
  143. self.directories = [
  144. posixpath.normpath(d) for d in util.to_list(directories, ())
  145. ]
  146. self.module_directory = module_directory
  147. self.modulename_callable = modulename_callable
  148. self.filesystem_checks = filesystem_checks
  149. self.collection_size = collection_size
  150. if cache_args is None:
  151. cache_args = {}
  152. # transfer deprecated cache_* args
  153. if cache_dir:
  154. cache_args.setdefault("dir", cache_dir)
  155. if cache_url:
  156. cache_args.setdefault("url", cache_url)
  157. if cache_type:
  158. cache_args.setdefault("type", cache_type)
  159. self.template_args = {
  160. "format_exceptions": format_exceptions,
  161. "error_handler": error_handler,
  162. "include_error_handler": include_error_handler,
  163. "output_encoding": output_encoding,
  164. "cache_impl": cache_impl,
  165. "encoding_errors": encoding_errors,
  166. "input_encoding": input_encoding,
  167. "module_directory": module_directory,
  168. "module_writer": module_writer,
  169. "cache_args": cache_args,
  170. "cache_enabled": cache_enabled,
  171. "default_filters": default_filters,
  172. "buffer_filters": buffer_filters,
  173. "strict_undefined": strict_undefined,
  174. "imports": imports,
  175. "future_imports": future_imports,
  176. "enable_loop": enable_loop,
  177. "preprocessor": preprocessor,
  178. "lexer_cls": lexer_cls,
  179. }
  180. if collection_size == -1:
  181. self._collection = {}
  182. self._uri_cache = {}
  183. else:
  184. self._collection = util.LRUCache(collection_size)
  185. self._uri_cache = util.LRUCache(collection_size)
  186. self._mutex = threading.Lock()
  187. def get_template(self, uri):
  188. """Return a :class:`.Template` object corresponding to the given
  189. ``uri``.
  190. .. note:: The ``relativeto`` argument is not supported here at
  191. the moment.
  192. """
  193. try:
  194. if self.filesystem_checks:
  195. return self._check(uri, self._collection[uri])
  196. else:
  197. return self._collection[uri]
  198. except KeyError as e:
  199. u = re.sub(r"^\/+", "", uri)
  200. for dir_ in self.directories:
  201. # make sure the path seperators are posix - os.altsep is empty
  202. # on POSIX and cannot be used.
  203. dir_ = dir_.replace(os.path.sep, posixpath.sep)
  204. srcfile = posixpath.normpath(posixpath.join(dir_, u))
  205. if os.path.isfile(srcfile):
  206. return self._load(srcfile, uri)
  207. else:
  208. raise exceptions.TopLevelLookupException(
  209. "Can't locate template for uri %r" % uri
  210. ) from e
  211. def adjust_uri(self, uri, relativeto):
  212. """Adjust the given ``uri`` based on the given relative URI."""
  213. key = (uri, relativeto)
  214. if key in self._uri_cache:
  215. return self._uri_cache[key]
  216. if uri[0] == "/":
  217. v = self._uri_cache[key] = uri
  218. elif relativeto is not None:
  219. v = self._uri_cache[key] = posixpath.join(
  220. posixpath.dirname(relativeto), uri
  221. )
  222. else:
  223. v = self._uri_cache[key] = "/" + uri
  224. return v
  225. def filename_to_uri(self, filename):
  226. """Convert the given ``filename`` to a URI relative to
  227. this :class:`.TemplateCollection`."""
  228. try:
  229. return self._uri_cache[filename]
  230. except KeyError:
  231. value = self._relativeize(filename)
  232. self._uri_cache[filename] = value
  233. return value
  234. def _relativeize(self, filename):
  235. """Return the portion of a filename that is 'relative'
  236. to the directories in this lookup.
  237. """
  238. filename = posixpath.normpath(filename)
  239. for dir_ in self.directories:
  240. if filename[0 : len(dir_)] == dir_:
  241. return filename[len(dir_) :]
  242. else:
  243. return None
  244. def _load(self, filename, uri):
  245. self._mutex.acquire()
  246. try:
  247. try:
  248. # try returning from collection one
  249. # more time in case concurrent thread already loaded
  250. return self._collection[uri]
  251. except KeyError:
  252. pass
  253. try:
  254. if self.modulename_callable is not None:
  255. module_filename = self.modulename_callable(filename, uri)
  256. else:
  257. module_filename = None
  258. self._collection[uri] = template = Template(
  259. uri=uri,
  260. filename=posixpath.normpath(filename),
  261. lookup=self,
  262. module_filename=module_filename,
  263. **self.template_args,
  264. )
  265. return template
  266. except:
  267. # if compilation fails etc, ensure
  268. # template is removed from collection,
  269. # re-raise
  270. self._collection.pop(uri, None)
  271. raise
  272. finally:
  273. self._mutex.release()
  274. def _check(self, uri, template):
  275. if template.filename is None:
  276. return template
  277. try:
  278. template_stat = os.stat(template.filename)
  279. if template.module._modified_time >= template_stat[stat.ST_MTIME]:
  280. return template
  281. self._collection.pop(uri, None)
  282. return self._load(template.filename, uri)
  283. except OSError as e:
  284. self._collection.pop(uri, None)
  285. raise exceptions.TemplateLookupException(
  286. "Can't locate template for uri %r" % uri
  287. ) from e
  288. def put_string(self, uri, text):
  289. """Place a new :class:`.Template` object into this
  290. :class:`.TemplateLookup`, based on the given string of
  291. ``text``.
  292. """
  293. self._collection[uri] = Template(
  294. text, lookup=self, uri=uri, **self.template_args
  295. )
  296. def put_template(self, uri, template):
  297. """Place a new :class:`.Template` object into this
  298. :class:`.TemplateLookup`, based on the given
  299. :class:`.Template` object.
  300. """
  301. self._collection[uri] = template