environment.py 48 KB

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