template.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. # mako/template.py
  2. # Copyright (C) 2006-2012 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. """Provides the Template class, a facade for parsing, generating and executing
  7. template strings, as well as template runtime operations."""
  8. from mako.lexer import Lexer
  9. from mako import runtime, util, exceptions, codegen, cache, compat
  10. import os
  11. import re
  12. import shutil
  13. import stat
  14. import sys
  15. import tempfile
  16. import types
  17. import weakref
  18. class Template(object):
  19. """Represents a compiled template.
  20. :class:`.Template` includes a reference to the original
  21. template source (via the :attr:`.source` attribute)
  22. as well as the source code of the
  23. generated Python module (i.e. the :attr:`.code` attribute),
  24. as well as a reference to an actual Python module.
  25. :class:`.Template` is constructed using either a literal string
  26. representing the template text, or a filename representing a filesystem
  27. path to a source file.
  28. :param text: textual template source. This argument is mutually
  29. exclusive versus the ``filename`` parameter.
  30. :param filename: filename of the source template. This argument is
  31. mutually exclusive versus the ``text`` parameter.
  32. :param buffer_filters: string list of filters to be applied
  33. to the output of ``%def``\ s which are buffered, cached, or otherwise
  34. filtered, after all filters
  35. defined with the ``%def`` itself have been applied. Allows the
  36. creation of default expression filters that let the output
  37. of return-valued ``%def``\ s "opt out" of that filtering via
  38. passing special attributes or objects.
  39. :param bytestring_passthrough: When ``True``, and ``output_encoding`` is
  40. set to ``None``, and :meth:`.Template.render` is used to render,
  41. the `StringIO` or `cStringIO` buffer will be used instead of the
  42. default "fast" buffer. This allows raw bytestrings in the
  43. output stream, such as in expressions, to pass straight
  44. through to the buffer. This flag is forced
  45. to ``True`` if ``disable_unicode`` is also configured.
  46. .. versionadded:: 0.4
  47. Added to provide the same behavior as that of the previous series.
  48. :param cache_args: Dictionary of cache configuration arguments that
  49. will be passed to the :class:`.CacheImpl`. See :ref:`caching_toplevel`.
  50. :param cache_dir:
  51. .. deprecated:: 0.6
  52. Use the ``'dir'`` argument in the ``cache_args`` dictionary.
  53. See :ref:`caching_toplevel`.
  54. :param cache_enabled: Boolean flag which enables caching of this
  55. template. See :ref:`caching_toplevel`.
  56. :param cache_impl: String name of a :class:`.CacheImpl` caching
  57. implementation to use. Defaults to ``'beaker'``.
  58. :param cache_type:
  59. .. deprecated:: 0.6
  60. Use the ``'type'`` argument in the ``cache_args`` dictionary.
  61. See :ref:`caching_toplevel`.
  62. :param cache_url:
  63. .. deprecated:: 0.6
  64. Use the ``'url'`` argument in the ``cache_args`` dictionary.
  65. See :ref:`caching_toplevel`.
  66. :param default_filters: List of string filter names that will
  67. be applied to all expressions. See :ref:`filtering_default_filters`.
  68. :param disable_unicode: Disables all awareness of Python Unicode
  69. objects. See :ref:`unicode_disabled`.
  70. :param enable_loop: When ``True``, enable the ``loop`` context variable.
  71. This can be set to ``False`` to support templates that may
  72. be making usage of the name "``loop``". Individual templates can
  73. re-enable the "loop" context by placing the directive
  74. ``enable_loop="True"`` inside the ``<%page>`` tag -- see
  75. :ref:`migrating_loop`.
  76. :param encoding_errors: Error parameter passed to ``encode()`` when
  77. string encoding is performed. See :ref:`usage_unicode`.
  78. :param error_handler: Python callable which is called whenever
  79. compile or runtime exceptions occur. The callable is passed
  80. the current context as well as the exception. If the
  81. callable returns ``True``, the exception is considered to
  82. be handled, else it is re-raised after the function
  83. completes. Is used to provide custom error-rendering
  84. functions.
  85. :param format_exceptions: if ``True``, exceptions which occur during
  86. the render phase of this template will be caught and
  87. formatted into an HTML error page, which then becomes the
  88. rendered result of the :meth:`.render` call. Otherwise,
  89. runtime exceptions are propagated outwards.
  90. :param imports: String list of Python statements, typically individual
  91. "import" lines, which will be placed into the module level
  92. preamble of all generated Python modules. See the example
  93. in :ref:`filtering_default_filters`.
  94. :param future_imports: String list of names to import from `__future__`.
  95. These will be concatenated into a comma-separated string and inserted
  96. into the beginning of the template, e.g. ``futures_imports=['FOO',
  97. 'BAR']`` results in ``from __future__ import FOO, BAR``. If you're
  98. interested in using features like the new division operator, you must
  99. use future_imports to convey that to the renderer, as otherwise the
  100. import will not appear as the first executed statement in the generated
  101. code and will therefore not have the desired effect.
  102. :param input_encoding: Encoding of the template's source code. Can
  103. be used in lieu of the coding comment. See
  104. :ref:`usage_unicode` as well as :ref:`unicode_toplevel` for
  105. details on source encoding.
  106. :param lookup: a :class:`.TemplateLookup` instance that will be used
  107. for all file lookups via the ``<%namespace>``,
  108. ``<%include>``, and ``<%inherit>`` tags. See
  109. :ref:`usage_templatelookup`.
  110. :param module_directory: Filesystem location where generated
  111. Python module files will be placed.
  112. :param module_filename: Overrides the filename of the generated
  113. Python module file. For advanced usage only.
  114. :param module_writer: A callable which overrides how the Python
  115. module is written entirely. The callable is passed the
  116. encoded source content of the module and the destination
  117. path to be written to. The default behavior of module writing
  118. uses a tempfile in conjunction with a file move in order
  119. to make the operation atomic. So a user-defined module
  120. writing function that mimics the default behavior would be:
  121. .. sourcecode:: python
  122. import tempfile
  123. import os
  124. import shutil
  125. def module_writer(source, outputpath):
  126. (dest, name) = \\
  127. tempfile.mkstemp(
  128. dir=os.path.dirname(outputpath)
  129. )
  130. os.write(dest, source)
  131. os.close(dest)
  132. shutil.move(name, outputpath)
  133. from mako.template import Template
  134. mytemplate = Template(
  135. filename="index.html",
  136. module_directory="/path/to/modules",
  137. module_writer=module_writer
  138. )
  139. The function is provided for unusual configurations where
  140. certain platform-specific permissions or other special
  141. steps are needed.
  142. :param output_encoding: The encoding to use when :meth:`.render`
  143. is called.
  144. See :ref:`usage_unicode` as well as :ref:`unicode_toplevel`.
  145. :param preprocessor: Python callable which will be passed
  146. the full template source before it is parsed. The return
  147. result of the callable will be used as the template source
  148. code.
  149. :param lexer_cls: A :class:`.Lexer` class used to parse
  150. the template. The :class:`.Lexer` class is used by
  151. default.
  152. .. versionadded:: 0.7.4
  153. :param strict_undefined: Replaces the automatic usage of
  154. ``UNDEFINED`` for any undeclared variables not located in
  155. the :class:`.Context` with an immediate raise of
  156. ``NameError``. The advantage is immediate reporting of
  157. missing variables which include the name.
  158. .. versionadded:: 0.3.6
  159. :param uri: string URI or other identifier for this template.
  160. If not provided, the ``uri`` is generated from the filesystem
  161. path, or from the in-memory identity of a non-file-based
  162. template. The primary usage of the ``uri`` is to provide a key
  163. within :class:`.TemplateLookup`, as well as to generate the
  164. file path of the generated Python module file, if
  165. ``module_directory`` is specified.
  166. """
  167. lexer_cls = Lexer
  168. def __init__(self,
  169. text=None,
  170. filename=None,
  171. uri=None,
  172. format_exceptions=False,
  173. error_handler=None,
  174. lookup=None,
  175. output_encoding=None,
  176. encoding_errors='strict',
  177. module_directory=None,
  178. cache_args=None,
  179. cache_impl='beaker',
  180. cache_enabled=True,
  181. cache_type=None,
  182. cache_dir=None,
  183. cache_url=None,
  184. module_filename=None,
  185. input_encoding=None,
  186. disable_unicode=False,
  187. module_writer=None,
  188. bytestring_passthrough=False,
  189. default_filters=None,
  190. buffer_filters=(),
  191. strict_undefined=False,
  192. imports=None,
  193. future_imports=None,
  194. enable_loop=True,
  195. preprocessor=None,
  196. lexer_cls=None):
  197. if uri:
  198. self.module_id = re.sub(r'\W', "_", uri)
  199. self.uri = uri
  200. elif filename:
  201. self.module_id = re.sub(r'\W', "_", filename)
  202. drive, path = os.path.splitdrive(filename)
  203. path = os.path.normpath(path).replace(os.path.sep, "/")
  204. self.uri = path
  205. else:
  206. self.module_id = "memory:" + hex(id(self))
  207. self.uri = self.module_id
  208. u_norm = self.uri
  209. if u_norm.startswith("/"):
  210. u_norm = u_norm[1:]
  211. u_norm = os.path.normpath(u_norm)
  212. if u_norm.startswith(".."):
  213. raise exceptions.TemplateLookupException(
  214. "Template uri \"%s\" is invalid - "
  215. "it cannot be relative outside "
  216. "of the root path." % self.uri)
  217. self.input_encoding = input_encoding
  218. self.output_encoding = output_encoding
  219. self.encoding_errors = encoding_errors
  220. self.disable_unicode = disable_unicode
  221. self.bytestring_passthrough = bytestring_passthrough or disable_unicode
  222. self.enable_loop = enable_loop
  223. self.strict_undefined = strict_undefined
  224. self.module_writer = module_writer
  225. if compat.py3k and disable_unicode:
  226. raise exceptions.UnsupportedError(
  227. "Mako for Python 3 does not "
  228. "support disabling Unicode")
  229. elif output_encoding and disable_unicode:
  230. raise exceptions.UnsupportedError(
  231. "output_encoding must be set to "
  232. "None when disable_unicode is used.")
  233. if default_filters is None:
  234. if compat.py3k or self.disable_unicode:
  235. self.default_filters = ['str']
  236. else:
  237. self.default_filters = ['unicode']
  238. else:
  239. self.default_filters = default_filters
  240. self.buffer_filters = buffer_filters
  241. self.imports = imports
  242. self.future_imports = future_imports
  243. self.preprocessor = preprocessor
  244. if lexer_cls is not None:
  245. self.lexer_cls = lexer_cls
  246. # if plain text, compile code in memory only
  247. if text is not None:
  248. (code, module) = _compile_text(self, text, filename)
  249. self._code = code
  250. self._source = text
  251. ModuleInfo(module, None, self, filename, code, text)
  252. elif filename is not None:
  253. # if template filename and a module directory, load
  254. # a filesystem-based module file, generating if needed
  255. if module_filename is not None:
  256. path = module_filename
  257. elif module_directory is not None:
  258. path = os.path.abspath(
  259. os.path.join(
  260. os.path.normpath(module_directory),
  261. u_norm + ".py"
  262. )
  263. )
  264. else:
  265. path = None
  266. module = self._compile_from_file(path, filename)
  267. else:
  268. raise exceptions.RuntimeException(
  269. "Template requires text or filename")
  270. self.module = module
  271. self.filename = filename
  272. self.callable_ = self.module.render_body
  273. self.format_exceptions = format_exceptions
  274. self.error_handler = error_handler
  275. self.lookup = lookup
  276. self.module_directory = module_directory
  277. self._setup_cache_args(
  278. cache_impl, cache_enabled, cache_args,
  279. cache_type, cache_dir, cache_url
  280. )
  281. @util.memoized_property
  282. def reserved_names(self):
  283. if self.enable_loop:
  284. return codegen.RESERVED_NAMES
  285. else:
  286. return codegen.RESERVED_NAMES.difference(['loop'])
  287. def _setup_cache_args(self,
  288. cache_impl, cache_enabled, cache_args,
  289. cache_type, cache_dir, cache_url):
  290. self.cache_impl = cache_impl
  291. self.cache_enabled = cache_enabled
  292. if cache_args:
  293. self.cache_args = cache_args
  294. else:
  295. self.cache_args = {}
  296. # transfer deprecated cache_* args
  297. if cache_type:
  298. self.cache_args['type'] = cache_type
  299. if cache_dir:
  300. self.cache_args['dir'] = cache_dir
  301. if cache_url:
  302. self.cache_args['url'] = cache_url
  303. def _compile_from_file(self, path, filename):
  304. if path is not None:
  305. util.verify_directory(os.path.dirname(path))
  306. filemtime = os.stat(filename)[stat.ST_MTIME]
  307. if not os.path.exists(path) or \
  308. os.stat(path)[stat.ST_MTIME] < filemtime:
  309. data = util.read_file(filename)
  310. _compile_module_file(
  311. self,
  312. data,
  313. filename,
  314. path,
  315. self.module_writer)
  316. module = compat.load_module(self.module_id, path)
  317. del sys.modules[self.module_id]
  318. if module._magic_number != codegen.MAGIC_NUMBER:
  319. data = util.read_file(filename)
  320. _compile_module_file(
  321. self,
  322. data,
  323. filename,
  324. path,
  325. self.module_writer)
  326. module = compat.load_module(self.module_id, path)
  327. del sys.modules[self.module_id]
  328. ModuleInfo(module, path, self, filename, None, None)
  329. else:
  330. # template filename and no module directory, compile code
  331. # in memory
  332. data = util.read_file(filename)
  333. code, module = _compile_text(
  334. self,
  335. data,
  336. filename)
  337. self._source = None
  338. self._code = code
  339. ModuleInfo(module, None, self, filename, code, None)
  340. return module
  341. @property
  342. def source(self):
  343. """Return the template source code for this :class:`.Template`."""
  344. return _get_module_info_from_callable(self.callable_).source
  345. @property
  346. def code(self):
  347. """Return the module source code for this :class:`.Template`."""
  348. return _get_module_info_from_callable(self.callable_).code
  349. @util.memoized_property
  350. def cache(self):
  351. return cache.Cache(self)
  352. @property
  353. def cache_dir(self):
  354. return self.cache_args['dir']
  355. @property
  356. def cache_url(self):
  357. return self.cache_args['url']
  358. @property
  359. def cache_type(self):
  360. return self.cache_args['type']
  361. def render(self, *args, **data):
  362. """Render the output of this template as a string.
  363. If the template specifies an output encoding, the string
  364. will be encoded accordingly, else the output is raw (raw
  365. output uses `cStringIO` and can't handle multibyte
  366. characters). A :class:`.Context` object is created corresponding
  367. to the given data. Arguments that are explicitly declared
  368. by this template's internal rendering method are also
  369. pulled from the given ``*args``, ``**data`` members.
  370. """
  371. return runtime._render(self, self.callable_, args, data)
  372. def render_unicode(self, *args, **data):
  373. """Render the output of this template as a unicode object."""
  374. return runtime._render(self,
  375. self.callable_,
  376. args,
  377. data,
  378. as_unicode=True)
  379. def render_context(self, context, *args, **kwargs):
  380. """Render this :class:`.Template` with the given context.
  381. The data is written to the context's buffer.
  382. """
  383. if getattr(context, '_with_template', None) is None:
  384. context._set_with_template(self)
  385. runtime._render_context(self,
  386. self.callable_,
  387. context,
  388. *args,
  389. **kwargs)
  390. def has_def(self, name):
  391. return hasattr(self.module, "render_%s" % name)
  392. def get_def(self, name):
  393. """Return a def of this template as a :class:`.DefTemplate`."""
  394. return DefTemplate(self, getattr(self.module, "render_%s" % name))
  395. def _get_def_callable(self, name):
  396. return getattr(self.module, "render_%s" % name)
  397. @property
  398. def last_modified(self):
  399. return self.module._modified_time
  400. class ModuleTemplate(Template):
  401. """A Template which is constructed given an existing Python module.
  402. e.g.::
  403. t = Template("this is a template")
  404. f = file("mymodule.py", "w")
  405. f.write(t.code)
  406. f.close()
  407. import mymodule
  408. t = ModuleTemplate(mymodule)
  409. print t.render()
  410. """
  411. def __init__(self, module,
  412. module_filename=None,
  413. template=None,
  414. template_filename=None,
  415. module_source=None,
  416. template_source=None,
  417. output_encoding=None,
  418. encoding_errors='strict',
  419. disable_unicode=False,
  420. bytestring_passthrough=False,
  421. format_exceptions=False,
  422. error_handler=None,
  423. lookup=None,
  424. cache_args=None,
  425. cache_impl='beaker',
  426. cache_enabled=True,
  427. cache_type=None,
  428. cache_dir=None,
  429. cache_url=None,
  430. ):
  431. self.module_id = re.sub(r'\W', "_", module._template_uri)
  432. self.uri = module._template_uri
  433. self.input_encoding = module._source_encoding
  434. self.output_encoding = output_encoding
  435. self.encoding_errors = encoding_errors
  436. self.disable_unicode = disable_unicode
  437. self.bytestring_passthrough = bytestring_passthrough or disable_unicode
  438. self.enable_loop = module._enable_loop
  439. if compat.py3k and disable_unicode:
  440. raise exceptions.UnsupportedError(
  441. "Mako for Python 3 does not "
  442. "support disabling Unicode")
  443. elif output_encoding and disable_unicode:
  444. raise exceptions.UnsupportedError(
  445. "output_encoding must be set to "
  446. "None when disable_unicode is used.")
  447. self.module = module
  448. self.filename = template_filename
  449. ModuleInfo(module,
  450. module_filename,
  451. self,
  452. template_filename,
  453. module_source,
  454. template_source)
  455. self.callable_ = self.module.render_body
  456. self.format_exceptions = format_exceptions
  457. self.error_handler = error_handler
  458. self.lookup = lookup
  459. self._setup_cache_args(
  460. cache_impl, cache_enabled, cache_args,
  461. cache_type, cache_dir, cache_url
  462. )
  463. class DefTemplate(Template):
  464. """A :class:`.Template` which represents a callable def in a parent
  465. template."""
  466. def __init__(self, parent, callable_):
  467. self.parent = parent
  468. self.callable_ = callable_
  469. self.output_encoding = parent.output_encoding
  470. self.module = parent.module
  471. self.encoding_errors = parent.encoding_errors
  472. self.format_exceptions = parent.format_exceptions
  473. self.error_handler = parent.error_handler
  474. self.enable_loop = parent.enable_loop
  475. self.lookup = parent.lookup
  476. self.bytestring_passthrough = parent.bytestring_passthrough
  477. def get_def(self, name):
  478. return self.parent.get_def(name)
  479. class ModuleInfo(object):
  480. """Stores information about a module currently loaded into
  481. memory, provides reverse lookups of template source, module
  482. source code based on a module's identifier.
  483. """
  484. _modules = weakref.WeakValueDictionary()
  485. def __init__(self,
  486. module,
  487. module_filename,
  488. template,
  489. template_filename,
  490. module_source,
  491. template_source):
  492. self.module = module
  493. self.module_filename = module_filename
  494. self.template_filename = template_filename
  495. self.module_source = module_source
  496. self.template_source = template_source
  497. self._modules[module.__name__] = template._mmarker = self
  498. if module_filename:
  499. self._modules[module_filename] = self
  500. @property
  501. def code(self):
  502. if self.module_source is not None:
  503. return self.module_source
  504. else:
  505. return util.read_python_file(self.module_filename)
  506. @property
  507. def source(self):
  508. if self.template_source is not None:
  509. if self.module._source_encoding and \
  510. not isinstance(self.template_source, compat.text_type):
  511. return self.template_source.decode(
  512. self.module._source_encoding)
  513. else:
  514. return self.template_source
  515. else:
  516. data = util.read_file(self.template_filename)
  517. if self.module._source_encoding:
  518. return data.decode(self.module._source_encoding)
  519. else:
  520. return data
  521. def _compile(template, text, filename, generate_magic_comment):
  522. lexer = template.lexer_cls(text,
  523. filename,
  524. disable_unicode=template.disable_unicode,
  525. input_encoding=template.input_encoding,
  526. preprocessor=template.preprocessor)
  527. node = lexer.parse()
  528. source = codegen.compile(node,
  529. template.uri,
  530. filename,
  531. default_filters=template.default_filters,
  532. buffer_filters=template.buffer_filters,
  533. imports=template.imports,
  534. future_imports=template.future_imports,
  535. source_encoding=lexer.encoding,
  536. generate_magic_comment=generate_magic_comment,
  537. disable_unicode=template.disable_unicode,
  538. strict_undefined=template.strict_undefined,
  539. enable_loop=template.enable_loop,
  540. reserved_names=template.reserved_names)
  541. return source, lexer
  542. def _compile_text(template, text, filename):
  543. identifier = template.module_id
  544. source, lexer = _compile(template, text, filename,
  545. generate_magic_comment=template.disable_unicode)
  546. cid = identifier
  547. if not compat.py3k and isinstance(cid, compat.text_type):
  548. cid = cid.encode()
  549. module = types.ModuleType(cid)
  550. code = compile(source, cid, 'exec')
  551. # this exec() works for 2.4->3.3.
  552. exec(code, module.__dict__, module.__dict__)
  553. return (source, module)
  554. def _compile_module_file(template, text, filename, outputpath, module_writer):
  555. source, lexer = _compile(template, text, filename,
  556. generate_magic_comment=True)
  557. if isinstance(source, compat.text_type):
  558. source = source.encode(lexer.encoding or 'ascii')
  559. if module_writer:
  560. module_writer(source, outputpath)
  561. else:
  562. # make tempfiles in the same location as the ultimate
  563. # location. this ensures they're on the same filesystem,
  564. # avoiding synchronization issues.
  565. (dest, name) = tempfile.mkstemp(dir=os.path.dirname(outputpath))
  566. os.write(dest, source)
  567. os.close(dest)
  568. shutil.move(name, outputpath)
  569. def _get_module_info_from_callable(callable_):
  570. if compat.py3k:
  571. return _get_module_info(callable_.__globals__['__name__'])
  572. else:
  573. return _get_module_info(callable_.func_globals['__name__'])
  574. def _get_module_info(filename):
  575. return ModuleInfo._modules[filename]