Debian Codegraph @

third_party/python/Mako/mako/template.py

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