You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1276 lines
50 KiB

4 years ago
  1. # -*- coding: utf-8 -*-
  2. """
  3. jinja2.environment
  4. ~~~~~~~~~~~~~~~~~~
  5. Provides a class that holds runtime and parsing time options.
  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 functools import reduce, partial
  13. from jinja2 import nodes
  14. from jinja2.defaults import BLOCK_START_STRING, \
  15. BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \
  16. COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \
  17. LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \
  18. DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE, \
  19. DEFAULT_POLICIES, KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS
  20. from jinja2.lexer import get_lexer, TokenStream
  21. from jinja2.parser import Parser
  22. from jinja2.nodes import EvalContext
  23. from jinja2.compiler import generate, CodeGenerator
  24. from jinja2.runtime import Undefined, new_context, Context
  25. from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \
  26. TemplatesNotFound, TemplateRuntimeError
  27. from jinja2.utils import import_string, LRUCache, Markup, missing, \
  28. concat, consume, internalcode, have_async_gen
  29. from jinja2._compat import imap, ifilter, string_types, iteritems, \
  30. text_type, reraise, implements_iterator, implements_to_string, \
  31. encode_filename, PY2, PYPY
  32. # for direct template usage we have up to ten living environments
  33. _spontaneous_environments = LRUCache(10)
  34. # the function to create jinja traceback objects. This is dynamically
  35. # imported on the first exception in the exception handler.
  36. _make_traceback = None
  37. def get_spontaneous_environment(*args):
  38. """Return a new spontaneous environment. A spontaneous environment is an
  39. unnamed and unaccessible (in theory) environment that is used for
  40. templates generated from a string and not from the file system.
  41. """
  42. try:
  43. env = _spontaneous_environments.get(args)
  44. except TypeError:
  45. return Environment(*args)
  46. if env is not None:
  47. return env
  48. _spontaneous_environments[args] = env = Environment(*args)
  49. env.shared = True
  50. return env
  51. def create_cache(size):
  52. """Return the cache class for the given size."""
  53. if size == 0:
  54. return None
  55. if size < 0:
  56. return {}
  57. return LRUCache(size)
  58. def copy_cache(cache):
  59. """Create an empty copy of the given cache."""
  60. if cache is None:
  61. return None
  62. elif type(cache) is dict:
  63. return {}
  64. return LRUCache(cache.capacity)
  65. def load_extensions(environment, extensions):
  66. """Load the extensions from the list and bind it to the environment.
  67. Returns a dict of instantiated environments.
  68. """
  69. result = {}
  70. for extension in extensions:
  71. if isinstance(extension, string_types):
  72. extension = import_string(extension)
  73. result[extension.identifier] = extension(environment)
  74. return result
  75. def fail_for_missing_callable(string, name):
  76. msg = string % name
  77. if isinstance(name, Undefined):
  78. try:
  79. name._fail_with_undefined_error()
  80. except Exception as e:
  81. msg = '%s (%s; did you forget to quote the callable name?)' % (msg, e)
  82. raise TemplateRuntimeError(msg)
  83. def _environment_sanity_check(environment):
  84. """Perform a sanity check on the environment."""
  85. assert issubclass(environment.undefined, Undefined), 'undefined must ' \
  86. 'be a subclass of undefined because filters depend on it.'
  87. assert environment.block_start_string != \
  88. environment.variable_start_string != \
  89. environment.comment_start_string, 'block, variable and comment ' \
  90. 'start strings must be different'
  91. assert environment.newline_sequence in ('\r', '\r\n', '\n'), \
  92. 'newline_sequence set to unknown line ending string.'
  93. return environment
  94. class Environment(object):
  95. r"""The core component of Jinja is the `Environment`. It contains
  96. important shared variables like configuration, filters, tests,
  97. globals and others. Instances of this class may be modified if
  98. they are not shared and if no template was loaded so far.
  99. Modifications on environments after the first template was loaded
  100. will lead to surprising effects and undefined behavior.
  101. Here are the possible initialization parameters:
  102. `block_start_string`
  103. The string marking the beginning of a block. Defaults to ``'{%'``.
  104. `block_end_string`
  105. The string marking the end of a block. Defaults to ``'%}'``.
  106. `variable_start_string`
  107. The string marking the beginning of a print statement.
  108. Defaults to ``'{{'``.
  109. `variable_end_string`
  110. The string marking the end of a print statement. Defaults to
  111. ``'}}'``.
  112. `comment_start_string`
  113. The string marking the beginning of a comment. Defaults to ``'{#'``.
  114. `comment_end_string`
  115. The string marking the end of a comment. Defaults to ``'#}'``.
  116. `line_statement_prefix`
  117. If given and a string, this will be used as prefix for line based
  118. statements. See also :ref:`line-statements`.
  119. `line_comment_prefix`
  120. If given and a string, this will be used as prefix for line based
  121. comments. See also :ref:`line-statements`.
  122. .. versionadded:: 2.2
  123. `trim_blocks`
  124. If this is set to ``True`` the first newline after a block is
  125. removed (block, not variable tag!). Defaults to `False`.
  126. `lstrip_blocks`
  127. If this is set to ``True`` leading spaces and tabs are stripped
  128. from the start of a line to a block. Defaults to `False`.
  129. `newline_sequence`
  130. The sequence that starts a newline. Must be one of ``'\r'``,
  131. ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a
  132. useful default for Linux and OS X systems as well as web
  133. applications.
  134. `keep_trailing_newline`
  135. Preserve the trailing newline when rendering templates.
  136. The default is ``False``, which causes a single newline,
  137. if present, to be stripped from the end of the template.
  138. .. versionadded:: 2.7
  139. `extensions`
  140. List of Jinja extensions to use. This can either be import paths
  141. as strings or extension classes. For more information have a
  142. look at :ref:`the extensions documentation <jinja-extensions>`.
  143. `optimized`
  144. should the optimizer be enabled? Default is ``True``.
  145. `undefined`
  146. :class:`Undefined` or a subclass of it that is used to represent
  147. undefined values in the template.
  148. `finalize`
  149. A callable that can be used to process the result of a variable
  150. expression before it is output. For example one can convert
  151. ``None`` implicitly into an empty string here.
  152. `autoescape`
  153. If set to ``True`` the XML/HTML autoescaping feature is enabled by
  154. default. For more details about autoescaping see
  155. :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also
  156. be a callable that is passed the template name and has to
  157. return ``True`` or ``False`` depending on autoescape should be
  158. enabled by default.
  159. .. versionchanged:: 2.4
  160. `autoescape` can now be a function
  161. `loader`
  162. The template loader for this environment.
  163. `cache_size`
  164. The size of the cache. Per default this is ``400`` which means
  165. that if more than 400 templates are loaded the loader will clean
  166. out the least recently used template. If the cache size is set to
  167. ``0`` templates are recompiled all the time, if the cache size is
  168. ``-1`` the cache will not be cleaned.
  169. .. versionchanged:: 2.8
  170. The cache size was increased to 400 from a low 50.
  171. `auto_reload`
  172. Some loaders load templates from locations where the template
  173. sources may change (ie: file system or database). If
  174. ``auto_reload`` is set to ``True`` (default) every time a template is
  175. requested the loader checks if the source changed and if yes, it
  176. will reload the template. For higher performance it's possible to
  177. disable that.
  178. `bytecode_cache`
  179. If set to a bytecode cache object, this object will provide a
  180. cache for the internal Jinja bytecode so that templates don't
  181. have to be parsed if they were not changed.
  182. See :ref:`bytecode-cache` for more information.
  183. `enable_async`
  184. If set to true this enables async template execution which allows
  185. you to take advantage of newer Python features. This requires
  186. Python 3.6 or later.
  187. """
  188. #: if this environment is sandboxed. Modifying this variable won't make
  189. #: the environment sandboxed though. For a real sandboxed environment
  190. #: have a look at jinja2.sandbox. This flag alone controls the code
  191. #: generation by the compiler.
  192. sandboxed = False
  193. #: True if the environment is just an overlay
  194. overlayed = False
  195. #: the environment this environment is linked to if it is an overlay
  196. linked_to = None
  197. #: shared environments have this set to `True`. A shared environment
  198. #: must not be modified
  199. shared = False
  200. #: these are currently EXPERIMENTAL undocumented features.
  201. exception_handler = None
  202. exception_formatter = None
  203. #: the class that is used for code generation. See
  204. #: :class:`~jinja2.compiler.CodeGenerator` for more information.
  205. code_generator_class = CodeGenerator
  206. #: the context class thatis used for templates. See
  207. #: :class:`~jinja2.runtime.Context` for more information.
  208. context_class = Context
  209. def __init__(self,
  210. block_start_string=BLOCK_START_STRING,
  211. block_end_string=BLOCK_END_STRING,
  212. variable_start_string=VARIABLE_START_STRING,
  213. variable_end_string=VARIABLE_END_STRING,
  214. comment_start_string=COMMENT_START_STRING,
  215. comment_end_string=COMMENT_END_STRING,
  216. line_statement_prefix=LINE_STATEMENT_PREFIX,
  217. line_comment_prefix=LINE_COMMENT_PREFIX,
  218. trim_blocks=TRIM_BLOCKS,
  219. lstrip_blocks=LSTRIP_BLOCKS,
  220. newline_sequence=NEWLINE_SEQUENCE,
  221. keep_trailing_newline=KEEP_TRAILING_NEWLINE,
  222. extensions=(),
  223. optimized=True,
  224. undefined=Undefined,
  225. finalize=None,
  226. autoescape=False,
  227. loader=None,
  228. cache_size=400,
  229. auto_reload=True,
  230. bytecode_cache=None,
  231. enable_async=False):
  232. # !!Important notice!!
  233. # The constructor accepts quite a few arguments that should be
  234. # passed by keyword rather than position. However it's important to
  235. # not change the order of arguments because it's used at least
  236. # internally in those cases:
  237. # - spontaneous environments (i18n extension and Template)
  238. # - unittests
  239. # If parameter changes are required only add parameters at the end
  240. # and don't change the arguments (or the defaults!) of the arguments
  241. # existing already.
  242. # lexer / parser information
  243. self.block_start_string = block_start_string
  244. self.block_end_string = block_end_string
  245. self.variable_start_string = variable_start_string
  246. self.variable_end_string = variable_end_string
  247. self.comment_start_string = comment_start_string
  248. self.comment_end_string = comment_end_string
  249. self.line_statement_prefix = line_statement_prefix
  250. self.line_comment_prefix = line_comment_prefix
  251. self.trim_blocks = trim_blocks
  252. self.lstrip_blocks = lstrip_blocks
  253. self.newline_sequence = newline_sequence
  254. self.keep_trailing_newline = keep_trailing_newline
  255. # runtime information
  256. self.undefined = undefined
  257. self.optimized = optimized
  258. self.finalize = finalize
  259. self.autoescape = autoescape
  260. # defaults
  261. self.filters = DEFAULT_FILTERS.copy()
  262. self.tests = DEFAULT_TESTS.copy()
  263. self.globals = DEFAULT_NAMESPACE.copy()
  264. # set the loader provided
  265. self.loader = loader
  266. self.cache = create_cache(cache_size)
  267. self.bytecode_cache = bytecode_cache
  268. self.auto_reload = auto_reload
  269. # configurable policies
  270. self.policies = DEFAULT_POLICIES.copy()
  271. # load extensions
  272. self.extensions = load_extensions(self, extensions)
  273. self.enable_async = enable_async
  274. self.is_async = self.enable_async and have_async_gen
  275. _environment_sanity_check(self)
  276. def add_extension(self, extension):
  277. """Adds an extension after the environment was created.
  278. .. versionadded:: 2.5
  279. """
  280. self.extensions.update(load_extensions(self, [extension]))
  281. def extend(self, **attributes):
  282. """Add the items to the instance of the environment if they do not exist
  283. yet. This is used by :ref:`extensions <writing-extensions>` to register
  284. callbacks and configuration values without breaking inheritance.
  285. """
  286. for key, value in iteritems(attributes):
  287. if not hasattr(self, key):
  288. setattr(self, key, value)
  289. def overlay(self, block_start_string=missing, block_end_string=missing,
  290. variable_start_string=missing, variable_end_string=missing,
  291. comment_start_string=missing, comment_end_string=missing,
  292. line_statement_prefix=missing, line_comment_prefix=missing,
  293. trim_blocks=missing, lstrip_blocks=missing,
  294. extensions=missing, optimized=missing,
  295. undefined=missing, finalize=missing, autoescape=missing,
  296. loader=missing, cache_size=missing, auto_reload=missing,
  297. bytecode_cache=missing):
  298. """Create a new overlay environment that shares all the data with the
  299. current environment except for cache and the overridden attributes.
  300. Extensions cannot be removed for an overlayed environment. An overlayed
  301. environment automatically gets all the extensions of the environment it
  302. is linked to plus optional extra extensions.
  303. Creating overlays should happen after the initial environment was set
  304. up completely. Not all attributes are truly linked, some are just
  305. copied over so modifications on the original environment may not shine
  306. through.
  307. """
  308. args = dict(locals())
  309. del args['self'], args['cache_size'], args['extensions']
  310. rv = object.__new__(self.__class__)
  311. rv.__dict__.update(self.__dict__)
  312. rv.overlayed = True
  313. rv.linked_to = self
  314. for key, value in iteritems(args):
  315. if value is not missing:
  316. setattr(rv, key, value)
  317. if cache_size is not missing:
  318. rv.cache = create_cache(cache_size)
  319. else:
  320. rv.cache = copy_cache(self.cache)
  321. rv.extensions = {}
  322. for key, value in iteritems(self.extensions):
  323. rv.extensions[key] = value.bind(rv)
  324. if extensions is not missing:
  325. rv.extensions.update(load_extensions(rv, extensions))
  326. return _environment_sanity_check(rv)
  327. lexer = property(get_lexer, doc="The lexer for this environment.")
  328. def iter_extensions(self):
  329. """Iterates over the extensions by priority."""
  330. return iter(sorted(self.extensions.values(),
  331. key=lambda x: x.priority))
  332. def getitem(self, obj, argument):
  333. """Get an item or attribute of an object but prefer the item."""
  334. try:
  335. return obj[argument]
  336. except (AttributeError, TypeError, LookupError):
  337. if isinstance(argument, string_types):
  338. try:
  339. attr = str(argument)
  340. except Exception:
  341. pass
  342. else:
  343. try:
  344. return getattr(obj, attr)
  345. except AttributeError:
  346. pass
  347. return self.undefined(obj=obj, name=argument)
  348. def getattr(self, obj, attribute):
  349. """Get an item or attribute of an object but prefer the attribute.
  350. Unlike :meth:`getitem` the attribute *must* be a bytestring.
  351. """
  352. try:
  353. return getattr(obj, attribute)
  354. except AttributeError:
  355. pass
  356. try:
  357. return obj[attribute]
  358. except (TypeError, LookupError, AttributeError):
  359. return self.undefined(obj=obj, name=attribute)
  360. def call_filter(self, name, value, args=None, kwargs=None,
  361. context=None, eval_ctx=None):
  362. """Invokes a filter on a value the same way the compiler does it.
  363. Note that on Python 3 this might return a coroutine in case the
  364. filter is running from an environment in async mode and the filter
  365. supports async execution. It's your responsibility to await this
  366. if needed.
  367. .. versionadded:: 2.7
  368. """
  369. func = self.filters.get(name)
  370. if func is None:
  371. fail_for_missing_callable('no filter named %r', name)
  372. args = [value] + list(args or ())
  373. if getattr(func, 'contextfilter', False):
  374. if context is None:
  375. raise TemplateRuntimeError('Attempted to invoke context '
  376. 'filter without context')
  377. args.insert(0, context)
  378. elif getattr(func, 'evalcontextfilter', False):
  379. if eval_ctx is None:
  380. if context is not None:
  381. eval_ctx = context.eval_ctx
  382. else:
  383. eval_ctx = EvalContext(self)
  384. args.insert(0, eval_ctx)
  385. elif getattr(func, 'environmentfilter', False):
  386. args.insert(0, self)
  387. return func(*args, **(kwargs or {}))
  388. def call_test(self, name, value, args=None, kwargs=None):
  389. """Invokes a test on a value the same way the compiler does it.
  390. .. versionadded:: 2.7
  391. """
  392. func = self.tests.get(name)
  393. if func is None:
  394. fail_for_missing_callable('no test named %r', name)
  395. return func(value, *(args or ()), **(kwargs or {}))
  396. @internalcode
  397. def parse(self, source, name=None, filename=None):
  398. """Parse the sourcecode and return the abstract syntax tree. This
  399. tree of nodes is used by the compiler to convert the template into
  400. executable source- or bytecode. This is useful for debugging or to
  401. extract information from templates.
  402. If you are :ref:`developing Jinja2 extensions <writing-extensions>`
  403. this gives you a good overview of the node tree generated.
  404. """
  405. try:
  406. return self._parse(source, name, filename)
  407. except TemplateSyntaxError:
  408. exc_info = sys.exc_info()
  409. self.handle_exception(exc_info, source_hint=source)
  410. def _parse(self, source, name, filename):
  411. """Internal parsing function used by `parse` and `compile`."""
  412. return Parser(self, source, name, encode_filename(filename)).parse()
  413. def lex(self, source, name=None, filename=None):
  414. """Lex the given sourcecode and return a generator that yields
  415. tokens as tuples in the form ``(lineno, token_type, value)``.
  416. This can be useful for :ref:`extension development <writing-extensions>`
  417. and debugging templates.
  418. This does not perform preprocessing. If you want the preprocessing
  419. of the extensions to be applied you have to filter source through
  420. the :meth:`preprocess` method.
  421. """
  422. source = text_type(source)
  423. try:
  424. return self.lexer.tokeniter(source, name, filename)
  425. except TemplateSyntaxError:
  426. exc_info = sys.exc_info()
  427. self.handle_exception(exc_info, source_hint=source)
  428. def preprocess(self, source, name=None, filename=None):
  429. """Preprocesses the source with all extensions. This is automatically
  430. called for all parsing and compiling methods but *not* for :meth:`lex`
  431. because there you usually only want the actual source tokenized.
  432. """
  433. return reduce(lambda s, e: e.preprocess(s, name, filename),
  434. self.iter_extensions(), text_type(source))
  435. def _tokenize(self, source, name, filename=None, state=None):
  436. """Called by the parser to do the preprocessing and filtering
  437. for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.
  438. """
  439. source = self.preprocess(source, name, filename)
  440. stream = self.lexer.tokenize(source, name, filename, state)
  441. for ext in self.iter_extensions():
  442. stream = ext.filter_stream(stream)
  443. if not isinstance(stream, TokenStream):
  444. stream = TokenStream(stream, name, filename)
  445. return stream
  446. def _generate(self, source, name, filename, defer_init=False):
  447. """Internal hook that can be overridden to hook a different generate
  448. method in.
  449. .. versionadded:: 2.5
  450. """
  451. return generate(source, self, name, filename, defer_init=defer_init,
  452. optimized=self.optimized)
  453. def _compile(self, source, filename):
  454. """Internal hook that can be overridden to hook a different compile
  455. method in.
  456. .. versionadded:: 2.5
  457. """
  458. return compile(source, filename, 'exec')
  459. @internalcode
  460. def compile(self, source, name=None, filename=None, raw=False,
  461. defer_init=False):
  462. """Compile a node or template source code. The `name` parameter is
  463. the load name of the template after it was joined using
  464. :meth:`join_path` if necessary, not the filename on the file system.
  465. the `filename` parameter is the estimated filename of the template on
  466. the file system. If the template came from a database or memory this
  467. can be omitted.
  468. The return value of this method is a python code object. If the `raw`
  469. parameter is `True` the return value will be a string with python
  470. code equivalent to the bytecode returned otherwise. This method is
  471. mainly used internally.
  472. `defer_init` is use internally to aid the module code generator. This
  473. causes the generated code to be able to import without the global
  474. environment variable to be set.
  475. .. versionadded:: 2.4
  476. `defer_init` parameter added.
  477. """
  478. source_hint = None
  479. try:
  480. if isinstance(source, string_types):
  481. source_hint = source
  482. source = self._parse(source, name, filename)
  483. source = self._generate(source, name, filename,
  484. defer_init=defer_init)
  485. if raw:
  486. return source
  487. if filename is None:
  488. filename = '<template>'
  489. else:
  490. filename = encode_filename(filename)
  491. return self._compile(source, filename)
  492. except TemplateSyntaxError:
  493. exc_info = sys.exc_info()
  494. self.handle_exception(exc_info, source_hint=source_hint)
  495. def compile_expression(self, source, undefined_to_none=True):
  496. """A handy helper method that returns a callable that accepts keyword
  497. arguments that appear as variables in the expression. If called it
  498. returns the result of the expression.
  499. This is useful if applications want to use the same rules as Jinja
  500. in template "configuration files" or similar situations.
  501. Example usage:
  502. >>> env = Environment()
  503. >>> expr = env.compile_expression('foo == 42')
  504. >>> expr(foo=23)
  505. False
  506. >>> expr(foo=42)
  507. True
  508. Per default the return value is converted to `None` if the
  509. expression returns an undefined value. This can be changed
  510. by setting `undefined_to_none` to `False`.
  511. >>> env.compile_expression('var')() is None
  512. True
  513. >>> env.compile_expression('var', undefined_to_none=False)()
  514. Undefined
  515. .. versionadded:: 2.1
  516. """
  517. parser = Parser(self, source, state='variable')
  518. exc_info = None
  519. try:
  520. expr = parser.parse_expression()
  521. if not parser.stream.eos:
  522. raise TemplateSyntaxError('chunk after expression',
  523. parser.stream.current.lineno,
  524. None, None)
  525. expr.set_environment(self)
  526. except TemplateSyntaxError:
  527. exc_info = sys.exc_info()
  528. if exc_info is not None:
  529. self.handle_exception(exc_info, source_hint=source)
  530. body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]
  531. template = self.from_string(nodes.Template(body, lineno=1))
  532. return TemplateExpression(template, undefined_to_none)
  533. def compile_templates(self, target, extensions=None, filter_func=None,
  534. zip='deflated', log_function=None,
  535. ignore_errors=True, py_compile=False):
  536. """Finds all the templates the loader can find, compiles them
  537. and stores them in `target`. If `zip` is `None`, instead of in a
  538. zipfile, the templates will be stored in a directory.
  539. By default a deflate zip algorithm is used. To switch to
  540. the stored algorithm, `zip` can be set to ``'stored'``.
  541. `extensions` and `filter_func` are passed to :meth:`list_templates`.
  542. Each template returned will be compiled to the target folder or
  543. zipfile.
  544. By default template compilation errors are ignored. In case a
  545. log function is provided, errors are logged. If you want template
  546. syntax errors to abort the compilation you can set `ignore_errors`
  547. to `False` and you will get an exception on syntax errors.
  548. If `py_compile` is set to `True` .pyc files will be written to the
  549. target instead of standard .py files. This flag does not do anything
  550. on pypy and Python 3 where pyc files are not picked up by itself and
  551. don't give much benefit.
  552. .. versionadded:: 2.4
  553. """
  554. from jinja2.loaders import ModuleLoader
  555. if log_function is None:
  556. log_function = lambda x: None
  557. if py_compile:
  558. if not PY2 or PYPY:
  559. from warnings import warn
  560. warn(Warning('py_compile has no effect on pypy or Python 3'))
  561. py_compile = False
  562. else:
  563. import imp
  564. import marshal
  565. py_header = imp.get_magic() + \
  566. u'\xff\xff\xff\xff'.encode('iso-8859-15')
  567. # Python 3.3 added a source filesize to the header
  568. if sys.version_info >= (3, 3):
  569. py_header += u'\x00\x00\x00\x00'.encode('iso-8859-15')
  570. def write_file(filename, data, mode):
  571. if zip:
  572. info = ZipInfo(filename)
  573. info.external_attr = 0o755 << 16
  574. zip_file.writestr(info, data)
  575. else:
  576. f = open(os.path.join(target, filename), mode)
  577. try:
  578. f.write(data)
  579. finally:
  580. f.close()
  581. if zip is not None:
  582. from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED
  583. zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED,
  584. stored=ZIP_STORED)[zip])
  585. log_function('Compiling into Zip archive "%s"' % target)
  586. else:
  587. if not os.path.isdir(target):
  588. os.makedirs(target)
  589. log_function('Compiling into folder "%s"' % target)
  590. try:
  591. for name in self.list_templates(extensions, filter_func):
  592. source, filename, _ = self.loader.get_source(self, name)
  593. try:
  594. code = self.compile(source, name, filename, True, True)
  595. except TemplateSyntaxError as e:
  596. if not ignore_errors:
  597. raise
  598. log_function('Could not compile "%s": %s' % (name, e))
  599. continue
  600. filename = ModuleLoader.get_module_filename(name)
  601. if py_compile:
  602. c = self._compile(code, encode_filename(filename))
  603. write_file(filename + 'c', py_header +
  604. marshal.dumps(c), 'wb')
  605. log_function('Byte-compiled "%s" as %s' %
  606. (name, filename + 'c'))
  607. else:
  608. write_file(filename, code, 'w')
  609. log_function('Compiled "%s" as %s' % (name, filename))
  610. finally:
  611. if zip:
  612. zip_file.close()
  613. log_function('Finished compiling templates')
  614. def list_templates(self, extensions=None, filter_func=None):
  615. """Returns a list of templates for this environment. This requires
  616. that the loader supports the loader's
  617. :meth:`~BaseLoader.list_templates` method.
  618. If there are other files in the template folder besides the
  619. actual templates, the returned list can be filtered. There are two
  620. ways: either `extensions` is set to a list of file extensions for
  621. templates, or a `filter_func` can be provided which is a callable that
  622. is passed a template name and should return `True` if it should end up
  623. in the result list.
  624. If the loader does not support that, a :exc:`TypeError` is raised.
  625. .. versionadded:: 2.4
  626. """
  627. x = self.loader.list_templates()
  628. if extensions is not None:
  629. if filter_func is not None:
  630. raise TypeError('either extensions or filter_func '
  631. 'can be passed, but not both')
  632. filter_func = lambda x: '.' in x and \
  633. x.rsplit('.', 1)[1] in extensions
  634. if filter_func is not None:
  635. x = list(ifilter(filter_func, x))
  636. return x
  637. def handle_exception(self, exc_info=None, rendered=False, source_hint=None):
  638. """Exception handling helper. This is used internally to either raise
  639. rewritten exceptions or return a rendered traceback for the template.
  640. """
  641. global _make_traceback
  642. if exc_info is None:
  643. exc_info = sys.exc_info()
  644. # the debugging module is imported when it's used for the first time.
  645. # we're doing a lot of stuff there and for applications that do not
  646. # get any exceptions in template rendering there is no need to load
  647. # all of that.
  648. if _make_traceback is None:
  649. from jinja2.debug import make_traceback as _make_traceback
  650. traceback = _make_traceback(exc_info, source_hint)
  651. if rendered and self.exception_formatter is not None:
  652. return self.exception_formatter(traceback)
  653. if self.exception_handler is not None:
  654. self.exception_handler(traceback)
  655. exc_type, exc_value, tb = traceback.standard_exc_info
  656. reraise(exc_type, exc_value, tb)
  657. def join_path(self, template, parent):
  658. """Join a template with the parent. By default all the lookups are
  659. relative to the loader root so this method returns the `template`
  660. parameter unchanged, but if the paths should be relative to the
  661. parent template, this function can be used to calculate the real
  662. template name.
  663. Subclasses may override this method and implement template path
  664. joining here.
  665. """
  666. return template
  667. @internalcode
  668. def _load_template(self, name, globals):
  669. if self.loader is None:
  670. raise TypeError('no loader for this environment specified')
  671. cache_key = (weakref.ref(self.loader), name)
  672. if self.cache is not None:
  673. template = self.cache.get(cache_key)
  674. if template is not None and (not self.auto_reload or
  675. template.is_up_to_date):
  676. return template
  677. template = self.loader.load(self, name, globals)
  678. if self.cache is not None:
  679. self.cache[cache_key] = template
  680. return template
  681. @internalcode
  682. def get_template(self, name, parent=None, globals=None):
  683. """Load a template from the loader. If a loader is configured this
  684. method asks the loader for the template and returns a :class:`Template`.
  685. If the `parent` parameter is not `None`, :meth:`join_path` is called
  686. to get the real template name before loading.
  687. The `globals` parameter can be used to provide template wide globals.
  688. These variables are available in the context at render time.
  689. If the template does not exist a :exc:`TemplateNotFound` exception is
  690. raised.
  691. .. versionchanged:: 2.4
  692. If `name` is a :class:`Template` object it is returned from the
  693. function unchanged.
  694. """
  695. if isinstance(name, Template):
  696. return name
  697. if parent is not None:
  698. name = self.join_path(name, parent)
  699. return self._load_template(name, self.make_globals(globals))
  700. @internalcode
  701. def select_template(self, names, parent=None, globals=None):
  702. """Works like :meth:`get_template` but tries a number of templates
  703. before it fails. If it cannot find any of the templates, it will
  704. raise a :exc:`TemplatesNotFound` exception.
  705. .. versionadded:: 2.3
  706. .. versionchanged:: 2.4
  707. If `names` contains a :class:`Template` object it is returned
  708. from the function unchanged.
  709. """
  710. if not names:
  711. raise TemplatesNotFound(message=u'Tried to select from an empty list '
  712. u'of templates.')
  713. globals = self.make_globals(globals)
  714. for name in names:
  715. if isinstance(name, Template):
  716. return name
  717. if parent is not None:
  718. name = self.join_path(name, parent)
  719. try:
  720. return self._load_template(name, globals)
  721. except TemplateNotFound:
  722. pass
  723. raise TemplatesNotFound(names)
  724. @internalcode
  725. def get_or_select_template(self, template_name_or_list,
  726. parent=None, globals=None):
  727. """Does a typecheck and dispatches to :meth:`select_template`
  728. if an iterable of template names is given, otherwise to
  729. :meth:`get_template`.
  730. .. versionadded:: 2.3
  731. """
  732. if isinstance(template_name_or_list, string_types):
  733. return self.get_template(template_name_or_list, parent, globals)
  734. elif isinstance(template_name_or_list, Template):
  735. return template_name_or_list
  736. return self.select_template(template_name_or_list, parent, globals)
  737. def from_string(self, source, globals=None, template_class=None):
  738. """Load a template from a string. This parses the source given and
  739. returns a :class:`Template` object.
  740. """
  741. globals = self.make_globals(globals)
  742. cls = template_class or self.template_class
  743. return cls.from_code(self, self.compile(source), globals, None)
  744. def make_globals(self, d):
  745. """Return a dict for the globals."""
  746. if not d:
  747. return self.globals
  748. return dict(self.globals, **d)
  749. class Template(object):
  750. """The central template object. This class represents a compiled template
  751. and is used to evaluate it.
  752. Normally the template object is generated from an :class:`Environment` but
  753. it also has a constructor that makes it possible to create a template
  754. instance directly using the constructor. It takes the same arguments as
  755. the environment constructor but it's not possible to specify a loader.
  756. Every template object has a few methods and members that are guaranteed
  757. to exist. However it's important that a template object should be
  758. considered immutable. Modifications on the object are not supported.
  759. Template objects created from the constructor rather than an environment
  760. do have an `environment` attribute that points to a temporary environment
  761. that is probably shared with other templates created with the constructor
  762. and compatible settings.
  763. >>> template = Template('Hello {{ name }}!')
  764. >>> template.render(name='John Doe') == u'Hello John Doe!'
  765. True
  766. >>> stream = template.stream(name='John Doe')
  767. >>> next(stream) == u'Hello John Doe!'
  768. True
  769. >>> next(stream)
  770. Traceback (most recent call last):
  771. ...
  772. StopIteration
  773. """
  774. def __new__(cls, source,
  775. block_start_string=BLOCK_START_STRING,
  776. block_end_string=BLOCK_END_STRING,
  777. variable_start_string=VARIABLE_START_STRING,
  778. variable_end_string=VARIABLE_END_STRING,
  779. comment_start_string=COMMENT_START_STRING,
  780. comment_end_string=COMMENT_END_STRING,
  781. line_statement_prefix=LINE_STATEMENT_PREFIX,
  782. line_comment_prefix=LINE_COMMENT_PREFIX,
  783. trim_blocks=TRIM_BLOCKS,
  784. lstrip_blocks=LSTRIP_BLOCKS,
  785. newline_sequence=NEWLINE_SEQUENCE,
  786. keep_trailing_newline=KEEP_TRAILING_NEWLINE,
  787. extensions=(),
  788. optimized=True,
  789. undefined=Undefined,
  790. finalize=None,
  791. autoescape=False,
  792. enable_async=False):
  793. env = get_spontaneous_environment(
  794. block_start_string, block_end_string, variable_start_string,
  795. variable_end_string, comment_start_string, comment_end_string,
  796. line_statement_prefix, line_comment_prefix, trim_blocks,
  797. lstrip_blocks, newline_sequence, keep_trailing_newline,
  798. frozenset(extensions), optimized, undefined, finalize, autoescape,
  799. None, 0, False, None, enable_async)
  800. return env.from_string(source, template_class=cls)
  801. @classmethod
  802. def from_code(cls, environment, code, globals, uptodate=None):
  803. """Creates a template object from compiled code and the globals. This
  804. is used by the loaders and environment to create a template object.
  805. """
  806. namespace = {
  807. 'environment': environment,
  808. '__file__': code.co_filename
  809. }
  810. exec(code, namespace)
  811. rv = cls._from_namespace(environment, namespace, globals)
  812. rv._uptodate = uptodate
  813. return rv
  814. @classmethod
  815. def from_module_dict(cls, environment, module_dict, globals):
  816. """Creates a template object from a module. This is used by the
  817. module loader to create a template object.
  818. .. versionadded:: 2.4
  819. """
  820. return cls._from_namespace(environment, module_dict, globals)
  821. @classmethod
  822. def _from_namespace(cls, environment, namespace, globals):
  823. t = object.__new__(cls)
  824. t.environment = environment
  825. t.globals = globals
  826. t.name = namespace['name']
  827. t.filename = namespace['__file__']
  828. t.blocks = namespace['blocks']
  829. # render function and module
  830. t.root_render_func = namespace['root']
  831. t._module = None
  832. # debug and loader helpers
  833. t._debug_info = namespace['debug_info']
  834. t._uptodate = None
  835. # store the reference
  836. namespace['environment'] = environment
  837. namespace['__jinja_template__'] = t
  838. return t
  839. def render(self, *args, **kwargs):
  840. """This method accepts the same arguments as the `dict` constructor:
  841. A dict, a dict subclass or some keyword arguments. If no arguments
  842. are given the context will be empty. These two calls do the same::
  843. template.render(knights='that say nih')
  844. template.render({'knights': 'that say nih'})
  845. This will return the rendered template as unicode string.
  846. """
  847. vars = dict(*args, **kwargs)
  848. try:
  849. return concat(self.root_render_func(self.new_context(vars)))
  850. except Exception:
  851. exc_info = sys.exc_info()
  852. return self.environment.handle_exception(exc_info, True)
  853. def render_async(self, *args, **kwargs):
  854. """This works similar to :meth:`render` but returns a coroutine
  855. that when awaited returns the entire rendered template string. This
  856. requires the async feature to be enabled.
  857. Example usage::
  858. await template.render_async(knights='that say nih; asynchronously')
  859. """
  860. # see asyncsupport for the actual implementation
  861. raise NotImplementedError('This feature is not available for this '
  862. 'version of Python')
  863. def stream(self, *args, **kwargs):
  864. """Works exactly like :meth:`generate` but returns a
  865. :class:`TemplateStream`.
  866. """
  867. return TemplateStream(self.generate(*args, **kwargs))
  868. def generate(self, *args, **kwargs):
  869. """For very large templates it can be useful to not render the whole
  870. template at once but evaluate each statement after another and yield
  871. piece for piece. This method basically does exactly that and returns
  872. a generator that yields one item after another as unicode strings.
  873. It accepts the same arguments as :meth:`render`.
  874. """
  875. vars = dict(*args, **kwargs)
  876. try:
  877. for event in self.root_render_func(self.new_context(vars)):
  878. yield event
  879. except Exception:
  880. exc_info = sys.exc_info()
  881. else:
  882. return
  883. yield self.environment.handle_exception(exc_info, True)
  884. def generate_async(self, *args, **kwargs):
  885. """An async version of :meth:`generate`. Works very similarly but
  886. returns an async iterator instead.
  887. """
  888. # see asyncsupport for the actual implementation
  889. raise NotImplementedError('This feature is not available for this '
  890. 'version of Python')
  891. def new_context(self, vars=None, shared=False, locals=None):
  892. """Create a new :class:`Context` for this template. The vars
  893. provided will be passed to the template. Per default the globals
  894. are added to the context. If shared is set to `True` the data
  895. is passed as it to the context without adding the globals.
  896. `locals` can be a dict of local variables for internal usage.
  897. """
  898. return new_context(self.environment, self.name, self.blocks,
  899. vars, shared, self.globals, locals)
  900. def make_module(self, vars=None, shared=False, locals=None):
  901. """This method works like the :attr:`module` attribute when called
  902. without arguments but it will evaluate the template on every call
  903. rather than caching it. It's also possible to provide
  904. a dict which is then used as context. The arguments are the same
  905. as for the :meth:`new_context` method.
  906. """
  907. return TemplateModule(self, self.new_context(vars, shared, locals))
  908. def make_module_async(self, vars=None, shared=False, locals=None):
  909. """As template module creation can invoke template code for
  910. asynchronous exections this method must be used instead of the
  911. normal :meth:`make_module` one. Likewise the module attribute
  912. becomes unavailable in async mode.
  913. """
  914. # see asyncsupport for the actual implementation
  915. raise NotImplementedError('This feature is not available for this '
  916. 'version of Python')
  917. @internalcode
  918. def _get_default_module(self):
  919. if self._module is not None:
  920. return self._module
  921. self._module = rv = self.make_module()
  922. return rv
  923. @property
  924. def module(self):
  925. """The template as module. This is used for imports in the
  926. template runtime but is also useful if one wants to access
  927. exported template variables from the Python layer:
  928. >>> t = Template('{% macro foo() %}42{% endmacro %}23')
  929. >>> str(t.module)
  930. '23'
  931. >>> t.module.foo() == u'42'
  932. True
  933. This attribute is not available if async mode is enabled.
  934. """
  935. return self._get_default_module()
  936. def get_corresponding_lineno(self, lineno):
  937. """Return the source line number of a line number in the
  938. generated bytecode as they are not in sync.
  939. """
  940. for template_line, code_line in reversed(self.debug_info):
  941. if code_line <= lineno:
  942. return template_line
  943. return 1
  944. @property
  945. def is_up_to_date(self):
  946. """If this variable is `False` there is a newer version available."""
  947. if self._uptodate is None:
  948. return True
  949. return self._uptodate()
  950. @property
  951. def debug_info(self):
  952. """The debug info mapping."""
  953. return [tuple(imap(int, x.split('='))) for x in
  954. self._debug_info.split('&')]
  955. def __repr__(self):
  956. if self.name is None:
  957. name = 'memory:%x' % id(self)
  958. else:
  959. name = repr(self.name)
  960. return '<%s %s>' % (self.__class__.__name__, name)
  961. @implements_to_string
  962. class TemplateModule(object):
  963. """Represents an imported template. All the exported names of the
  964. template are available as attributes on this object. Additionally
  965. converting it into an unicode- or bytestrings renders the contents.
  966. """
  967. def __init__(self, template, context, body_stream=None):
  968. if body_stream is None:
  969. if context.environment.is_async:
  970. raise RuntimeError('Async mode requires a body stream '
  971. 'to be passed to a template module. Use '
  972. 'the async methods of the API you are '
  973. 'using.')
  974. body_stream = list(template.root_render_func(context))
  975. self._body_stream = body_stream
  976. self.__dict__.update(context.get_exported())
  977. self.__name__ = template.name
  978. def __html__(self):
  979. return Markup(concat(self._body_stream))
  980. def __str__(self):
  981. return concat(self._body_stream)
  982. def __repr__(self):
  983. if self.__name__ is None:
  984. name = 'memory:%x' % id(self)
  985. else:
  986. name = repr(self.__name__)
  987. return '<%s %s>' % (self.__class__.__name__, name)
  988. class TemplateExpression(object):
  989. """The :meth:`jinja2.Environment.compile_expression` method returns an
  990. instance of this object. It encapsulates the expression-like access
  991. to the template with an expression it wraps.
  992. """
  993. def __init__(self, template, undefined_to_none):
  994. self._template = template
  995. self._undefined_to_none = undefined_to_none
  996. def __call__(self, *args, **kwargs):
  997. context = self._template.new_context(dict(*args, **kwargs))
  998. consume(self._template.root_render_func(context))
  999. rv = context.vars['result']
  1000. if self._undefined_to_none and isinstance(rv, Undefined):
  1001. rv = None
  1002. return rv
  1003. @implements_iterator
  1004. class TemplateStream(object):
  1005. """A template stream works pretty much like an ordinary python generator
  1006. but it can buffer multiple items to reduce the number of total iterations.
  1007. Per default the output is unbuffered which means that for every unbuffered
  1008. instruction in the template one unicode string is yielded.
  1009. If buffering is enabled with a buffer size of 5, five items are combined
  1010. into a new unicode string. This is mainly useful if you are streaming
  1011. big templates to a client via WSGI which flushes after each iteration.
  1012. """
  1013. def __init__(self, gen):
  1014. self._gen = gen
  1015. self.disable_buffering()
  1016. def dump(self, fp, encoding=None, errors='strict'):
  1017. """Dump the complete stream into a file or file-like object.
  1018. Per default unicode strings are written, if you want to encode
  1019. before writing specify an `encoding`.
  1020. Example usage::
  1021. Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')
  1022. """
  1023. close = False
  1024. if isinstance(fp, string_types):
  1025. if encoding is None:
  1026. encoding = 'utf-8'
  1027. fp = open(fp, 'wb')
  1028. close = True
  1029. try:
  1030. if encoding is not None:
  1031. iterable = (x.encode(encoding, errors) for x in self)
  1032. else:
  1033. iterable = self
  1034. if hasattr(fp, 'writelines'):
  1035. fp.writelines(iterable)
  1036. else:
  1037. for item in iterable:
  1038. fp.write(item)
  1039. finally:
  1040. if close:
  1041. fp.close()
  1042. def disable_buffering(self):
  1043. """Disable the output buffering."""
  1044. self._next = partial(next, self._gen)
  1045. self.buffered = False
  1046. def _buffered_generator(self, size):
  1047. buf = []
  1048. c_size = 0
  1049. push = buf.append
  1050. while 1:
  1051. try:
  1052. while c_size < size:
  1053. c = next(self._gen)
  1054. push(c)
  1055. if c:
  1056. c_size += 1
  1057. except StopIteration:
  1058. if not c_size:
  1059. return
  1060. yield concat(buf)
  1061. del buf[:]
  1062. c_size = 0
  1063. def enable_buffering(self, size=5):
  1064. """Enable buffering. Buffer `size` items before yielding them."""
  1065. if size <= 1:
  1066. raise ValueError('buffer size too small')
  1067. self.buffered = True
  1068. self._next = partial(next, self._buffered_generator(size))
  1069. def __iter__(self):
  1070. return self
  1071. def __next__(self):
  1072. return self._next()
  1073. # hook in default template class. if anyone reads this comment: ignore that
  1074. # it's possible to use custom templates ;-)
  1075. Environment.template_class = Template