Skip to content
Myr

Merge pull request #1121 from pallets/the-great-rename

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Rename jinja2 to jinja

authored by David Lord · committed by GitHub · parents 42d4a4e, fc9c60b · Browse files · 131 files+13793 added−13627 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

131 files+13793 added−13627 removed

  • tests:+169 added−171 removed
  • other:+13624 added−13456 removed

131 files+13793 added−13627 removed

modified:docs/examples/cache_extension.py+2 added-2 removed
1from jinja2 import nodes2from jinja2.ext import Extension1from jinja import nodes2from jinja.ext import Extension345class FragmentCacheExtension(Extension):6 # a set of names that trigger the extension.
48 unmodified lines
modified:docs/examples/inline_gettext_extension.py+4 added-4 removed
1# -*- coding: utf-8 -*-2import re34from jinja2.exceptions import TemplateSyntaxError5from jinja2.ext import Extension6from jinja2.lexer import count_newlines7from jinja2.lexer import Token4from jinja.exceptions import TemplateSyntaxError5from jinja.ext import Extension6from jinja.lexer import count_newlines7from jinja.lexer import Token8910_outside_re = re.compile(r"\\?(gettext|_)\(")11_inside_re = re.compile(r"\\?[()]")
62 unmodified lines
modified:docs/api.rst+48 added-48 removed
1API2===34.. module:: jinja24.. module:: jinja5 :noindex:6 :synopsis: public Jinja API78This document describes the API to Jinja and not the template language. It
17 unmodified lines
2627The simplest way to configure Jinja to load templates for your application28looks roughly like this::2930 from jinja2 import Environment, PackageLoader, select_autoescape30 from jinja import Environment, PackageLoader, select_autoescape31 env = Environment(32 loader=PackageLoader('yourapplication', 'templates'),33 autoescape=select_autoescape(['html', 'xml'])34 )
106 unmodified lines
141 .. attribute:: sandboxed142143 If the environment is sandboxed this attribute is `True`. For the144 sandbox mode have a look at the documentation for the145 :class:`~jinja2.sandbox.SandboxedEnvironment`.145 :class:`~jinja.sandbox.SandboxedEnvironment`.146147 .. attribute:: filters148149 A dict of filters for this environment. As long as no template was
31 unmodified lines
181182 The context used for templates. This should not be changed183 in most cases, unless you need to modify internals of how184 template variables are handled. For details, see185 :class:`~jinja2.runtime.Context`.185 :class:`~jinja.runtime.Context`.186187 .. automethod:: overlay([options])188189 .. method:: undefined([hint, obj, name, exc])
60 unmodified lines
250251 .. automethod:: generate_async([context])252253254.. autoclass:: jinja2.environment.TemplateStream()254.. autoclass:: jinja.environment.TemplateStream()255 :members: disable_buffering, enable_buffering, dump256257258Autoescaping
7 unmodified lines
266future. It's recommended to configure a sensible default for267autoescaping. This makes it possible to enable and disable autoescaping268on a per-template basis (HTML versus text for instance).269270.. autofunction:: jinja2.select_autoescape270.. autofunction:: jinja.select_autoescape271272Here a recommended setup that enables autoescaping for templates ending273in ``'.html'``, ``'.htm'`` and ``'.xml'`` and disabling it by default274for all other extensions. You can use the :func:`~jinja2.select_autoescape`274for all other extensions. You can use the :func:`~jinja.select_autoescape`275function for this::276277 from jinja2 import Environment, select_autoescape277 from jinja import Environment, select_autoescape278 env = Environment(autoescape=select_autoescape(['html', 'htm', 'xml']),279 loader=PackageLoader('mypackage'))280281The :func:`~jinja.select_autoescape` function returns a function that
41 unmodified lines
323324The closest to regular Python behavior is the :class:`StrictUndefined` which325disallows all operations beside testing if it's an undefined object.326327.. autoclass:: jinja2.Undefined()327.. autoclass:: jinja.Undefined()328329 .. attribute:: _undefined_hint330331 Either `None` or an unicode string with the error message for
19 unmodified lines
351 When called with any arguments this method raises352 :attr:`_undefined_exception` with an error message generated353 from the undefined hints stored on the undefined object.354355.. autoclass:: jinja2.ChainableUndefined()355.. autoclass:: jinja.ChainableUndefined()356357.. autoclass:: jinja2.DebugUndefined()357.. autoclass:: jinja.DebugUndefined()358359.. autoclass:: jinja2.StrictUndefined()359.. autoclass:: jinja.StrictUndefined()360361There is also a factory function that can decorate undefined objects to362implement logging on failures:363364.. autofunction:: jinja2.make_logging_undefined364.. autofunction:: jinja.make_logging_undefined365366Undefined objects are created by calling :attr:`undefined`.367368.. admonition:: Implementation
23 unmodified lines
392393The Context394-----------395396.. autoclass:: jinja2.runtime.Context()396.. autoclass:: jinja.runtime.Context()397 :members: resolve, get_exported, get_all398399 .. attribute:: parent400
35 unmodified lines
436 .. attribute:: eval_ctx437438 The current :ref:`eval-context`.439440 .. automethod:: jinja2.runtime.Context.call(callable, \*args, \**kwargs)440 .. automethod:: jinja.runtime.Context.call(callable, \*args, \**kwargs)441442443.. admonition:: Implementation444
18 unmodified lines
463size by default and templates are automatically reloaded.464All loaders are subclasses of :class:`BaseLoader`. If you want to create your465own loader, subclass :class:`BaseLoader` and override `get_source`.466467.. autoclass:: jinja2.BaseLoader467.. autoclass:: jinja.BaseLoader468 :members: get_source, load469470Here a list of the builtin loaders Jinja provides:471472.. autoclass:: jinja2.FileSystemLoader472.. autoclass:: jinja.FileSystemLoader473474.. autoclass:: jinja2.PackageLoader474.. autoclass:: jinja.PackageLoader475476.. autoclass:: jinja2.DictLoader476.. autoclass:: jinja.DictLoader477478.. autoclass:: jinja2.FunctionLoader478.. autoclass:: jinja.FunctionLoader479480.. autoclass:: jinja2.PrefixLoader480.. autoclass:: jinja.PrefixLoader481482.. autoclass:: jinja2.ChoiceLoader482.. autoclass:: jinja.ChoiceLoader483484.. autoclass:: jinja2.ModuleLoader484.. autoclass:: jinja.ModuleLoader485486487.. _bytecode-cache:488
9 unmodified lines
498the application.499500To use a bytecode cache, instantiate it and pass it to the :class:`Environment`.501502.. autoclass:: jinja2.BytecodeCache502.. autoclass:: jinja.BytecodeCache503 :members: load_bytecode, dump_bytecode, clear504505.. autoclass:: jinja2.bccache.Bucket505.. autoclass:: jinja.bccache.Bucket506 :members: write_bytecode, load_bytecode, bytecode_from_string,507 bytecode_to_string, reset508509 .. attribute:: environment
10 unmodified lines
520521522Builtin bytecode caches:523524.. autoclass:: jinja2.FileSystemBytecodeCache524.. autoclass:: jinja.FileSystemBytecodeCache525526.. autoclass:: jinja2.MemcachedBytecodeCache526.. autoclass:: jinja.MemcachedBytecodeCache527528529Async Support530-------------
37 unmodified lines
568569Starting with Jinja 2.9 policies can be configured on the environment570which can slightly influence how filters and other template constructs571behave. They can be configured with the572:attr:`~jinja2.Environment.policies` attribute.572:attr:`~jinja.Environment.policies` attribute.573574Example::575576 env.policies['urlize.rel'] = 'nofollow noopener'
48 unmodified lines
625626These helper functions and classes are useful if you add custom filters or627functions to a Jinja environment.628629.. autofunction:: jinja2.environmentfilter629.. autofunction:: jinja.environmentfilter630631.. autofunction:: jinja2.contextfilter631.. autofunction:: jinja.contextfilter632633.. autofunction:: jinja2.evalcontextfilter633.. autofunction:: jinja.evalcontextfilter634635.. autofunction:: jinja2.environmentfunction635.. autofunction:: jinja.environmentfunction636637.. autofunction:: jinja2.contextfunction637.. autofunction:: jinja.contextfunction638639.. autofunction:: jinja2.evalcontextfunction639.. autofunction:: jinja.evalcontextfunction640641.. function:: escape(s)642643 Convert the characters ``&``, ``<``, ``>``, ``'``, and ``"`` in string `s`
2 unmodified lines
646 that do have an HTML representation such as already escaped data.647648 The return value is a :class:`Markup` string.649650.. autofunction:: jinja2.clear_caches650.. autofunction:: jinja.clear_caches651652.. autofunction:: jinja2.is_undefined652.. autofunction:: jinja.is_undefined653654.. autoclass:: jinja2.Markup([string])654.. autoclass:: jinja.Markup([string])655 :members: escape, unescape, striptags656657.. admonition:: Note658
4 unmodified lines
663664Exceptions665----------666667.. autoexception:: jinja2.TemplateError667.. autoexception:: jinja.TemplateError668669.. autoexception:: jinja2.UndefinedError669.. autoexception:: jinja.UndefinedError670671.. autoexception:: jinja2.TemplateNotFound671.. autoexception:: jinja.TemplateNotFound672673.. autoexception:: jinja2.TemplatesNotFound673.. autoexception:: jinja.TemplatesNotFound674675.. autoexception:: jinja2.TemplateSyntaxError675.. autoexception:: jinja.TemplateSyntaxError676677 .. attribute:: message678679 The error message as utf-8 bytestring.
14 unmodified lines
694 The reason why the filename and error message are bytestrings and not695 unicode strings is that Python 2.x is not using unicode for exceptions696 and tracebacks as well as the compiler. This will change with Python 3.697698.. autoexception:: jinja2.TemplateRuntimeError698.. autoexception:: jinja.TemplateRuntimeError699700.. autoexception:: jinja2.TemplateAssertionError700.. autoexception:: jinja.TemplateAssertionError701702703.. _writing-filters:704
33 unmodified lines
738paragraphs and marks the return value as safe HTML string if autoescaping is739enabled::740741 import re742 from jinja2 import evalcontextfilter, Markup, escape742 from jinja import evalcontextfilter, Markup, escape743744 _paragraph_re = re.compile(r'(?:\r\n|\r(?!\n)|\n){2,}')745746 @evalcontextfilter
57 unmodified lines
804must only happen with a :class:`nodes.EvalContextModifier` and805:class:`nodes.ScopedEvalContextModifier` from an extension, not on the806eval context object itself.807808.. autoclass:: jinja2.nodes.EvalContext808.. autoclass:: jinja.nodes.EvalContext809810 .. attribute:: autoescape811812 `True` or `False` depending on if autoescaping is active or not.
114 unmodified lines
927could help applications to implement more advanced template concepts. All928the functions of the meta API operate on an abstract syntax tree as929returned by the :meth:`Environment.parse` method.930931.. autofunction:: jinja2.meta.find_undeclared_variables931.. autofunction:: jinja.meta.find_undeclared_variables932933.. autofunction:: jinja2.meta.find_referenced_templates933.. autofunction:: jinja.meta.find_referenced_templates
modified:docs/conf.py+2 added-2 removed
4 unmodified lines
56project = "Jinja"7copyright = "2007 Pallets"8author = "Pallets"9release, version = get_version("Jinja2")9release, version = get_version("Jinja")1011# General --------------------------------------------------------------1213master_doc = "index"
14 unmodified lines
28html_context = {29 "project_links": [30 ProjectLink("Donate to Pallets", "https://palletsprojects.com/donate"),31 ProjectLink("Jinja Website", "https://palletsprojects.com/p/jinja/"),32 ProjectLink("PyPI releases", "https://pypi.org/project/Jinja2/"),32 ProjectLink("PyPI releases", "https://pypi.org/project/Jinja/"),33 ProjectLink("Source Code", "https://github.com/pallets/jinja/"),34 ProjectLink("Issue Tracker", "https://github.com/pallets/jinja/issues/"),35 ]36}
16 unmodified lines
modified:docs/extensions.rst+26 added-26 removed
12 unmodified lines
1314Extensions are added to the Jinja environment at creation time. Once the15environment is created additional extensions cannot be added. To add an16extension pass a list of extension classes or import paths to the17``extensions`` parameter of the :class:`~jinja2.Environment` constructor. The following17``extensions`` parameter of the :class:`~jinja.Environment` constructor. The following18example creates a Jinja environment with the i18n extension loaded::1920 jinja_env = Environment(extensions=['jinja2.ext.i18n'])20 jinja_env = Environment(extensions=['jinja.ext.i18n'])212223.. _i18n-extension:2425i18n Extension26--------------2728**Import name:** ``jinja2.ext.i18n``28**Import name:** ``jinja.ext.i18n``2930The i18n extension can be used in combination with `gettext`_ or31`Babel`_. When it's enabled, Jinja provides a ``trans`` statement that32marks a block as translatable and calls ``gettext``.
7 unmodified lines
4041After enabling the extension, the environment provides the following42additional methods:4344.. method:: jinja2.Environment.install_gettext_translations(translations, newstyle=False)44.. method:: jinja.Environment.install_gettext_translations(translations, newstyle=False)4546 Installs a translation globally for the environment. The47 ``translations`` object must implement ``gettext`` and ``ngettext``48 (or ``ugettext`` and ``ungettext`` for Python 2).
1 unmodified line
50 and `Babel`_\s ``Translations`` are supported.5152 .. versionchanged:: 2.5 Added new-style gettext support.5354.. method:: jinja2.Environment.install_null_translations(newstyle=False)54.. method:: jinja.Environment.install_null_translations(newstyle=False)5556 Install no-op gettext functions. This is useful if you want to57 prepare the application for internationalization but don't want to58 implement the full system yet.5960 .. versionchanged:: 2.5 Added new-style gettext support.6162.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)62.. method:: jinja.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)6364 Install the given ``gettext`` and ``ngettext`` callables into the65 environment. They should behave exactly like66 :func:`gettext.gettext` and :func:`gettext.ngettext` (or
3 unmodified lines
70 newstyle callables. See :ref:`newstyle-gettext` for more information.7172 .. versionadded:: 2.5 Added new-style gettext support.7374.. method:: jinja2.Environment.uninstall_gettext_translations()74.. method:: jinja.Environment.uninstall_gettext_translations()7576 Uninstall the environment's globally installed translation.7778.. method:: jinja2.Environment.extract_translations(source)78.. method:: jinja.Environment.extract_translations(source)7980 Extract localizable strings from the given template node or source.8182 For every string found this function yields a ``(lineno, function,
16 unmodified lines
99100.. code-block:: python101102 translations = get_gettext_translations()103 env = Environment(extensions=["jinja2.ext.i18n"])103 env = Environment(extensions=["jinja.ext.i18n"])104 env.install_gettext_translations(translations)105106The ``get_gettext_translations`` function would return the translator107for the current configuration, for example by using ``gettext.find``.
73 unmodified lines
181182Expression Statement183--------------------184185**Import name:** ``jinja2.ext.do``185**Import name:** ``jinja.ext.do``186187The "do" aka expression-statement extension adds a simple ``do`` tag to the188template engine that works like a variable expression but ignores the189return value.
2 unmodified lines
192193Loop Controls194-------------195196**Import name:** ``jinja2.ext.loopcontrols``196**Import name:** ``jinja.ext.loopcontrols``197198This extension adds support for ``break`` and ``continue`` in loops. After199enabling, Jinja provides those two keywords which work exactly like in200Python.
2 unmodified lines
203204With Statement205--------------206207**Import name:** ``jinja2.ext.with_``207**Import name:** ``jinja.ext.with_``208209.. versionchanged:: 2.9210211 This extension is now built-in and no longer does anything.
2 unmodified lines
214215Autoescape Extension216--------------------217218**Import name:** ``jinja2.ext.autoescape``218**Import name:** ``jinja.ext.autoescape``219220.. versionchanged:: 2.9221222 This extension was removed and is now built-in. Enabling the
4 unmodified lines
227228Debug Extension229---------------230231**Import name:** ``jinja2.ext.debug``231**Import name:** ``jinja.ext.debug``232233Adds a ``{% debug %}`` tag to dump the current context as well as the234available filters and tests. This is useful to see what's available to235use in the template without setting up a debugger.
3 unmodified lines
239240Writing Extensions241------------------242243.. module:: jinja2.ext243.. module:: jinja.ext244245By writing extensions you can add custom tags to Jinja. This is a non-trivial246task and usually not needed as the default tags and expressions cover all247common use cases. The i18n extension is a good example of why extensions are
20 unmodified lines
268 :language: python269270And here is how you use it in an environment::271272 from jinja2 import Environment272 from jinja import Environment273 from cachelib import SimpleCache274275 env = Environment(extensions=[FragmentCacheExtension])276 env.fragment_cache = SimpleCache()
35 unmodified lines
312313Extension314~~~~~~~~~315316Extensions always have to extend the :class:`jinja2.ext.Extension` class:316Extensions always have to extend the :class:`jinja.ext.Extension` class:317318.. autoclass:: Extension319 :members: preprocess, filter_stream, parse, attr, call_method320
14 unmodified lines
335The parser passed to :meth:`Extension.parse` provides ways to parse336expressions of different types. The following methods may be used by337extensions:338339.. autoclass:: jinja2.parser.Parser339.. autoclass:: jinja.parser.Parser340 :members: parse_expression, parse_tuple, parse_assign_target,341 parse_statements, free_identifier, fail342343 .. attribute:: filename
8 unmodified lines
352 The load name of the template.353354 .. attribute:: stream355356 The current :class:`~jinja2.lexer.TokenStream`356 The current :class:`~jinja.lexer.TokenStream`357358.. autoclass:: jinja2.lexer.TokenStream358.. autoclass:: jinja.lexer.TokenStream359 :members: push, look, eos, skip, __next__, next_if, skip_if, expect360361 .. attribute:: current362363 The current :class:`~jinja2.lexer.Token`.363 The current :class:`~jinja.lexer.Token`.364365.. autoclass:: jinja2.lexer.Token365.. autoclass:: jinja.lexer.Token366 :members: test, test_any367368 .. attribute:: lineno369
10 unmodified lines
380381There is also a utility function in the lexer module that can count newline382characters in strings:383384.. autofunction:: jinja2.lexer.count_newlines384.. autofunction:: jinja.lexer.count_newlines385386387AST388~~~
5 unmodified lines
394395The list below describes all nodes that are currently available. The AST may396change between Jinja versions but will stay backwards compatible.397398For more information have a look at the repr of :meth:`jinja2.Environment.parse`.398For more information have a look at the repr of :meth:`jinja.Environment.parse`.399400.. module:: jinja2.nodes400.. module:: jinja.nodes401402.. jinja:nodes:: jinja2.nodes.Node402.. jinja:nodes:: jinja.nodes.Node403404.. autoexception:: Impossible
modified:docs/faq.rst+1 added-1 removed
143 unmodified lines
144 from google.appengine.tools.devappserver2.python import sandbox145 sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']146147Credit for this snippet goes to `Thomas Johansson148<https://stackoverflow.com/questions/3086091/debug-jinja2-in-google-app-engine/3694434#3694434>`_148<https://stackoverflow.com/a/3694434>`_149150Why is there no Python 2.3/2.4/2.5/2.6/3.1/3.2/3.3 support?151-----------------------------------------------------------152
43 unmodified lines
modified:docs/integration.rst+4 added-4 removed
12 unmodified lines
13Babel Integration14-----------------1516Jinja provides support for extracting gettext messages from templates via a17`Babel`_ extractor entry point called `jinja2.ext.babel_extract`. The Babel17`Babel`_ extractor entry point called `jinja.ext.babel_extract`. The Babel18support is implemented as part of the :ref:`i18n-extension` extension.1920Gettext messages extracted from both `trans` tags and code expressions.21
1 unmodified line
23in its Babel extraction method `mapping file`_:2425.. sourcecode:: ini2627 [jinja2: **/templates/**.html]27 [jinja: **/templates/**.html]28 encoding = utf-82930The syntax related options of the :class:`Environment` are also available as31configuration values in the mapping file. For example to tell the extraction32that templates use ``%`` as `line_statement_prefix` you can use this code:3334.. sourcecode:: ini3536 [jinja2: **/templates/**.html]36 [jinja: **/templates/**.html]37 encoding = utf-838 line_statement_prefix = %3940:ref:`jinja-extensions` may also be defined by passing a comma separated list
19 unmodified lines
6061The template engine is configured in `config/environment.py`. The configuration62for Jinja looks something like that::6364 from jinja2 import Environment, PackageLoader64 from jinja import Environment, PackageLoader65 config['pylons.app_globals'].jinja_env = Environment(66 loader=PackageLoader('yourapplication', 'templates')67 )68
38 unmodified lines
modified:docs/intro.rst+12 added-34 removed
7 unmodified lines
8Django, you should feel right at home with Jinja. It's both designer and9developer friendly by sticking to Python's principles and adding functionality10useful for templating environments.111213Prerequisites14-------------1515Jinja works with Python 2.7.x and >= 3.5. If you are using Python163.2 you can use an older release of Jinja (2.6) as support for Python 3.217was dropped in Jinja version 2.7. The last release which supported Python 2.618and 3.3 was Jinja 2.10.16Jinja works with Python >= 3.5 and 2.7.1720If you wish to use the :class:`~jinja2.PackageLoader` class, you will also21need `setuptools`_ or `distribute`_ installed at runtime.18Jinja depends on `MarkupSafe`_. If you install via ``pip`` it will be19installed automatically.2021.. _MarkupSafe: https://markupsafe.palletsprojects.com/222324Installation25------------2627You can install the most recent Jinja version using `pip`_::2828 pip install Jinja229 pip install Jinja3031This will install Jinja in your Python installation's site-packages directory.3232Installing the development version33~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~34351. Install `git`_362. ``git clone git://github.com/pallets/jinja.git``373. ``cd jinja2``384. ``ln -s jinja2 /usr/lib/python2.X/site-packages``3940As an alternative to steps 4 you can also do ``python setup.py develop``41which will install the package via `distribute` in development mode. This also42has the advantage that the C extensions are compiled.4344.. _distribute: https://pypi.org/project/distribute/45.. _setuptools: https://pypi.org/project/setuptools/33.. _pip: https://pypi.org/project/pip/47.. _git: https://git-scm.com/343550MarkupSafe Dependency51~~~~~~~~~~~~~~~~~~~~~5253As of version 2.7 Jinja depends on the `MarkupSafe`_ module. If you install54Jinja via ``pip`` it will be installed automatically for you.5556.. _MarkupSafe: https://markupsafe.palletsprojects.com/5736Basic API Usage37---------------3839This section gives you a brief introduction to the Python API for Jinja40templates.4142The most basic way to create a template and render it is through65:class:`~jinja2.Template`. This however is not the recommended way to43:class:`~jinja.Template`. This however is not the recommended way to44work with it if your templates are not loaded from strings but the file45system or another data source:4669>>> from jinja2 import Template47>>> from jinja import Template48>>> template = Template('Hello {{ name }}!')49>>> template.render(name='John Doe')50u'Hello John Doe!'5174By creating an instance of :class:`~jinja2.Template` you get back a new template75object that provides a method called :meth:`~jinja2.Template.render` which when52By creating an instance of :class:`~jinja.Template` you get back a new template53object that provides a method called :meth:`~jinja.Template.render` which when54called with a dict or keyword arguments expands the template. The dict55or keywords arguments passed to the template are the so-called "context"56of the template.57
3 unmodified lines
modified:docs/nativetypes.rst+2 added-2 removed
1.. module:: jinja2.nativetypes1.. module:: jinja.nativetypes23.. _nativetypes:45Native Python Types6===================78The default :class:`~jinja2.Environment` renders templates to strings. With8The default :class:`~jinja.Environment` renders templates to strings. With9:class:`NativeEnvironment`, rendering a template produces a native Python type.10This is useful if you are using Jinja outside the context of creating text11files. For example, your code may have an intermediate step where users may use12templates to define values that will then be passed to a traditional string
52 unmodified lines
modified:docs/sandbox.rst+2 added-2 removed
15 unmodified lines
1617API18---1920.. module:: jinja2.sandbox20.. module:: jinja.sandbox2122.. autoclass:: SandboxedEnvironment([options])23 :members: is_safe_attribute, is_safe_callable, default_binop_table,24 default_unop_table, intercepted_binops, intercepted_unops,
51 unmodified lines
7677This example shows how the power (``**``) operator can be disabled in78Jinja::7980 from jinja2.sandbox import SandboxedEnvironment80 from jinja.sandbox import SandboxedEnvironment818283 class MyEnvironment(SandboxedEnvironment):84 intercepted_binops = frozenset(['**'])
10 unmodified lines
modified:docs/templates.rst+4 added-4 removed
1423 unmodified lines
14241425List of Builtin Filters1426-----------------------14271428.. jinja:filters:: jinja2.defaults.DEFAULT_FILTERS1428.. jinja:filters:: jinja.defaults.DEFAULT_FILTERS142914301431.. _builtin-tests:14321433List of Builtin Tests1434---------------------14351436.. jinja:tests:: jinja2.defaults.DEFAULT_TESTS1436.. jinja:tests:: jinja.defaults.DEFAULT_TESTS143714381439.. _builtin-globals:1440
289 unmodified lines
1730 <pre>{% debug %}</pre>17311732.. code-block:: text17331734 {'context': {'cycler': <class 'jinja2.utils.Cycler'>,1734 {'context': {'cycler': <class 'jinja.utils.Cycler'>,1735 ...,1736 'namespace': <class 'jinja2.utils.Namespace'>},1736 'namespace': <class 'jinja.utils.Namespace'>},1737 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',1738 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],1739 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',1740 ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}
80 unmodified lines
modified:examples/basic/cycle.py+1 added-1 removed
1from __future__ import print_function23from jinja2 import Environment3from jinja import Environment45env = Environment(6 line_statement_prefix="#", variable_start_string="${", variable_end_string="}"7)
11 unmodified lines
modified:examples/basic/debugger.py+2 added-2 removed
1from __future__ import print_function23from jinja2 import Environment4from jinja2.loaders import FileSystemLoader3from jinja import Environment4from jinja.loaders import FileSystemLoader56env = Environment(loader=FileSystemLoader("templates"))7tmpl = env.get_template("broken.html")8print(tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1]))
modified:examples/basic/inheritance.py+2 added-2 removed
1from __future__ import print_function23from jinja2 import Environment4from jinja2.loaders import DictLoader3from jinja import Environment4from jinja.loaders import DictLoader56env = Environment(7 loader=DictLoader(8 {
7 unmodified lines
modified:examples/basic/test_filter_and_linestatements.py+1 added-1 removed
1from __future__ import print_function23from jinja2 import Environment3from jinja import Environment45env = Environment(6 line_statement_prefix="%", variable_start_string="${", variable_end_string="}"7)
22 unmodified lines
modified:examples/basic/test_loop_filter.py+1 added-1 removed
1from __future__ import print_function23from jinja2 import Environment3from jinja import Environment45tmpl = Environment().from_string(6 """\7<ul>
8 unmodified lines
modified:examples/basic/test.py+2 added-2 removed
1from __future__ import print_function23from jinja2 import Environment4from jinja2.loaders import DictLoader3from jinja import Environment4from jinja.loaders import DictLoader56env = Environment(7 loader=DictLoader(8 {
23 unmodified lines
modified:examples/basic/translate.py+2 added-2 removed
1from __future__ import print_function23from jinja2 import Environment3from jinja import Environment45env = Environment(extensions=["jinja2.ext.i18n"])5env = Environment(extensions=["jinja.ext.i18n"])6env.globals["gettext"] = {"Hello %(user)s!": "Hallo %(user)s!"}.__getitem__7env.globals["ngettext"] = lambda s, p, n: {8 "%(count)s user": "%(count)d Benutzer",9 "%(count)s users": "%(count)d Benutzer",
11 unmodified lines
added:jinja2-compat/src/jinja2/__init__.py+21 added
1def _export_jinja(name, ns):2 import warnings3 from importlib import import_module45 mod_name = "jinja" if not name else ("jinja." + name)6 warnings.warn(7 "'jinja2' has been renamed to 'jinja'. Import from %r instead." % mod_name,8 DeprecationWarning,9 stacklevel=3,10 )11 mod = import_module(mod_name)1213 for key, value in vars(mod).items():14 if not key.startswith("__") or key == "__version__":15 ns[key] = value1617 if name:18 ns.pop("_export_jinja")192021_export_jinja(None, globals())
added:jinja2-compat/src/jinja2/_compat.py+3 added
1from . import _export_jinja23_export_jinja("_compat", globals())
added:jinja2-compat/src/jinja2/_identifier.py+3 added
1from . import _export_jinja23_export_jinja("_identifier", globals())
added:jinja2-compat/src/jinja2/asyncfilters.py+3 added
1from . import _export_jinja23_export_jinja("asyncfilters", globals())
added:jinja2-compat/src/jinja2/asyncsupport.py+3 added
1from . import _export_jinja23_export_jinja("asyncsupport", globals())
added:jinja2-compat/src/jinja2/bccache.py+3 added
1from . import _export_jinja23_export_jinja("bccache", globals())
added:jinja2-compat/src/jinja2/compiler.py+3 added
1from . import _export_jinja23_export_jinja("compiler", globals())
added:jinja2-compat/src/jinja2/constants.py+3 added
1from . import _export_jinja23_export_jinja("constants", globals())
added:jinja2-compat/src/jinja2/debug.py+3 added
1from . import _export_jinja23_export_jinja("debug", globals())
added:jinja2-compat/src/jinja2/defaults.py+3 added
1from . import _export_jinja23_export_jinja("defaults", globals())
added:jinja2-compat/src/jinja2/environment.py+3 added
1from . import _export_jinja23_export_jinja("environment", globals())
added:jinja2-compat/src/jinja2/exceptions.py+3 added
1from . import _export_jinja23_export_jinja("exceptions", globals())
added:jinja2-compat/src/jinja2/ext.py+3 added
1from . import _export_jinja23_export_jinja("ext", globals())
added:jinja2-compat/src/jinja2/filters.py+3 added
1from . import _export_jinja23_export_jinja("filters", globals())
added:jinja2-compat/src/jinja2/idtracking.py+3 added
1from . import _export_jinja23_export_jinja("idtracking", globals())
added:jinja2-compat/src/jinja2/lexer.py+3 added
1from . import _export_jinja23_export_jinja("lexer", globals())
added:jinja2-compat/src/jinja2/loaders.py+3 added
1from . import _export_jinja23_export_jinja("loaders", globals())
added:jinja2-compat/src/jinja2/meta.py+3 added
1from . import _export_jinja23_export_jinja("meta", globals())
added:jinja2-compat/src/jinja2/nativetypes.py+3 added
1from . import _export_jinja23_export_jinja("nativetypes", globals())
added:jinja2-compat/src/jinja2/nodes.py+3 added
1from . import _export_jinja23_export_jinja("nodes", globals())
added:jinja2-compat/src/jinja2/optimizer.py+3 added
1from . import _export_jinja23_export_jinja("optimizer", globals())
added:jinja2-compat/src/jinja2/parser.py+3 added
1from . import _export_jinja23_export_jinja("parser", globals())
added:jinja2-compat/src/jinja2/runtime.py+3 added
1from . import _export_jinja23_export_jinja("runtime", globals())
added:jinja2-compat/src/jinja2/sandbox.py+3 added
1from . import _export_jinja23_export_jinja("sandbox", globals())
added:jinja2-compat/src/jinja2/tests.py+3 added
1from . import _export_jinja23_export_jinja("tests", globals())
added:jinja2-compat/src/jinja2/utils.py+3 added
1from . import _export_jinja23_export_jinja("utils", globals())
added:jinja2-compat/src/jinja2/visitor.py+3 added
1from . import _export_jinja23_export_jinja("visitor", globals())
added:jinja2-compat/LICENSE.rst+28 added
1Copyright 2007 Pallets23Redistribution and use in source and binary forms, with or without4modification, are permitted provided that the following conditions are5met:671. Redistributions of source code must retain the above copyright8 notice, this list of conditions and the following disclaimer.9102. Redistributions in binary form must reproduce the above copyright11 notice, this list of conditions and the following disclaimer in the12 documentation and/or other materials provided with the distribution.13143. Neither the name of the copyright holder nor the names of its15 contributors may be used to endorse or promote products derived from16 this software without specific prior written permission.1718THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS19"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT20LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A21PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT22HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,23SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED24TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR25PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF26LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING27NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS28SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
added:jinja2-compat/MANIFEST.in+1 added
1global-exclude *.pyc
added:jinja2-compat/README.rst+9 added
1The Jinja2 package has been renamed to `Jinja`_. This package provides2compatibility while projects transition to the new name. Imports from3``jinja2`` will be redirected to ``jinja`` and a deprecation warning4will be emitted.56Projects are advised to require 'Jinja' instead of 'Jinja2' and replace7all imports of ``jinja2`` with ``jinja`` to continue receiving updates.89.. _Jinja: https://pypi.org/project/Jinja/
added:jinja2-compat/setup.cfg+5 added
1[metadata]2license_file = LICENSE.rst34[bdist_wheel]5universal = true
added:jinja2-compat/setup.py+53 added
1import io23from setuptools import find_packages4from setuptools import setup56with io.open("README.rst", "rt", encoding="utf8") as f:7 readme = f.read()89setup(10 name="Jinja2",11 version="2.11.0rc1",12 url="https://palletsprojects.com/p/jinja/",13 project_urls={14 "Documentation": "https://jinja.palletsprojects.com/",15 "Code": "https://github.com/pallets/jinja",16 "Issue tracker": "https://github.com/pallets/jinja/issues",17 },18 license="BSD-3-Clause",19 maintainer="Pallets",20 maintainer_email="contact@palletsprojects.com",21 description=(22 "A very fast and expressive template engine. Compatibility"23 " package for Jinja2 to Jinja rename."24 ),25 long_description=readme,26 classifiers=[27 "Development Status :: 5 - Production/Stable",28 "Environment :: Web Environment",29 "Intended Audience :: Developers",30 "License :: OSI Approved :: BSD License",31 "Operating System :: OS Independent",32 "Programming Language :: Python",33 "Programming Language :: Python :: 2",34 "Programming Language :: Python :: 2.7",35 "Programming Language :: Python :: 3",36 "Programming Language :: Python :: 3.5",37 "Programming Language :: Python :: 3.6",38 "Programming Language :: Python :: 3.7",39 "Programming Language :: Python :: 3.8",40 "Programming Language :: Python :: Implementation :: CPython",41 "Programming Language :: Python :: Implementation :: PyPy",42 "Topic :: Internet :: WWW/HTTP :: Dynamic Content",43 "Topic :: Software Development :: Libraries :: Python Modules",44 "Topic :: Text Processing :: Markup :: HTML",45 ],46 packages=find_packages("src"),47 package_dir={"": "src"},48 include_package_data=True,49 python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",50 install_requires=["Jinja<4.0"],51 extras_require={"i18n": ["Babel>=0.8"]},52 entry_points={"babel.extractors": ["jinja2 = jinja2.ext:babel_extract[i18n]"]},53)
modified:scripts/generate_identifier_pattern.py+2 added-4 removed
56 unmodified lines
57 return "".join(out)585960def main():61 """Build the regex pattern and write it to62 ``jinja2/_identifier.py``.63 """61 """Build the regex pattern and write it to ``_identifier.py``."""62 pattern = build_pattern(collapse_ranges(get_characters()))63 filename = os.path.abspath(66 os.path.join(os.path.dirname(__file__), "..", "src", "jinja2", "_identifier.py")64 os.path.join(os.path.dirname(__file__), "..", "src", "jinja", "_identifier.py")65 )6667 with open(filename, "w", encoding="utf8") as f:68 f.write("import re\n\n")
8 unmodified lines
added:src/jinja/__init__.py+43 added
1# -*- coding: utf-8 -*-2"""Jinja is a template engine written in pure Python. It provides a3non-XML syntax that supports inline expressions and an optional4sandboxed environment.5"""6from .bccache import BytecodeCache7from .bccache import FileSystemBytecodeCache8from .bccache import MemcachedBytecodeCache9from .environment import Environment10from .environment import Template11from .exceptions import TemplateAssertionError12from .exceptions import TemplateError13from .exceptions import TemplateNotFound14from .exceptions import TemplateRuntimeError15from .exceptions import TemplatesNotFound16from .exceptions import TemplateSyntaxError17from .exceptions import UndefinedError18from .filters import contextfilter19from .filters import environmentfilter20from .filters import evalcontextfilter21from .loaders import BaseLoader22from .loaders import ChoiceLoader23from .loaders import DictLoader24from .loaders import FileSystemLoader25from .loaders import FunctionLoader26from .loaders import ModuleLoader27from .loaders import PackageLoader28from .loaders import PrefixLoader29from .runtime import ChainableUndefined30from .runtime import DebugUndefined31from .runtime import make_logging_undefined32from .runtime import StrictUndefined33from .runtime import Undefined34from .utils import clear_caches35from .utils import contextfunction36from .utils import environmentfunction37from .utils import escape38from .utils import evalcontextfunction39from .utils import is_undefined40from .utils import Markup41from .utils import select_autoescape4243__version__ = "2.11.0rc1"
added:src/jinja/_compat.py+132 added
1# -*- coding: utf-8 -*-2# flake8: noqa3import marshal4import sys56PY2 = sys.version_info[0] == 27PYPY = hasattr(sys, "pypy_translation_info")8_identity = lambda x: x910if not PY2:11 unichr = chr12 range_type = range13 text_type = str14 string_types = (str,)15 integer_types = (int,)1617 iterkeys = lambda d: iter(d.keys())18 itervalues = lambda d: iter(d.values())19 iteritems = lambda d: iter(d.items())2021 import pickle22 from io import BytesIO, StringIO2324 NativeStringIO = StringIO2526 def reraise(tp, value, tb=None):27 if value.__traceback__ is not tb:28 raise value.with_traceback(tb)29 raise value3031 ifilter = filter32 imap = map33 izip = zip34 intern = sys.intern3536 implements_iterator = _identity37 implements_to_string = _identity38 encode_filename = _identity3940 marshal_dump = marshal.dump41 marshal_load = marshal.load4243else:44 unichr = unichr45 text_type = unicode46 range_type = xrange47 string_types = (str, unicode)48 integer_types = (int, long)4950 iterkeys = lambda d: d.iterkeys()51 itervalues = lambda d: d.itervalues()52 iteritems = lambda d: d.iteritems()5354 import cPickle as pickle55 from cStringIO import StringIO as BytesIO, StringIO5657 NativeStringIO = BytesIO5859 exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")6061 from itertools import imap, izip, ifilter6263 intern = intern6465 def implements_iterator(cls):66 cls.next = cls.__next__67 del cls.__next__68 return cls6970 def implements_to_string(cls):71 cls.__unicode__ = cls.__str__72 cls.__str__ = lambda x: x.__unicode__().encode("utf-8")73 return cls7475 def encode_filename(filename):76 if isinstance(filename, unicode):77 return filename.encode("utf-8")78 return filename7980 def marshal_dump(code, f):81 if isinstance(f, file):82 marshal.dump(code, f)83 else:84 f.write(marshal.dumps(code))8586 def marshal_load(f):87 if isinstance(f, file):88 return marshal.load(f)89 return marshal.loads(f.read())909192def with_metaclass(meta, *bases):93 """Create a base class with a metaclass."""94 # This requires a bit of explanation: the basic idea is to make a95 # dummy metaclass for one level of class instantiation that replaces96 # itself with the actual metaclass.97 class metaclass(type):98 def __new__(cls, name, this_bases, d):99 return meta(name, bases, d)100101 return type.__new__(metaclass, "temporary_class", (), {})102103104try:105 from urllib.parse import quote_from_bytes as url_quote106except ImportError:107 from urllib import quote as url_quote108109110try:111 from collections import abc112except ImportError:113 import collections as abc114115116try:117 from os import fspath118except ImportError:119 try:120 from pathlib import PurePath121 except ImportError:122 PurePath = None123124 def fspath(path):125 if hasattr(path, "__fspath__"):126 return path.__fspath__()127128 # Python 3.5 doesn't have __fspath__ yet, use str.129 if PurePath is not None and isinstance(path, PurePath):130 return str(path)131132 return path
added:src/jinja/_identifier.py+6 added
1import re23# generated by scripts/generate_identifier_pattern.py4pattern = re.compile(5 r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఃా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑅳𑄴𑆀-𑆂𑆳-𑇊𑇀-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B9506)
added:src/jinja/asyncfilters.py+159 added
1from functools import wraps23from . import filters4from .asyncsupport import auto_aiter5from .asyncsupport import auto_await678async def auto_to_seq(value):9 seq = []10 if hasattr(value, "__aiter__"):11 async for item in value:12 seq.append(item)13 else:14 for item in value:15 seq.append(item)16 return seq171819async def async_select_or_reject(args, kwargs, modfunc, lookup_attr):20 seq, func = filters.prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)21 if seq:22 async for item in auto_aiter(seq):23 if func(item):24 yield item252627def dualfilter(normal_filter, async_filter):28 wrap_evalctx = False29 if getattr(normal_filter, "environmentfilter", False):3031 def is_async(args):32 return args[0].is_async3334 wrap_evalctx = False35 else:36 if not getattr(normal_filter, "evalcontextfilter", False) and not getattr(37 normal_filter, "contextfilter", False38 ):39 wrap_evalctx = True4041 def is_async(args):42 return args[0].environment.is_async4344 @wraps(normal_filter)45 def wrapper(*args, **kwargs):46 b = is_async(args)47 if wrap_evalctx:48 args = args[1:]49 if b:50 return async_filter(*args, **kwargs)51 return normal_filter(*args, **kwargs)5253 if wrap_evalctx:54 wrapper.evalcontextfilter = True5556 wrapper.asyncfiltervariant = True5758 return wrapper596061def asyncfiltervariant(original):62 def decorator(f):63 return dualfilter(original, f)6465 return decorator666768@asyncfiltervariant(filters.do_first)69async def do_first(environment, seq):70 try:71 return await auto_aiter(seq).__anext__()72 except StopAsyncIteration:73 return environment.undefined("No first item, sequence was empty.")747576@asyncfiltervariant(filters.do_groupby)77async def do_groupby(environment, value, attribute):78 expr = filters.make_attrgetter(environment, attribute)79 return [80 filters._GroupTuple(key, await auto_to_seq(values))81 for key, values in filters.groupby(82 sorted(await auto_to_seq(value), key=expr), expr83 )84 ]858687@asyncfiltervariant(filters.do_join)88async def do_join(eval_ctx, value, d=u"", attribute=None):89 return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)909192@asyncfiltervariant(filters.do_list)93async def do_list(value):94 return await auto_to_seq(value)959697@asyncfiltervariant(filters.do_reject)98async def do_reject(*args, **kwargs):99 return async_select_or_reject(args, kwargs, lambda x: not x, False)100101102@asyncfiltervariant(filters.do_rejectattr)103async def do_rejectattr(*args, **kwargs):104 return async_select_or_reject(args, kwargs, lambda x: not x, True)105106107@asyncfiltervariant(filters.do_select)108async def do_select(*args, **kwargs):109 return async_select_or_reject(args, kwargs, lambda x: x, False)110111112@asyncfiltervariant(filters.do_selectattr)113async def do_selectattr(*args, **kwargs):114 return async_select_or_reject(args, kwargs, lambda x: x, True)115116117@asyncfiltervariant(filters.do_map)118async def do_map(*args, **kwargs):119 seq, func = filters.prepare_map(args, kwargs)120 if seq:121 async for item in auto_aiter(seq):122 yield await auto_await(func(item))123124125@asyncfiltervariant(filters.do_sum)126async def do_sum(environment, iterable, attribute=None, start=0):127 rv = start128 if attribute is not None:129 func = filters.make_attrgetter(environment, attribute)130 else:131132 def func(x):133 return x134135 async for item in auto_aiter(iterable):136 rv += func(item)137 return rv138139140@asyncfiltervariant(filters.do_slice)141async def do_slice(value, slices, fill_with=None):142 return filters.do_slice(await auto_to_seq(value), slices, fill_with)143144145ASYNC_FILTERS = {146 "first": do_first,147 "groupby": do_groupby,148 "join": do_join,149 "list": do_list,150 # we intentionally do not support do_last because that would be151 # ridiculous152 "reject": do_reject,153 "rejectattr": do_rejectattr,154 "map": do_map,155 "select": do_select,156 "selectattr": do_selectattr,157 "sum": do_sum,158 "slice": do_slice,159}
added:src/jinja/asyncsupport.py+263 added
1# -*- coding: utf-8 -*-2"""The code for async support. Importing this patches Jinja on supported3Python versions.4"""5import asyncio6import inspect7from functools import update_wrapper89from .environment import TemplateModule10from .runtime import LoopContext11from .utils import concat12from .utils import internalcode13from .utils import Markup14from .utils import missing151617async def concat_async(async_gen):18 rv = []1920 async def collect():21 async for event in async_gen:22 rv.append(event)2324 await collect()25 return concat(rv)262728async def generate_async(self, *args, **kwargs):29 vars = dict(*args, **kwargs)30 try:31 async for event in self.root_render_func(self.new_context(vars)):32 yield event33 except Exception:34 yield self.environment.handle_exception()353637def wrap_generate_func(original_generate):38 def _convert_generator(self, loop, args, kwargs):39 async_gen = self.generate_async(*args, **kwargs)40 try:41 while 1:42 yield loop.run_until_complete(async_gen.__anext__())43 except StopAsyncIteration:44 pass4546 def generate(self, *args, **kwargs):47 if not self.environment.is_async:48 return original_generate(self, *args, **kwargs)49 return _convert_generator(self, asyncio.get_event_loop(), args, kwargs)5051 return update_wrapper(generate, original_generate)525354async def render_async(self, *args, **kwargs):55 if not self.environment.is_async:56 raise RuntimeError("The environment was not created with async mode enabled.")5758 vars = dict(*args, **kwargs)59 ctx = self.new_context(vars)6061 try:62 return await concat_async(self.root_render_func(ctx))63 except Exception:64 return self.environment.handle_exception()656667def wrap_render_func(original_render):68 def render(self, *args, **kwargs):69 if not self.environment.is_async:70 return original_render(self, *args, **kwargs)71 loop = asyncio.get_event_loop()72 return loop.run_until_complete(self.render_async(*args, **kwargs))7374 return update_wrapper(render, original_render)757677def wrap_block_reference_call(original_call):78 @internalcode79 async def async_call(self):80 rv = await concat_async(self._stack[self._depth](self._context))81 if self._context.eval_ctx.autoescape:82 rv = Markup(rv)83 return rv8485 @internalcode86 def __call__(self):87 if not self._context.environment.is_async:88 return original_call(self)89 return async_call(self)9091 return update_wrapper(__call__, original_call)929394def wrap_macro_invoke(original_invoke):95 @internalcode96 async def async_invoke(self, arguments, autoescape):97 rv = await self._func(*arguments)98 if autoescape:99 rv = Markup(rv)100 return rv101102 @internalcode103 def _invoke(self, arguments, autoescape):104 if not self._environment.is_async:105 return original_invoke(self, arguments, autoescape)106 return async_invoke(self, arguments, autoescape)107108 return update_wrapper(_invoke, original_invoke)109110111@internalcode112async def get_default_module_async(self):113 if self._module is not None:114 return self._module115 self._module = rv = await self.make_module_async()116 return rv117118119def wrap_default_module(original_default_module):120 @internalcode121 def _get_default_module(self):122 if self.environment.is_async:123 raise RuntimeError("Template module attribute is unavailable in async mode")124 return original_default_module(self)125126 return _get_default_module127128129async def make_module_async(self, vars=None, shared=False, locals=None):130 context = self.new_context(vars, shared, locals)131 body_stream = []132 async for item in self.root_render_func(context):133 body_stream.append(item)134 return TemplateModule(self, context, body_stream)135136137def patch_template():138 from . import Template139140 Template.generate = wrap_generate_func(Template.generate)141 Template.generate_async = update_wrapper(generate_async, Template.generate_async)142 Template.render_async = update_wrapper(render_async, Template.render_async)143 Template.render = wrap_render_func(Template.render)144 Template._get_default_module = wrap_default_module(Template._get_default_module)145 Template._get_default_module_async = get_default_module_async146 Template.make_module_async = update_wrapper(147 make_module_async, Template.make_module_async148 )149150151def patch_runtime():152 from .runtime import BlockReference, Macro153154 BlockReference.__call__ = wrap_block_reference_call(BlockReference.__call__)155 Macro._invoke = wrap_macro_invoke(Macro._invoke)156157158def patch_filters():159 from .filters import FILTERS160 from .asyncfilters import ASYNC_FILTERS161162 FILTERS.update(ASYNC_FILTERS)163164165def patch_all():166 patch_template()167 patch_runtime()168 patch_filters()169170171async def auto_await(value):172 if inspect.isawaitable(value):173 return await value174 return value175176177async def auto_aiter(iterable):178 if hasattr(iterable, "__aiter__"):179 async for item in iterable:180 yield item181 return182 for item in iterable:183 yield item184185186class AsyncLoopContext(LoopContext):187 _to_iterator = staticmethod(auto_aiter)188189 @property190 async def length(self):191 if self._length is not None:192 return self._length193194 try:195 self._length = len(self._iterable)196 except TypeError:197 iterable = [x async for x in self._iterator]198 self._iterator = self._to_iterator(iterable)199 self._length = len(iterable) + self.index + (self._after is not missing)200201 return self._length202203 @property204 async def revindex0(self):205 return await self.length - self.index206207 @property208 async def revindex(self):209 return await self.length - self.index0210211 async def _peek_next(self):212 if self._after is not missing:213 return self._after214215 try:216 self._after = await self._iterator.__anext__()217 except StopAsyncIteration:218 self._after = missing219220 return self._after221222 @property223 async def last(self):224 return await self._peek_next() is missing225226 @property227 async def nextitem(self):228 rv = await self._peek_next()229230 if rv is missing:231 return self._undefined("there is no next item")232233 return rv234235 def __aiter__(self):236 return self237238 async def __anext__(self):239 if self._after is not missing:240 rv = self._after241 self._after = missing242 else:243 rv = await self._iterator.__anext__()244245 self.index0 += 1246 self._before = self._current247 self._current = rv248 return rv, self249250251async def make_async_loop_context(iterable, undefined, recurse=None, depth0=0):252 import warnings253254 warnings.warn(255 "This template must be recompiled with at least Jinja 2.11, or"256 " it will fail in 3.0.",257 DeprecationWarning,258 stacklevel=2,259 )260 return AsyncLoopContext(iterable, undefined, recurse, depth0)261262263patch_all()
added:src/jinja/bccache.py+358 added
1# -*- coding: utf-8 -*-2"""The optional bytecode cache system. This is useful if you have very3complex template situations and the compilation of all those templates4slows down your application too much.56Situations where this is useful are often forking web applications that7are initialized on the first request.8"""9import errno10import fnmatch11import os12import stat13import sys14import tempfile15from hashlib import sha116from os import listdir17from os import path1819from ._compat import BytesIO20from ._compat import marshal_dump21from ._compat import marshal_load22from ._compat import pickle23from ._compat import text_type24from .utils import open_if_exists2526bc_version = 427# Magic bytes to identify Jinja bytecode cache files. Contains the28# Python major and minor version to avoid loading incompatible bytecode29# if a project upgrades its Python version.30bc_magic = (31 b"jinja"32 + pickle.dumps(bc_version, 2)33 + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2)34)353637class Bucket(object):38 """Buckets are used to store the bytecode for one template. It's created39 and initialized by the bytecode cache and passed to the loading functions.4041 The buckets get an internal checksum from the cache assigned and use this42 to automatically reject outdated cache material. Individual bytecode43 cache subclasses don't have to care about cache invalidation.44 """4546 def __init__(self, environment, key, checksum):47 self.environment = environment48 self.key = key49 self.checksum = checksum50 self.reset()5152 def reset(self):53 """Resets the bucket (unloads the bytecode)."""54 self.code = None5556 def load_bytecode(self, f):57 """Loads bytecode from a file or file like object."""58 # make sure the magic header is correct59 magic = f.read(len(bc_magic))60 if magic != bc_magic:61 self.reset()62 return63 # the source code of the file changed, we need to reload64 checksum = pickle.load(f)65 if self.checksum != checksum:66 self.reset()67 return68 # if marshal_load fails then we need to reload69 try:70 self.code = marshal_load(f)71 except (EOFError, ValueError, TypeError):72 self.reset()73 return7475 def write_bytecode(self, f):76 """Dump the bytecode into the file or file like object passed."""77 if self.code is None:78 raise TypeError("can't write empty bucket")79 f.write(bc_magic)80 pickle.dump(self.checksum, f, 2)81 marshal_dump(self.code, f)8283 def bytecode_from_string(self, string):84 """Load bytecode from a string."""85 self.load_bytecode(BytesIO(string))8687 def bytecode_to_string(self):88 """Return the bytecode as string."""89 out = BytesIO()90 self.write_bytecode(out)91 return out.getvalue()929394class BytecodeCache(object):95 """To implement your own bytecode cache you have to subclass this class96 and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of97 these methods are passed a :class:`Bucket`.9899 A very basic bytecode cache that saves the bytecode on the file system::100101 from os import path102103 class MyCache(BytecodeCache):104105 def __init__(self, directory):106 self.directory = directory107108 def load_bytecode(self, bucket):109 filename = path.join(self.directory, bucket.key)110 if path.exists(filename):111 with open(filename, 'rb') as f:112 bucket.load_bytecode(f)113114 def dump_bytecode(self, bucket):115 filename = path.join(self.directory, bucket.key)116 with open(filename, 'wb') as f:117 bucket.write_bytecode(f)118119 A more advanced version of a filesystem based bytecode cache is part of120 Jinja.121 """122123 def load_bytecode(self, bucket):124 """Subclasses have to override this method to load bytecode into a125 bucket. If they are not able to find code in the cache for the126 bucket, it must not do anything.127 """128 raise NotImplementedError()129130 def dump_bytecode(self, bucket):131 """Subclasses have to override this method to write the bytecode132 from a bucket back to the cache. If it unable to do so it must not133 fail silently but raise an exception.134 """135 raise NotImplementedError()136137 def clear(self):138 """Clears the cache. This method is not used by Jinja but should be139 implemented to allow applications to clear the bytecode cache used140 by a particular environment.141 """142143 def get_cache_key(self, name, filename=None):144 """Returns the unique hash key for this template name."""145 hash = sha1(name.encode("utf-8"))146 if filename is not None:147 filename = "|" + filename148 if isinstance(filename, text_type):149 filename = filename.encode("utf-8")150 hash.update(filename)151 return hash.hexdigest()152153 def get_source_checksum(self, source):154 """Returns a checksum for the source."""155 return sha1(source.encode("utf-8")).hexdigest()156157 def get_bucket(self, environment, name, filename, source):158 """Return a cache bucket for the given template. All arguments are159 mandatory but filename may be `None`.160 """161 key = self.get_cache_key(name, filename)162 checksum = self.get_source_checksum(source)163 bucket = Bucket(environment, key, checksum)164 self.load_bytecode(bucket)165 return bucket166167 def set_bucket(self, bucket):168 """Put the bucket into the cache."""169 self.dump_bytecode(bucket)170171172class FileSystemBytecodeCache(BytecodeCache):173 """A bytecode cache that stores bytecode on the filesystem. It accepts174 two arguments: The directory where the cache items are stored and a175 pattern string that is used to build the filename.176177 If no directory is specified a default cache directory is selected. On178 Windows the user's temp directory is used, on UNIX systems a directory179 is created for the user in the system temp directory.180181 The pattern can be used to have multiple separate caches operate on the182 same directory. The default pattern is ``'__jinja_%s.cache'``. ``%s``183 is replaced with the cache key.184185 >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')186187 This bytecode cache supports clearing of the cache using the clear method.188189 .. versionchanged:; 2.11190 The default cache directory was renamed to191 ``_jinja-cache-{uid}``. The default filename pattern was renamed192 to ``__jinja_%s.cache``.193 """194195 def __init__(self, directory=None, pattern="__jinja_%s.cache"):196 if directory is None:197 directory = self._get_default_cache_dir()198 self.directory = directory199 self.pattern = pattern200201 def _get_default_cache_dir(self):202 def _unsafe_dir():203 raise RuntimeError(204 "Cannot determine safe temp directory. You "205 "need to explicitly provide one."206 )207208 tmpdir = tempfile.gettempdir()209210 # On windows the temporary directory is used specific unless211 # explicitly forced otherwise. We can just use that.212 if os.name == "nt":213 return tmpdir214 if not hasattr(os, "getuid"):215 _unsafe_dir()216217 dirname = "_jinja-cache-%d" % os.getuid()218 actual_dir = os.path.join(tmpdir, dirname)219220 try:221 os.mkdir(actual_dir, stat.S_IRWXU)222 except OSError as e:223 if e.errno != errno.EEXIST:224 raise225 try:226 os.chmod(actual_dir, stat.S_IRWXU)227 actual_dir_stat = os.lstat(actual_dir)228 if (229 actual_dir_stat.st_uid != os.getuid()230 or not stat.S_ISDIR(actual_dir_stat.st_mode)231 or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU232 ):233 _unsafe_dir()234 except OSError as e:235 if e.errno != errno.EEXIST:236 raise237238 actual_dir_stat = os.lstat(actual_dir)239 if (240 actual_dir_stat.st_uid != os.getuid()241 or not stat.S_ISDIR(actual_dir_stat.st_mode)242 or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU243 ):244 _unsafe_dir()245246 return actual_dir247248 def _get_cache_filename(self, bucket):249 return path.join(self.directory, self.pattern % bucket.key)250251 def load_bytecode(self, bucket):252 f = open_if_exists(self._get_cache_filename(bucket), "rb")253 if f is not None:254 try:255 bucket.load_bytecode(f)256 finally:257 f.close()258259 def dump_bytecode(self, bucket):260 f = open(self._get_cache_filename(bucket), "wb")261 try:262 bucket.write_bytecode(f)263 finally:264 f.close()265266 def clear(self):267 # imported lazily here because google app-engine doesn't support268 # write access on the file system and the function does not exist269 # normally.270 from os import remove271272 files = fnmatch.filter(listdir(self.directory), self.pattern % "*")273 for filename in files:274 try:275 remove(path.join(self.directory, filename))276 except OSError:277 pass278279280class MemcachedBytecodeCache(BytecodeCache):281 """This class implements a bytecode cache that uses a memcache cache for282 storing the information. It does not enforce a specific memcache library283 (tummy's memcache or cmemcache) but will accept any class that provides284 the minimal interface required.285286 Libraries compatible with this class:287288 - `cachelib <https://github.com/pallets/cachelib>`_289 - `python-memcached <https://pypi.org/project/python-memcached/>`_290291 (Unfortunately the django cache interface is not compatible because it292 does not support storing binary data, only unicode. You can however pass293 the underlying cache client to the bytecode cache which is available294 as `django.core.cache.cache._client`.)295296 The minimal interface for the client passed to the constructor is this:297298 .. class:: MinimalClientInterface299300 .. method:: set(key, value[, timeout])301302 Stores the bytecode in the cache. `value` is a string and303 `timeout` the timeout of the key. If timeout is not provided304 a default timeout or no timeout should be assumed, if it's305 provided it's an integer with the number of seconds the cache306 item should exist.307308 .. method:: get(key)309310 Returns the value for the cache key. If the item does not311 exist in the cache the return value must be `None`.312313 The other arguments to the constructor are the prefix for all keys that314 is added before the actual cache key and the timeout for the bytecode in315 the cache system. We recommend a high (or no) timeout.316317 This bytecode cache does not support clearing of used items in the cache.318 The clear method is a no-operation function.319320 .. versionchanged:: 2.11321 The default prefix was renamed to ``jinja/bytecode/``.322323 .. versionchanged:: 2.7324 Added support for ignoring memcache errors through the325 ``ignore_memcache_errors`` parameter.326 """327328 def __init__(329 self,330 client,331 prefix="jinja/bytecode/",332 timeout=None,333 ignore_memcache_errors=True,334 ):335 self.client = client336 self.prefix = prefix337 self.timeout = timeout338 self.ignore_memcache_errors = ignore_memcache_errors339340 def load_bytecode(self, bucket):341 try:342 code = self.client.get(self.prefix + bucket.key)343 except Exception:344 if not self.ignore_memcache_errors:345 raise346 code = None347 if code is not None:348 bucket.bytecode_from_string(code)349350 def dump_bytecode(self, bucket):351 args = (self.prefix + bucket.key, bucket.bytecode_to_string())352 if self.timeout is not None:353 args += (self.timeout,)354 try:355 self.client.set(*args)356 except Exception:357 if not self.ignore_memcache_errors:358 raise
added:src/jinja/compiler.py+1842 added
1# -*- coding: utf-8 -*-2"""Compiles nodes from the parser into Python code."""3from collections import namedtuple4from functools import update_wrapper5from itertools import chain6from keyword import iskeyword as is_python_keyword78from . import nodes9from ._compat import imap10from ._compat import iteritems11from ._compat import izip12from ._compat import NativeStringIO13from ._compat import range_type14from ._compat import string_types15from ._compat import text_type16from .exceptions import TemplateAssertionError17from .idtracking import Symbols18from .idtracking import VAR_LOAD_ALIAS19from .idtracking import VAR_LOAD_PARAMETER20from .idtracking import VAR_LOAD_RESOLVE21from .idtracking import VAR_LOAD_UNDEFINED22from .nodes import EvalContext23from .optimizer import Optimizer24from .utils import concat25from .utils import escape26from .utils import Markup27from .visitor import NodeVisitor2829operators = {30 "eq": "==",31 "ne": "!=",32 "gt": ">",33 "gteq": ">=",34 "lt": "<",35 "lteq": "<=",36 "in": "in",37 "notin": "not in",38}3940# what method to iterate over items do we want to use for dict iteration41# in generated code? on 2.x let's go with iteritems, on 3.x with items42if hasattr(dict, "iteritems"):43 dict_item_iter = "iteritems"44else:45 dict_item_iter = "items"4647code_features = ["division"]4849# does this python version support generator stops? (PEP 0479)50try:51 exec("from __future__ import generator_stop")52 code_features.append("generator_stop")53except SyntaxError:54 pass5556# does this python version support yield from?57try:58 exec("def f(): yield from x()")59except SyntaxError:60 supports_yield_from = False61else:62 supports_yield_from = True636465def optimizeconst(f):66 def new_func(self, node, frame, **kwargs):67 # Only optimize if the frame is not volatile68 if self.optimized and not frame.eval_ctx.volatile:69 new_node = self.optimizer.visit(node, frame.eval_ctx)70 if new_node != node:71 return self.visit(new_node, frame)72 return f(self, node, frame, **kwargs)7374 return update_wrapper(new_func, f)757677def generate(78 node, environment, name, filename, stream=None, defer_init=False, optimized=True79):80 """Generate the python source for a node tree."""81 if not isinstance(node, nodes.Template):82 raise TypeError("Can't compile non template nodes")83 generator = environment.code_generator_class(84 environment, name, filename, stream, defer_init, optimized85 )86 generator.visit(node)87 if stream is None:88 return generator.stream.getvalue()899091def has_safe_repr(value):92 """Does the node have a safe representation?"""93 if value is None or value is NotImplemented or value is Ellipsis:94 return True95 if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:96 return True97 if type(value) in (tuple, list, set, frozenset):98 for item in value:99 if not has_safe_repr(item):100 return False101 return True102 elif type(value) is dict:103 for key, value in iteritems(value):104 if not has_safe_repr(key):105 return False106 if not has_safe_repr(value):107 return False108 return True109 return False110111112def find_undeclared(nodes, names):113 """Check if the names passed are accessed undeclared. The return value114 is a set of all the undeclared names from the sequence of names found.115 """116 visitor = UndeclaredNameVisitor(names)117 try:118 for node in nodes:119 visitor.visit(node)120 except VisitorExit:121 pass122 return visitor.undeclared123124125class MacroRef(object):126 def __init__(self, node):127 self.node = node128 self.accesses_caller = False129 self.accesses_kwargs = False130 self.accesses_varargs = False131132133class Frame(object):134 """Holds compile time information for us."""135136 def __init__(self, eval_ctx, parent=None, level=None):137 self.eval_ctx = eval_ctx138 self.symbols = Symbols(parent and parent.symbols or None, level=level)139140 # a toplevel frame is the root + soft frames such as if conditions.141 self.toplevel = False142143 # the root frame is basically just the outermost frame, so no if144 # conditions. This information is used to optimize inheritance145 # situations.146 self.rootlevel = False147148 # in some dynamic inheritance situations the compiler needs to add149 # write tests around output statements.150 self.require_output_check = parent and parent.require_output_check151152 # inside some tags we are using a buffer rather than yield statements.153 # this for example affects {% filter %} or {% macro %}. If a frame154 # is buffered this variable points to the name of the list used as155 # buffer.156 self.buffer = None157158 # the name of the block we're in, otherwise None.159 self.block = parent and parent.block or None160161 # the parent of this frame162 self.parent = parent163164 if parent is not None:165 self.buffer = parent.buffer166167 def copy(self):168 """Create a copy of the current one."""169 rv = object.__new__(self.__class__)170 rv.__dict__.update(self.__dict__)171 rv.symbols = self.symbols.copy()172 return rv173174 def inner(self, isolated=False):175 """Return an inner frame."""176 if isolated:177 return Frame(self.eval_ctx, level=self.symbols.level + 1)178 return Frame(self.eval_ctx, self)179180 def soft(self):181 """Return a soft frame. A soft frame may not be modified as182 standalone thing as it shares the resources with the frame it183 was created of, but it's not a rootlevel frame any longer.184185 This is only used to implement if-statements.186 """187 rv = self.copy()188 rv.rootlevel = False189 return rv190191 __copy__ = copy192193194class VisitorExit(RuntimeError):195 """Exception used by the `UndeclaredNameVisitor` to signal a stop."""196197198class DependencyFinderVisitor(NodeVisitor):199 """A visitor that collects filter and test calls."""200201 def __init__(self):202 self.filters = set()203 self.tests = set()204205 def visit_Filter(self, node):206 self.generic_visit(node)207 self.filters.add(node.name)208209 def visit_Test(self, node):210 self.generic_visit(node)211 self.tests.add(node.name)212213 def visit_Block(self, node):214 """Stop visiting at blocks."""215216217class UndeclaredNameVisitor(NodeVisitor):218 """A visitor that checks if a name is accessed without being219 declared. This is different from the frame visitor as it will220 not stop at closure frames.221 """222223 def __init__(self, names):224 self.names = set(names)225 self.undeclared = set()226227 def visit_Name(self, node):228 if node.ctx == "load" and node.name in self.names:229 self.undeclared.add(node.name)230 if self.undeclared == self.names:231 raise VisitorExit()232 else:233 self.names.discard(node.name)234235 def visit_Block(self, node):236 """Stop visiting a blocks."""237238239class CompilerExit(Exception):240 """Raised if the compiler encountered a situation where it just241 doesn't make sense to further process the code. Any block that242 raises such an exception is not further processed.243 """244245246class CodeGenerator(NodeVisitor):247 def __init__(248 self, environment, name, filename, stream=None, defer_init=False, optimized=True249 ):250 if stream is None:251 stream = NativeStringIO()252 self.environment = environment253 self.name = name254 self.filename = filename255 self.stream = stream256 self.created_block_context = False257 self.defer_init = defer_init258 self.optimized = optimized259 if optimized:260 self.optimizer = Optimizer(environment)261262 # aliases for imports263 self.import_aliases = {}264265 # a registry for all blocks. Because blocks are moved out266 # into the global python scope they are registered here267 self.blocks = {}268269 # the number of extends statements so far270 self.extends_so_far = 0271272 # some templates have a rootlevel extends. In this case we273 # can safely assume that we're a child template and do some274 # more optimizations.275 self.has_known_extends = False276277 # the current line number278 self.code_lineno = 1279280 # registry of all filters and tests (global, not block local)281 self.tests = {}282 self.filters = {}283284 # the debug information285 self.debug_info = []286 self._write_debug_info = None287288 # the number of new lines before the next write()289 self._new_lines = 0290291 # the line number of the last written statement292 self._last_line = 0293294 # true if nothing was written so far.295 self._first_write = True296297 # used by the `temporary_identifier` method to get new298 # unique, temporary identifier299 self._last_identifier = 0300301 # the current indentation302 self._indentation = 0303304 # Tracks toplevel assignments305 self._assign_stack = []306307 # Tracks parameter definition blocks308 self._param_def_block = []309310 # Tracks the current context.311 self._context_reference_stack = ["context"]312313 # -- Various compilation helpers314315 def fail(self, msg, lineno):316 """Fail with a :exc:`TemplateAssertionError`."""317 raise TemplateAssertionError(msg, lineno, self.name, self.filename)318319 def temporary_identifier(self):320 """Get a new unique identifier."""321 self._last_identifier += 1322 return "t_%d" % self._last_identifier323324 def buffer(self, frame):325 """Enable buffering for the frame from that point onwards."""326 frame.buffer = self.temporary_identifier()327 self.writeline("%s = []" % frame.buffer)328329 def return_buffer_contents(self, frame, force_unescaped=False):330 """Return the buffer contents of the frame."""331 if not force_unescaped:332 if frame.eval_ctx.volatile:333 self.writeline("if context.eval_ctx.autoescape:")334 self.indent()335 self.writeline("return Markup(concat(%s))" % frame.buffer)336 self.outdent()337 self.writeline("else:")338 self.indent()339 self.writeline("return concat(%s)" % frame.buffer)340 self.outdent()341 return342 elif frame.eval_ctx.autoescape:343 self.writeline("return Markup(concat(%s))" % frame.buffer)344 return345 self.writeline("return concat(%s)" % frame.buffer)346347 def indent(self):348 """Indent by one."""349 self._indentation += 1350351 def outdent(self, step=1):352 """Outdent by step."""353 self._indentation -= step354355 def start_write(self, frame, node=None):356 """Yield or write into the frame buffer."""357 if frame.buffer is None:358 self.writeline("yield ", node)359 else:360 self.writeline("%s.append(" % frame.buffer, node)361362 def end_write(self, frame):363 """End the writing process started by `start_write`."""364 if frame.buffer is not None:365 self.write(")")366367 def simple_write(self, s, frame, node=None):368 """Simple shortcut for start_write + write + end_write."""369 self.start_write(frame, node)370 self.write(s)371 self.end_write(frame)372373 def blockvisit(self, nodes, frame):374 """Visit a list of nodes as block in a frame. If the current frame375 is no buffer a dummy ``if 0: yield None`` is written automatically.376 """377 try:378 self.writeline("pass")379 for node in nodes:380 self.visit(node, frame)381 except CompilerExit:382 pass383384 def write(self, x):385 """Write a string into the output stream."""386 if self._new_lines:387 if not self._first_write:388 self.stream.write("\n" * self._new_lines)389 self.code_lineno += self._new_lines390 if self._write_debug_info is not None:391 self.debug_info.append((self._write_debug_info, self.code_lineno))392 self._write_debug_info = None393 self._first_write = False394 self.stream.write(" " * self._indentation)395 self._new_lines = 0396 self.stream.write(x)397398 def writeline(self, x, node=None, extra=0):399 """Combination of newline and write."""400 self.newline(node, extra)401 self.write(x)402403 def newline(self, node=None, extra=0):404 """Add one or more newlines before the next write."""405 self._new_lines = max(self._new_lines, 1 + extra)406 if node is not None and node.lineno != self._last_line:407 self._write_debug_info = node.lineno408 self._last_line = node.lineno409410 def signature(self, node, frame, extra_kwargs=None):411 """Writes a function call to the stream for the current node.412 A leading comma is added automatically. The extra keyword413 arguments may not include python keywords otherwise a syntax414 error could occur. The extra keyword arguments should be given415 as python dict.416 """417 # if any of the given keyword arguments is a python keyword418 # we have to make sure that no invalid call is created.419 kwarg_workaround = False420 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):421 if is_python_keyword(kwarg):422 kwarg_workaround = True423 break424425 for arg in node.args:426 self.write(", ")427 self.visit(arg, frame)428429 if not kwarg_workaround:430 for kwarg in node.kwargs:431 self.write(", ")432 self.visit(kwarg, frame)433 if extra_kwargs is not None:434 for key, value in iteritems(extra_kwargs):435 self.write(", %s=%s" % (key, value))436 if node.dyn_args:437 self.write(", *")438 self.visit(node.dyn_args, frame)439440 if kwarg_workaround:441 if node.dyn_kwargs is not None:442 self.write(", **dict({")443 else:444 self.write(", **{")445 for kwarg in node.kwargs:446 self.write("%r: " % kwarg.key)447 self.visit(kwarg.value, frame)448 self.write(", ")449 if extra_kwargs is not None:450 for key, value in iteritems(extra_kwargs):451 self.write("%r: %s, " % (key, value))452 if node.dyn_kwargs is not None:453 self.write("}, **")454 self.visit(node.dyn_kwargs, frame)455 self.write(")")456 else:457 self.write("}")458459 elif node.dyn_kwargs is not None:460 self.write(", **")461 self.visit(node.dyn_kwargs, frame)462463 def pull_dependencies(self, nodes):464 """Pull all the dependencies."""465 visitor = DependencyFinderVisitor()466 for node in nodes:467 visitor.visit(node)468 for dependency in "filters", "tests":469 mapping = getattr(self, dependency)470 for name in getattr(visitor, dependency):471 if name not in mapping:472 mapping[name] = self.temporary_identifier()473 self.writeline(474 "%s = environment.%s[%r]" % (mapping[name], dependency, name)475 )476477 def enter_frame(self, frame):478 undefs = []479 for target, (action, param) in iteritems(frame.symbols.loads):480 if action == VAR_LOAD_PARAMETER:481 pass482 elif action == VAR_LOAD_RESOLVE:483 self.writeline("%s = %s(%r)" % (target, self.get_resolve_func(), param))484 elif action == VAR_LOAD_ALIAS:485 self.writeline("%s = %s" % (target, param))486 elif action == VAR_LOAD_UNDEFINED:487 undefs.append(target)488 else:489 raise NotImplementedError("unknown load instruction")490 if undefs:491 self.writeline("%s = missing" % " = ".join(undefs))492493 def leave_frame(self, frame, with_python_scope=False):494 if not with_python_scope:495 undefs = []496 for target, _ in iteritems(frame.symbols.loads):497 undefs.append(target)498 if undefs:499 self.writeline("%s = missing" % " = ".join(undefs))500501 def func(self, name):502 if self.environment.is_async:503 return "async def %s" % name504 return "def %s" % name505506 def macro_body(self, node, frame):507 """Dump the function def of a macro or call block."""508 frame = frame.inner()509 frame.symbols.analyze_node(node)510 macro_ref = MacroRef(node)511512 explicit_caller = None513 skip_special_params = set()514 args = []515 for idx, arg in enumerate(node.args):516 if arg.name == "caller":517 explicit_caller = idx518 if arg.name in ("kwargs", "varargs"):519 skip_special_params.add(arg.name)520 args.append(frame.symbols.ref(arg.name))521522 undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs"))523524 if "caller" in undeclared:525 # In older Jinja versions there was a bug that allowed caller526 # to retain the special behavior even if it was mentioned in527 # the argument list. However thankfully this was only really528 # working if it was the last argument. So we are explicitly529 # checking this now and error out if it is anywhere else in530 # the argument list.531 if explicit_caller is not None:532 try:533 node.defaults[explicit_caller - len(node.args)]534 except IndexError:535 self.fail(536 "When defining macros or call blocks the "537 'special "caller" argument must be omitted '538 "or be given a default.",539 node.lineno,540 )541 else:542 args.append(frame.symbols.declare_parameter("caller"))543 macro_ref.accesses_caller = True544 if "kwargs" in undeclared and "kwargs" not in skip_special_params:545 args.append(frame.symbols.declare_parameter("kwargs"))546 macro_ref.accesses_kwargs = True547 if "varargs" in undeclared and "varargs" not in skip_special_params:548 args.append(frame.symbols.declare_parameter("varargs"))549 macro_ref.accesses_varargs = True550551 # macros are delayed, they never require output checks552 frame.require_output_check = False553 frame.symbols.analyze_node(node)554 self.writeline("%s(%s):" % (self.func("macro"), ", ".join(args)), node)555 self.indent()556557 self.buffer(frame)558 self.enter_frame(frame)559560 self.push_parameter_definitions(frame)561 for idx, arg in enumerate(node.args):562 ref = frame.symbols.ref(arg.name)563 self.writeline("if %s is missing:" % ref)564 self.indent()565 try:566 default = node.defaults[idx - len(node.args)]567 except IndexError:568 self.writeline(569 "%s = undefined(%r, name=%r)"570 % (ref, "parameter %r was not provided" % arg.name, arg.name)571 )572 else:573 self.writeline("%s = " % ref)574 self.visit(default, frame)575 self.mark_parameter_stored(ref)576 self.outdent()577 self.pop_parameter_definitions()578579 self.blockvisit(node.body, frame)580 self.return_buffer_contents(frame, force_unescaped=True)581 self.leave_frame(frame, with_python_scope=True)582 self.outdent()583584 return frame, macro_ref585586 def macro_def(self, macro_ref, frame):587 """Dump the macro definition for the def created by macro_body."""588 arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args)589 name = getattr(macro_ref.node, "name", None)590 if len(macro_ref.node.args) == 1:591 arg_tuple += ","592 self.write(593 "Macro(environment, macro, %r, (%s), %r, %r, %r, "594 "context.eval_ctx.autoescape)"595 % (596 name,597 arg_tuple,598 macro_ref.accesses_kwargs,599 macro_ref.accesses_varargs,600 macro_ref.accesses_caller,601 )602 )603604 def position(self, node):605 """Return a human readable position for the node."""606 rv = "line %d" % node.lineno607 if self.name is not None:608 rv += " in " + repr(self.name)609 return rv610611 def dump_local_context(self, frame):612 return "{%s}" % ", ".join(613 "%r: %s" % (name, target)614 for name, target in iteritems(frame.symbols.dump_stores())615 )616617 def write_commons(self):618 """Writes a common preamble that is used by root and block functions.619 Primarily this sets up common local helpers and enforces a generator620 through a dead branch.621 """622 self.writeline("resolve = context.resolve_or_missing")623 self.writeline("undefined = environment.undefined")624 # always use the standard Undefined class for the implicit else of625 # conditional expressions626 self.writeline("cond_expr_undefined = Undefined")627 self.writeline("if 0: yield None")628629 def push_parameter_definitions(self, frame):630 """Pushes all parameter targets from the given frame into a local631 stack that permits tracking of yet to be assigned parameters. In632 particular this enables the optimization from `visit_Name` to skip633 undefined expressions for parameters in macros as macros can reference634 otherwise unbound parameters.635 """636 self._param_def_block.append(frame.symbols.dump_param_targets())637638 def pop_parameter_definitions(self):639 """Pops the current parameter definitions set."""640 self._param_def_block.pop()641642 def mark_parameter_stored(self, target):643 """Marks a parameter in the current parameter definitions as stored.644 This will skip the enforced undefined checks.645 """646 if self._param_def_block:647 self._param_def_block[-1].discard(target)648649 def push_context_reference(self, target):650 self._context_reference_stack.append(target)651652 def pop_context_reference(self):653 self._context_reference_stack.pop()654655 def get_context_ref(self):656 return self._context_reference_stack[-1]657658 def get_resolve_func(self):659 target = self._context_reference_stack[-1]660 if target == "context":661 return "resolve"662 return "%s.resolve" % target663664 def derive_context(self, frame):665 return "%s.derived(%s)" % (666 self.get_context_ref(),667 self.dump_local_context(frame),668 )669670 def parameter_is_undeclared(self, target):671 """Checks if a given target is an undeclared parameter."""672 if not self._param_def_block:673 return False674 return target in self._param_def_block[-1]675676 def push_assign_tracking(self):677 """Pushes a new layer for assignment tracking."""678 self._assign_stack.append(set())679680 def pop_assign_tracking(self, frame):681 """Pops the topmost level for assignment tracking and updates the682 context variables if necessary.683 """684 vars = self._assign_stack.pop()685 if not frame.toplevel or not vars:686 return687 public_names = [x for x in vars if x[:1] != "_"]688 if len(vars) == 1:689 name = next(iter(vars))690 ref = frame.symbols.ref(name)691 self.writeline("context.vars[%r] = %s" % (name, ref))692 else:693 self.writeline("context.vars.update({")694 for idx, name in enumerate(vars):695 if idx:696 self.write(", ")697 ref = frame.symbols.ref(name)698 self.write("%r: %s" % (name, ref))699 self.write("})")700 if public_names:701 if len(public_names) == 1:702 self.writeline("context.exported_vars.add(%r)" % public_names[0])703 else:704 self.writeline(705 "context.exported_vars.update((%s))"706 % ", ".join(imap(repr, public_names))707 )708709 # -- Statement Visitors710711 def visit_Template(self, node, frame=None):712 assert frame is None, "no root frame allowed"713 eval_ctx = EvalContext(self.environment, self.name)714715 from .runtime import exported716717 self.writeline("from __future__ import %s" % ", ".join(code_features))718 self.writeline("from jinja.runtime import " + ", ".join(exported))719720 if self.environment.is_async:721 self.writeline(722 "from jinja.asyncsupport import auto_await, "723 "auto_aiter, AsyncLoopContext"724 )725726 # if we want a deferred initialization we cannot move the727 # environment into a local name728 envenv = not self.defer_init and ", environment=environment" or ""729730 # do we have an extends tag at all? If not, we can save some731 # overhead by just not processing any inheritance code.732 have_extends = node.find(nodes.Extends) is not None733734 # find all blocks735 for block in node.find_all(nodes.Block):736 if block.name in self.blocks:737 self.fail("block %r defined twice" % block.name, block.lineno)738 self.blocks[block.name] = block739740 # find all imports and import them741 for import_ in node.find_all(nodes.ImportedName):742 if import_.importname not in self.import_aliases:743 imp = import_.importname744 self.import_aliases[imp] = alias = self.temporary_identifier()745 if "." in imp:746 module, obj = imp.rsplit(".", 1)747 self.writeline("from %s import %s as %s" % (module, obj, alias))748 else:749 self.writeline("import %s as %s" % (imp, alias))750751 # add the load name752 self.writeline("name = %r" % self.name)753754 # generate the root render function.755 self.writeline(756 "%s(context, missing=missing%s):" % (self.func("root"), envenv), extra=1757 )758 self.indent()759 self.write_commons()760761 # process the root762 frame = Frame(eval_ctx)763 if "self" in find_undeclared(node.body, ("self",)):764 ref = frame.symbols.declare_parameter("self")765 self.writeline("%s = TemplateReference(context)" % ref)766 frame.symbols.analyze_node(node)767 frame.toplevel = frame.rootlevel = True768 frame.require_output_check = have_extends and not self.has_known_extends769 if have_extends:770 self.writeline("parent_template = None")771 self.enter_frame(frame)772 self.pull_dependencies(node.body)773 self.blockvisit(node.body, frame)774 self.leave_frame(frame, with_python_scope=True)775 self.outdent()776777 # make sure that the parent root is called.778 if have_extends:779 if not self.has_known_extends:780 self.indent()781 self.writeline("if parent_template is not None:")782 self.indent()783 if supports_yield_from and not self.environment.is_async:784 self.writeline("yield from parent_template.root_render_func(context)")785 else:786 self.writeline(787 "%sfor event in parent_template."788 "root_render_func(context):"789 % (self.environment.is_async and "async " or "")790 )791 self.indent()792 self.writeline("yield event")793 self.outdent()794 self.outdent(1 + (not self.has_known_extends))795796 # at this point we now have the blocks collected and can visit them too.797 for name, block in iteritems(self.blocks):798 self.writeline(799 "%s(context, missing=missing%s):"800 % (self.func("block_" + name), envenv),801 block,802 1,803 )804 self.indent()805 self.write_commons()806 # It's important that we do not make this frame a child of the807 # toplevel template. This would cause a variety of808 # interesting issues with identifier tracking.809 block_frame = Frame(eval_ctx)810 undeclared = find_undeclared(block.body, ("self", "super"))811 if "self" in undeclared:812 ref = block_frame.symbols.declare_parameter("self")813 self.writeline("%s = TemplateReference(context)" % ref)814 if "super" in undeclared:815 ref = block_frame.symbols.declare_parameter("super")816 self.writeline("%s = context.super(%r, block_%s)" % (ref, name, name))817 block_frame.symbols.analyze_node(block)818 block_frame.block = name819 self.enter_frame(block_frame)820 self.pull_dependencies(block.body)821 self.blockvisit(block.body, block_frame)822 self.leave_frame(block_frame, with_python_scope=True)823 self.outdent()824825 self.writeline(826 "blocks = {%s}" % ", ".join("%r: block_%s" % (x, x) for x in self.blocks),827 extra=1,828 )829830 # add a function that returns the debug info831 self.writeline(832 "debug_info = %r" % "&".join("%s=%s" % x for x in self.debug_info)833 )834835 def visit_Block(self, node, frame):836 """Call a block and register it for the template."""837 level = 0838 if frame.toplevel:839 # if we know that we are a child template, there is no need to840 # check if we are one841 if self.has_known_extends:842 return843 if self.extends_so_far > 0:844 self.writeline("if parent_template is None:")845 self.indent()846 level += 1847848 if node.scoped:849 context = self.derive_context(frame)850 else:851 context = self.get_context_ref()852853 if (854 supports_yield_from855 and not self.environment.is_async856 and frame.buffer is None857 ):858 self.writeline(859 "yield from context.blocks[%r][0](%s)" % (node.name, context), node860 )861 else:862 loop = self.environment.is_async and "async for" or "for"863 self.writeline(864 "%s event in context.blocks[%r][0](%s):" % (loop, node.name, context),865 node,866 )867 self.indent()868 self.simple_write("event", frame)869 self.outdent()870871 self.outdent(level)872873 def visit_Extends(self, node, frame):874 """Calls the extender."""875 if not frame.toplevel:876 self.fail("cannot use extend from a non top-level scope", node.lineno)877878 # if the number of extends statements in general is zero so879 # far, we don't have to add a check if something extended880 # the template before this one.881 if self.extends_so_far > 0:882883 # if we have a known extends we just add a template runtime884 # error into the generated code. We could catch that at compile885 # time too, but i welcome it not to confuse users by throwing the886 # same error at different times just "because we can".887 if not self.has_known_extends:888 self.writeline("if parent_template is not None:")889 self.indent()890 self.writeline("raise TemplateRuntimeError(%r)" % "extended multiple times")891892 # if we have a known extends already we don't need that code here893 # as we know that the template execution will end here.894 if self.has_known_extends:895 raise CompilerExit()896 else:897 self.outdent()898899 self.writeline("parent_template = environment.get_template(", node)900 self.visit(node.template, frame)901 self.write(", %r)" % self.name)902 self.writeline(903 "for name, parent_block in parent_template.blocks.%s():" % dict_item_iter904 )905 self.indent()906 self.writeline("context.blocks.setdefault(name, []).append(parent_block)")907 self.outdent()908909 # if this extends statement was in the root level we can take910 # advantage of that information and simplify the generated code911 # in the top level from this point onwards912 if frame.rootlevel:913 self.has_known_extends = True914915 # and now we have one more916 self.extends_so_far += 1917918 def visit_Include(self, node, frame):919 """Handles includes."""920 if node.ignore_missing:921 self.writeline("try:")922 self.indent()923924 func_name = "get_or_select_template"925 if isinstance(node.template, nodes.Const):926 if isinstance(node.template.value, string_types):927 func_name = "get_template"928 elif isinstance(node.template.value, (tuple, list)):929 func_name = "select_template"930 elif isinstance(node.template, (nodes.Tuple, nodes.List)):931 func_name = "select_template"932933 self.writeline("template = environment.%s(" % func_name, node)934 self.visit(node.template, frame)935 self.write(", %r)" % self.name)936 if node.ignore_missing:937 self.outdent()938 self.writeline("except TemplateNotFound:")939 self.indent()940 self.writeline("pass")941 self.outdent()942 self.writeline("else:")943 self.indent()944945 skip_event_yield = False946 if node.with_context:947 loop = self.environment.is_async and "async for" or "for"948 self.writeline(949 "%s event in template.root_render_func("950 "template.new_context(context.get_all(), True, "951 "%s)):" % (loop, self.dump_local_context(frame))952 )953 elif self.environment.is_async:954 self.writeline(955 "for event in (await "956 "template._get_default_module_async())"957 "._body_stream:"958 )959 else:960 if supports_yield_from:961 self.writeline("yield from template._get_default_module()._body_stream")962 skip_event_yield = True963 else:964 self.writeline(965 "for event in template._get_default_module()._body_stream:"966 )967968 if not skip_event_yield:969 self.indent()970 self.simple_write("event", frame)971 self.outdent()972973 if node.ignore_missing:974 self.outdent()975976 def visit_Import(self, node, frame):977 """Visit regular imports."""978 self.writeline("%s = " % frame.symbols.ref(node.target), node)979 if frame.toplevel:980 self.write("context.vars[%r] = " % node.target)981 if self.environment.is_async:982 self.write("await ")983 self.write("environment.get_template(")984 self.visit(node.template, frame)985 self.write(", %r)." % self.name)986 if node.with_context:987 self.write(988 "make_module%s(context.get_all(), True, %s)"989 % (990 self.environment.is_async and "_async" or "",991 self.dump_local_context(frame),992 )993 )994 elif self.environment.is_async:995 self.write("_get_default_module_async()")996 else:997 self.write("_get_default_module()")998 if frame.toplevel and not node.target.startswith("_"):999 self.writeline("context.exported_vars.discard(%r)" % node.target)10001001 def visit_FromImport(self, node, frame):1002 """Visit named imports."""1003 self.newline(node)1004 self.write(1005 "included_template = %senvironment.get_template("1006 % (self.environment.is_async and "await " or "")1007 )1008 self.visit(node.template, frame)1009 self.write(", %r)." % self.name)1010 if node.with_context:1011 self.write(1012 "make_module%s(context.get_all(), True, %s)"1013 % (1014 self.environment.is_async and "_async" or "",1015 self.dump_local_context(frame),1016 )1017 )1018 elif self.environment.is_async:1019 self.write("_get_default_module_async()")1020 else:1021 self.write("_get_default_module()")10221023 var_names = []1024 discarded_names = []1025 for name in node.names:1026 if isinstance(name, tuple):1027 name, alias = name1028 else:1029 alias = name1030 self.writeline(1031 "%s = getattr(included_template, "1032 "%r, missing)" % (frame.symbols.ref(alias), name)1033 )1034 self.writeline("if %s is missing:" % frame.symbols.ref(alias))1035 self.indent()1036 self.writeline(1037 "%s = undefined(%r %% "1038 "included_template.__name__, "1039 "name=%r)"1040 % (1041 frame.symbols.ref(alias),1042 "the template %%r (imported on %s) does "1043 "not export the requested name %s"1044 % (self.position(node), repr(name)),1045 name,1046 )1047 )1048 self.outdent()1049 if frame.toplevel:1050 var_names.append(alias)1051 if not alias.startswith("_"):1052 discarded_names.append(alias)10531054 if var_names:1055 if len(var_names) == 1:1056 name = var_names[0]1057 self.writeline(1058 "context.vars[%r] = %s" % (name, frame.symbols.ref(name))1059 )1060 else:1061 self.writeline(1062 "context.vars.update({%s})"1063 % ", ".join(1064 "%r: %s" % (name, frame.symbols.ref(name)) for name in var_names1065 )1066 )1067 if discarded_names:1068 if len(discarded_names) == 1:1069 self.writeline("context.exported_vars.discard(%r)" % discarded_names[0])1070 else:1071 self.writeline(1072 "context.exported_vars.difference_"1073 "update((%s))" % ", ".join(imap(repr, discarded_names))1074 )10751076 def visit_For(self, node, frame):1077 loop_frame = frame.inner()1078 test_frame = frame.inner()1079 else_frame = frame.inner()10801081 # try to figure out if we have an extended loop. An extended loop1082 # is necessary if the loop is in recursive mode if the special loop1083 # variable is accessed in the body.1084 extended_loop = node.recursive or "loop" in find_undeclared(1085 node.iter_child_nodes(only=("body",)), ("loop",)1086 )10871088 loop_ref = None1089 if extended_loop:1090 loop_ref = loop_frame.symbols.declare_parameter("loop")10911092 loop_frame.symbols.analyze_node(node, for_branch="body")1093 if node.else_:1094 else_frame.symbols.analyze_node(node, for_branch="else")10951096 if node.test:1097 loop_filter_func = self.temporary_identifier()1098 test_frame.symbols.analyze_node(node, for_branch="test")1099 self.writeline("%s(fiter):" % self.func(loop_filter_func), node.test)1100 self.indent()1101 self.enter_frame(test_frame)1102 self.writeline(self.environment.is_async and "async for " or "for ")1103 self.visit(node.target, loop_frame)1104 self.write(" in ")1105 self.write(self.environment.is_async and "auto_aiter(fiter)" or "fiter")1106 self.write(":")1107 self.indent()1108 self.writeline("if ", node.test)1109 self.visit(node.test, test_frame)1110 self.write(":")1111 self.indent()1112 self.writeline("yield ")1113 self.visit(node.target, loop_frame)1114 self.outdent(3)1115 self.leave_frame(test_frame, with_python_scope=True)11161117 # if we don't have an recursive loop we have to find the shadowed1118 # variables at that point. Because loops can be nested but the loop1119 # variable is a special one we have to enforce aliasing for it.1120 if node.recursive:1121 self.writeline(1122 "%s(reciter, loop_render_func, depth=0):" % self.func("loop"), node1123 )1124 self.indent()1125 self.buffer(loop_frame)11261127 # Use the same buffer for the else frame1128 else_frame.buffer = loop_frame.buffer11291130 # make sure the loop variable is a special one and raise a template1131 # assertion error if a loop tries to write to loop1132 if extended_loop:1133 self.writeline("%s = missing" % loop_ref)11341135 for name in node.find_all(nodes.Name):1136 if name.ctx == "store" and name.name == "loop":1137 self.fail(1138 "Can't assign to special loop variable in for-loop target",1139 name.lineno,1140 )11411142 if node.else_:1143 iteration_indicator = self.temporary_identifier()1144 self.writeline("%s = 1" % iteration_indicator)11451146 self.writeline(self.environment.is_async and "async for " or "for ", node)1147 self.visit(node.target, loop_frame)1148 if extended_loop:1149 if self.environment.is_async:1150 self.write(", %s in AsyncLoopContext(" % loop_ref)1151 else:1152 self.write(", %s in LoopContext(" % loop_ref)1153 else:1154 self.write(" in ")11551156 if node.test:1157 self.write("%s(" % loop_filter_func)1158 if node.recursive:1159 self.write("reciter")1160 else:1161 if self.environment.is_async and not extended_loop:1162 self.write("auto_aiter(")1163 self.visit(node.iter, frame)1164 if self.environment.is_async and not extended_loop:1165 self.write(")")1166 if node.test:1167 self.write(")")11681169 if node.recursive:1170 self.write(", undefined, loop_render_func, depth):")1171 else:1172 self.write(extended_loop and ", undefined):" or ":")11731174 self.indent()1175 self.enter_frame(loop_frame)11761177 self.blockvisit(node.body, loop_frame)1178 if node.else_:1179 self.writeline("%s = 0" % iteration_indicator)1180 self.outdent()1181 self.leave_frame(1182 loop_frame, with_python_scope=node.recursive and not node.else_1183 )11841185 if node.else_:1186 self.writeline("if %s:" % iteration_indicator)1187 self.indent()1188 self.enter_frame(else_frame)1189 self.blockvisit(node.else_, else_frame)1190 self.leave_frame(else_frame)1191 self.outdent()11921193 # if the node was recursive we have to return the buffer contents1194 # and start the iteration code1195 if node.recursive:1196 self.return_buffer_contents(loop_frame)1197 self.outdent()1198 self.start_write(frame, node)1199 if self.environment.is_async:1200 self.write("await ")1201 self.write("loop(")1202 if self.environment.is_async:1203 self.write("auto_aiter(")1204 self.visit(node.iter, frame)1205 if self.environment.is_async:1206 self.write(")")1207 self.write(", loop)")1208 self.end_write(frame)12091210 def visit_If(self, node, frame):1211 if_frame = frame.soft()1212 self.writeline("if ", node)1213 self.visit(node.test, if_frame)1214 self.write(":")1215 self.indent()1216 self.blockvisit(node.body, if_frame)1217 self.outdent()1218 for elif_ in node.elif_:1219 self.writeline("elif ", elif_)1220 self.visit(elif_.test, if_frame)1221 self.write(":")1222 self.indent()1223 self.blockvisit(elif_.body, if_frame)1224 self.outdent()1225 if node.else_:1226 self.writeline("else:")1227 self.indent()1228 self.blockvisit(node.else_, if_frame)1229 self.outdent()12301231 def visit_Macro(self, node, frame):1232 macro_frame, macro_ref = self.macro_body(node, frame)1233 self.newline()1234 if frame.toplevel:1235 if not node.name.startswith("_"):1236 self.write("context.exported_vars.add(%r)" % node.name)1237 self.writeline("context.vars[%r] = " % node.name)1238 self.write("%s = " % frame.symbols.ref(node.name))1239 self.macro_def(macro_ref, macro_frame)12401241 def visit_CallBlock(self, node, frame):1242 call_frame, macro_ref = self.macro_body(node, frame)1243 self.writeline("caller = ")1244 self.macro_def(macro_ref, call_frame)1245 self.start_write(frame, node)1246 self.visit_Call(node.call, frame, forward_caller=True)1247 self.end_write(frame)12481249 def visit_FilterBlock(self, node, frame):1250 filter_frame = frame.inner()1251 filter_frame.symbols.analyze_node(node)1252 self.enter_frame(filter_frame)1253 self.buffer(filter_frame)1254 self.blockvisit(node.body, filter_frame)1255 self.start_write(frame, node)1256 self.visit_Filter(node.filter, filter_frame)1257 self.end_write(frame)1258 self.leave_frame(filter_frame)12591260 def visit_With(self, node, frame):1261 with_frame = frame.inner()1262 with_frame.symbols.analyze_node(node)1263 self.enter_frame(with_frame)1264 for target, expr in izip(node.targets, node.values):1265 self.newline()1266 self.visit(target, with_frame)1267 self.write(" = ")1268 self.visit(expr, frame)1269 self.blockvisit(node.body, with_frame)1270 self.leave_frame(with_frame)12711272 def visit_ExprStmt(self, node, frame):1273 self.newline(node)1274 self.visit(node.node, frame)12751276 _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1277 #: The default finalize function if the environment isn't configured1278 #: with one. Or if the environment has one, this is called on that1279 #: function's output for constants.1280 _default_finalize = text_type1281 _finalize = None12821283 def _make_finalize(self):1284 """Build the finalize function to be used on constants and at1285 runtime. Cached so it's only created once for all output nodes.12861287 Returns a ``namedtuple`` with the following attributes:12881289 ``const``1290 A function to finalize constant data at compile time.12911292 ``src``1293 Source code to output around nodes to be evaluated at1294 runtime.1295 """1296 if self._finalize is not None:1297 return self._finalize12981299 finalize = default = self._default_finalize1300 src = None13011302 if self.environment.finalize:1303 src = "environment.finalize("1304 env_finalize = self.environment.finalize13051306 def finalize(value):1307 return default(env_finalize(value))13081309 if getattr(env_finalize, "contextfunction", False):1310 src += "context, "1311 finalize = None # noqa: F8111312 elif getattr(env_finalize, "evalcontextfunction", False):1313 src += "context.eval_ctx, "1314 finalize = None1315 elif getattr(env_finalize, "environmentfunction", False):1316 src += "environment, "13171318 def finalize(value):1319 return default(env_finalize(self.environment, value))13201321 self._finalize = self._FinalizeInfo(finalize, src)1322 return self._finalize13231324 def _output_const_repr(self, group):1325 """Given a group of constant values converted from ``Output``1326 child nodes, produce a string to write to the template module1327 source.1328 """1329 return repr(concat(group))13301331 def _output_child_to_const(self, node, frame, finalize):1332 """Try to optimize a child of an ``Output`` node by trying to1333 convert it to constant, finalized data at compile time.13341335 If :exc:`Impossible` is raised, the node is not constant and1336 will be evaluated at runtime. Any other exception will also be1337 evaluated at runtime for easier debugging.1338 """1339 const = node.as_const(frame.eval_ctx)13401341 if frame.eval_ctx.autoescape:1342 const = escape(const)13431344 # Template data doesn't go through finalize.1345 if isinstance(node, nodes.TemplateData):1346 return text_type(const)13471348 return finalize.const(const)13491350 def _output_child_pre(self, node, frame, finalize):1351 """Output extra source code before visiting a child of an1352 ``Output`` node.1353 """1354 if frame.eval_ctx.volatile:1355 self.write("(escape if context.eval_ctx.autoescape else to_string)(")1356 elif frame.eval_ctx.autoescape:1357 self.write("escape(")1358 else:1359 self.write("to_string(")13601361 if finalize.src is not None:1362 self.write(finalize.src)13631364 def _output_child_post(self, node, frame, finalize):1365 """Output extra source code after visiting a child of an1366 ``Output`` node.1367 """1368 self.write(")")13691370 if finalize.src is not None:1371 self.write(")")13721373 def visit_Output(self, node, frame):1374 # If an extends is active, don't render outside a block.1375 if frame.require_output_check:1376 # A top-level extends is known to exist at compile time.1377 if self.has_known_extends:1378 return13791380 self.writeline("if parent_template is None:")1381 self.indent()13821383 finalize = self._make_finalize()1384 body = []13851386 # Evaluate constants at compile time if possible. Each item in1387 # body will be either a list of static data or a node to be1388 # evaluated at runtime.1389 for child in node.nodes:1390 try:1391 if not (1392 # If the finalize function requires runtime context,1393 # constants can't be evaluated at compile time.1394 finalize.const1395 # Unless it's basic template data that won't be1396 # finalized anyway.1397 or isinstance(child, nodes.TemplateData)1398 ):1399 raise nodes.Impossible()14001401 const = self._output_child_to_const(child, frame, finalize)1402 except (nodes.Impossible, Exception):1403 # The node was not constant and needs to be evaluated at1404 # runtime. Or another error was raised, which is easier1405 # to debug at runtime.1406 body.append(child)1407 continue14081409 if body and isinstance(body[-1], list):1410 body[-1].append(const)1411 else:1412 body.append([const])14131414 if frame.buffer is not None:1415 if len(body) == 1:1416 self.writeline("%s.append(" % frame.buffer)1417 else:1418 self.writeline("%s.extend((" % frame.buffer)14191420 self.indent()14211422 for item in body:1423 if isinstance(item, list):1424 # A group of constant data to join and output.1425 val = self._output_const_repr(item)14261427 if frame.buffer is None:1428 self.writeline("yield " + val)1429 else:1430 self.writeline(val + ",")1431 else:1432 if frame.buffer is None:1433 self.writeline("yield ", item)1434 else:1435 self.newline(item)14361437 # A node to be evaluated at runtime.1438 self._output_child_pre(item, frame, finalize)1439 self.visit(item, frame)1440 self._output_child_post(item, frame, finalize)14411442 if frame.buffer is not None:1443 self.write(",")14441445 if frame.buffer is not None:1446 self.outdent()1447 self.writeline(")" if len(body) == 1 else "))")14481449 if frame.require_output_check:1450 self.outdent()14511452 def visit_Assign(self, node, frame):1453 self.push_assign_tracking()1454 self.newline(node)1455 self.visit(node.target, frame)1456 self.write(" = ")1457 self.visit(node.node, frame)1458 self.pop_assign_tracking(frame)14591460 def visit_AssignBlock(self, node, frame):1461 self.push_assign_tracking()1462 block_frame = frame.inner()1463 # This is a special case. Since a set block always captures we1464 # will disable output checks. This way one can use set blocks1465 # toplevel even in extended templates.1466 block_frame.require_output_check = False1467 block_frame.symbols.analyze_node(node)1468 self.enter_frame(block_frame)1469 self.buffer(block_frame)1470 self.blockvisit(node.body, block_frame)1471 self.newline(node)1472 self.visit(node.target, frame)1473 self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")1474 if node.filter is not None:1475 self.visit_Filter(node.filter, block_frame)1476 else:1477 self.write("concat(%s)" % block_frame.buffer)1478 self.write(")")1479 self.pop_assign_tracking(frame)1480 self.leave_frame(block_frame)14811482 # -- Expression Visitors14831484 def visit_Name(self, node, frame):1485 if node.ctx == "store" and frame.toplevel:1486 if self._assign_stack:1487 self._assign_stack[-1].add(node.name)1488 ref = frame.symbols.ref(node.name)14891490 # If we are looking up a variable we might have to deal with the1491 # case where it's undefined. We can skip that case if the load1492 # instruction indicates a parameter which are always defined.1493 if node.ctx == "load":1494 load = frame.symbols.find_load(ref)1495 if not (1496 load is not None1497 and load[0] == VAR_LOAD_PARAMETER1498 and not self.parameter_is_undeclared(ref)1499 ):1500 self.write(1501 "(undefined(name=%r) if %s is missing else %s)"1502 % (node.name, ref, ref)1503 )1504 return15051506 self.write(ref)15071508 def visit_NSRef(self, node, frame):1509 # NSRefs can only be used to store values; since they use the normal1510 # `foo.bar` notation they will be parsed as a normal attribute access1511 # when used anywhere but in a `set` context1512 ref = frame.symbols.ref(node.name)1513 self.writeline("if not isinstance(%s, Namespace):" % ref)1514 self.indent()1515 self.writeline(1516 "raise TemplateRuntimeError(%r)"1517 % "cannot assign attribute on non-namespace object"1518 )1519 self.outdent()1520 self.writeline("%s[%r]" % (ref, node.attr))15211522 def visit_Const(self, node, frame):1523 val = node.as_const(frame.eval_ctx)1524 if isinstance(val, float):1525 self.write(str(val))1526 else:1527 self.write(repr(val))15281529 def visit_TemplateData(self, node, frame):1530 try:1531 self.write(repr(node.as_const(frame.eval_ctx)))1532 except nodes.Impossible:1533 self.write(1534 "(Markup if context.eval_ctx.autoescape else identity)(%r)" % node.data1535 )15361537 def visit_Tuple(self, node, frame):1538 self.write("(")1539 idx = -11540 for idx, item in enumerate(node.items):1541 if idx:1542 self.write(", ")1543 self.visit(item, frame)1544 self.write(idx == 0 and ",)" or ")")15451546 def visit_List(self, node, frame):1547 self.write("[")1548 for idx, item in enumerate(node.items):1549 if idx:1550 self.write(", ")1551 self.visit(item, frame)1552 self.write("]")15531554 def visit_Dict(self, node, frame):1555 self.write("{")1556 for idx, item in enumerate(node.items):1557 if idx:1558 self.write(", ")1559 self.visit(item.key, frame)1560 self.write(": ")1561 self.visit(item.value, frame)1562 self.write("}")15631564 def binop(operator, interceptable=True): # noqa: B9021565 @optimizeconst1566 def visitor(self, node, frame):1567 if (1568 self.environment.sandboxed1569 and operator in self.environment.intercepted_binops1570 ):1571 self.write("environment.call_binop(context, %r, " % operator)1572 self.visit(node.left, frame)1573 self.write(", ")1574 self.visit(node.right, frame)1575 else:1576 self.write("(")1577 self.visit(node.left, frame)1578 self.write(" %s " % operator)1579 self.visit(node.right, frame)1580 self.write(")")15811582 return visitor15831584 def uaop(operator, interceptable=True): # noqa: B9021585 @optimizeconst1586 def visitor(self, node, frame):1587 if (1588 self.environment.sandboxed1589 and operator in self.environment.intercepted_unops1590 ):1591 self.write("environment.call_unop(context, %r, " % operator)1592 self.visit(node.node, frame)1593 else:1594 self.write("(" + operator)1595 self.visit(node.node, frame)1596 self.write(")")15971598 return visitor15991600 visit_Add = binop("+")1601 visit_Sub = binop("-")1602 visit_Mul = binop("*")1603 visit_Div = binop("/")1604 visit_FloorDiv = binop("//")1605 visit_Pow = binop("**")1606 visit_Mod = binop("%")1607 visit_And = binop("and", interceptable=False)1608 visit_Or = binop("or", interceptable=False)1609 visit_Pos = uaop("+")1610 visit_Neg = uaop("-")1611 visit_Not = uaop("not ", interceptable=False)1612 del binop, uaop16131614 @optimizeconst1615 def visit_Concat(self, node, frame):1616 if frame.eval_ctx.volatile:1617 func_name = "(context.eval_ctx.volatile and markup_join or unicode_join)"1618 elif frame.eval_ctx.autoescape:1619 func_name = "markup_join"1620 else:1621 func_name = "unicode_join"1622 self.write("%s((" % func_name)1623 for arg in node.nodes:1624 self.visit(arg, frame)1625 self.write(", ")1626 self.write("))")16271628 @optimizeconst1629 def visit_Compare(self, node, frame):1630 self.write("(")1631 self.visit(node.expr, frame)1632 for op in node.ops:1633 self.visit(op, frame)1634 self.write(")")16351636 def visit_Operand(self, node, frame):1637 self.write(" %s " % operators[node.op])1638 self.visit(node.expr, frame)16391640 @optimizeconst1641 def visit_Getattr(self, node, frame):1642 if self.environment.is_async:1643 self.write("await auto_await(")16441645 self.write("environment.getattr(")1646 self.visit(node.node, frame)1647 self.write(", %r)" % node.attr)16481649 if self.environment.is_async:1650 self.write(")")16511652 @optimizeconst1653 def visit_Getitem(self, node, frame):1654 # slices bypass the environment getitem method.1655 if isinstance(node.arg, nodes.Slice):1656 self.visit(node.node, frame)1657 self.write("[")1658 self.visit(node.arg, frame)1659 self.write("]")1660 else:1661 if self.environment.is_async:1662 self.write("await auto_await(")16631664 self.write("environment.getitem(")1665 self.visit(node.node, frame)1666 self.write(", ")1667 self.visit(node.arg, frame)1668 self.write(")")16691670 if self.environment.is_async:1671 self.write(")")16721673 def visit_Slice(self, node, frame):1674 if node.start is not None:1675 self.visit(node.start, frame)1676 self.write(":")1677 if node.stop is not None:1678 self.visit(node.stop, frame)1679 if node.step is not None:1680 self.write(":")1681 self.visit(node.step, frame)16821683 @optimizeconst1684 def visit_Filter(self, node, frame):1685 if self.environment.is_async:1686 self.write("await auto_await(")1687 self.write(self.filters[node.name] + "(")1688 func = self.environment.filters.get(node.name)1689 if func is None:1690 self.fail("no filter named %r" % node.name, node.lineno)1691 if getattr(func, "contextfilter", False):1692 self.write("context, ")1693 elif getattr(func, "evalcontextfilter", False):1694 self.write("context.eval_ctx, ")1695 elif getattr(func, "environmentfilter", False):1696 self.write("environment, ")16971698 # if the filter node is None we are inside a filter block1699 # and want to write to the current buffer1700 if node.node is not None:1701 self.visit(node.node, frame)1702 elif frame.eval_ctx.volatile:1703 self.write(1704 "(context.eval_ctx.autoescape and"1705 " Markup(concat(%s)) or concat(%s))" % (frame.buffer, frame.buffer)1706 )1707 elif frame.eval_ctx.autoescape:1708 self.write("Markup(concat(%s))" % frame.buffer)1709 else:1710 self.write("concat(%s)" % frame.buffer)1711 self.signature(node, frame)1712 self.write(")")1713 if self.environment.is_async:1714 self.write(")")17151716 @optimizeconst1717 def visit_Test(self, node, frame):1718 self.write(self.tests[node.name] + "(")1719 if node.name not in self.environment.tests:1720 self.fail("no test named %r" % node.name, node.lineno)1721 self.visit(node.node, frame)1722 self.signature(node, frame)1723 self.write(")")17241725 @optimizeconst1726 def visit_CondExpr(self, node, frame):1727 def write_expr2():1728 if node.expr2 is not None:1729 return self.visit(node.expr2, frame)1730 self.write(1731 "cond_expr_undefined(%r)"1732 % (1733 "the inline if-"1734 "expression on %s evaluated to false and "1735 "no else section was defined." % self.position(node)1736 )1737 )17381739 self.write("(")1740 self.visit(node.expr1, frame)1741 self.write(" if ")1742 self.visit(node.test, frame)1743 self.write(" else ")1744 write_expr2()1745 self.write(")")17461747 @optimizeconst1748 def visit_Call(self, node, frame, forward_caller=False):1749 if self.environment.is_async:1750 self.write("await auto_await(")1751 if self.environment.sandboxed:1752 self.write("environment.call(context, ")1753 else:1754 self.write("context.call(")1755 self.visit(node.node, frame)1756 extra_kwargs = forward_caller and {"caller": "caller"} or None1757 self.signature(node, frame, extra_kwargs)1758 self.write(")")1759 if self.environment.is_async:1760 self.write(")")17611762 def visit_Keyword(self, node, frame):1763 self.write(node.key + "=")1764 self.visit(node.value, frame)17651766 # -- Unused nodes for extensions17671768 def visit_MarkSafe(self, node, frame):1769 self.write("Markup(")1770 self.visit(node.expr, frame)1771 self.write(")")17721773 def visit_MarkSafeIfAutoescape(self, node, frame):1774 self.write("(context.eval_ctx.autoescape and Markup or identity)(")1775 self.visit(node.expr, frame)1776 self.write(")")17771778 def visit_EnvironmentAttribute(self, node, frame):1779 self.write("environment." + node.name)17801781 def visit_ExtensionAttribute(self, node, frame):1782 self.write("environment.extensions[%r].%s" % (node.identifier, node.name))17831784 def visit_ImportedName(self, node, frame):1785 self.write(self.import_aliases[node.importname])17861787 def visit_InternalName(self, node, frame):1788 self.write(node.name)17891790 def visit_ContextReference(self, node, frame):1791 self.write("context")17921793 def visit_DerivedContextReference(self, node, frame):1794 self.write(self.derive_context(frame))17951796 def visit_Continue(self, node, frame):1797 self.writeline("continue", node)17981799 def visit_Break(self, node, frame):1800 self.writeline("break", node)18011802 def visit_Scope(self, node, frame):1803 scope_frame = frame.inner()1804 scope_frame.symbols.analyze_node(node)1805 self.enter_frame(scope_frame)1806 self.blockvisit(node.body, scope_frame)1807 self.leave_frame(scope_frame)18081809 def visit_OverlayScope(self, node, frame):1810 ctx = self.temporary_identifier()1811 self.writeline("%s = %s" % (ctx, self.derive_context(frame)))1812 self.writeline("%s.vars = " % ctx)1813 self.visit(node.context, frame)1814 self.push_context_reference(ctx)18151816 scope_frame = frame.inner(isolated=True)1817 scope_frame.symbols.analyze_node(node)1818 self.enter_frame(scope_frame)1819 self.blockvisit(node.body, scope_frame)1820 self.leave_frame(scope_frame)1821 self.pop_context_reference()18221823 def visit_EvalContextModifier(self, node, frame):1824 for keyword in node.options:1825 self.writeline("context.eval_ctx.%s = " % keyword.key)1826 self.visit(keyword.value, frame)1827 try:1828 val = keyword.value.as_const(frame.eval_ctx)1829 except nodes.Impossible:1830 frame.eval_ctx.volatile = True1831 else:1832 setattr(frame.eval_ctx, keyword.key, val)18331834 def visit_ScopedEvalContextModifier(self, node, frame):1835 old_ctx_name = self.temporary_identifier()1836 saved_ctx = frame.eval_ctx.save()1837 self.writeline("%s = context.eval_ctx.save()" % old_ctx_name)1838 self.visit_EvalContextModifier(node, frame)1839 for child in node.body:1840 self.visit(child, frame)1841 frame.eval_ctx.revert(saved_ctx)1842 self.writeline("context.eval_ctx.revert(%s)" % old_ctx_name)
added:src/jinja/constants.py+21 added
1# -*- coding: utf-8 -*-2#: list of lorem ipsum words used by the lipsum() helper function3LOREM_IPSUM_WORDS = u"""\4a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at5auctor augue bibendum blandit class commodo condimentum congue consectetuer6consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus7diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend8elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames9faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac10hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum11justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem12luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie13mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non14nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque15penatibus per pharetra phasellus placerat platea porta porttitor posuere16potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus17ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit18sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor19tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices20ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus21viverra volutpat vulputate"""
added:src/jinja/debug.py+271 added
1import sys2from types import CodeType34from . import TemplateSyntaxError5from ._compat import PYPY6from .utils import internal_code7from .utils import missing8910def rewrite_traceback_stack(source=None):11 """Rewrite the current exception to replace any tracebacks from12 within compiled template code with tracebacks that look like they13 came from the template source.1415 This must be called within an ``except`` block.1617 :param exc_info: A :meth:`sys.exc_info` tuple. If not provided,18 the current ``exc_info`` is used.19 :param source: For ``TemplateSyntaxError``, the original source if20 known.21 :return: A :meth:`sys.exc_info` tuple that can be re-raised.22 """23 exc_type, exc_value, tb = sys.exc_info()2425 if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:26 exc_value.translated = True27 exc_value.source = source2829 try:30 # Remove the old traceback on Python 3, otherwise the frames31 # from the compiler still show up.32 exc_value.with_traceback(None)33 except AttributeError:34 pass3536 # Outside of runtime, so the frame isn't executing template37 # code, but it still needs to point at the template.38 tb = fake_traceback(39 exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno40 )41 else:42 # Skip the frame for the render function.43 tb = tb.tb_next4445 stack = []4647 # Build the stack of traceback object, replacing any in template48 # code with the source file and line information.49 while tb is not None:50 # Skip frames decorated with @internalcode. These are internal51 # calls that aren't useful in template debugging output.52 if tb.tb_frame.f_code in internal_code:53 tb = tb.tb_next54 continue5556 template = tb.tb_frame.f_globals.get("__jinja_template__")5758 if template is not None:59 lineno = template.get_corresponding_lineno(tb.tb_lineno)60 fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)61 stack.append(fake_tb)62 else:63 stack.append(tb)6465 tb = tb.tb_next6667 tb_next = None6869 # Assign tb_next in reverse to avoid circular references.70 for tb in reversed(stack):71 tb_next = tb_set_next(tb, tb_next)7273 return exc_type, exc_value, tb_next747576def fake_traceback(exc_value, tb, filename, lineno):77 """Produce a new traceback object that looks like it came from the78 template source instead of the compiled code. The filename, line79 number, and location name will point to the template, and the local80 variables will be the current template context.8182 :param exc_value: The original exception to be re-raised to create83 the new traceback.84 :param tb: The original traceback to get the local variables and85 code info from.86 :param filename: The template filename.87 :param lineno: The line number in the template source.88 """89 if tb is not None:90 # Replace the real locals with the context that would be91 # available at that point in the template.92 locals = get_template_locals(tb.tb_frame.f_locals)93 locals.pop("__jinja_exception__", None)94 else:95 locals = {}9697 globals = {98 "__name__": filename,99 "__file__": filename,100 "__jinja_exception__": exc_value,101 }102 # Raise an exception at the correct line number.103 code = compile("\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec")104105 # Build a new code object that points to the template file and106 # replaces the location with a block name.107 try:108 location = "template"109110 if tb is not None:111 function = tb.tb_frame.f_code.co_name112113 if function == "root":114 location = "top-level template code"115 elif function.startswith("block_"):116 location = 'block "%s"' % function[6:]117118 # Collect arguments for the new code object. CodeType only119 # accepts positional arguments, and arguments were inserted in120 # new Python versions.121 code_args = []122123 for attr in (124 "argcount",125 "posonlyargcount", # Python 3.8126 "kwonlyargcount", # Python 3127 "nlocals",128 "stacksize",129 "flags",130 "code", # codestring131 "consts", # constants132 "names",133 "varnames",134 ("filename", filename),135 ("name", location),136 "firstlineno",137 "lnotab",138 "freevars",139 "cellvars",140 ):141 if isinstance(attr, tuple):142 # Replace with given value.143 code_args.append(attr[1])144 continue145146 try:147 # Copy original value if it exists.148 code_args.append(getattr(code, "co_" + attr))149 except AttributeError:150 # Some arguments were added later.151 continue152153 code = CodeType(*code_args)154 except Exception:155 # Some environments such as Google App Engine don't support156 # modifying code objects.157 pass158159 # Execute the new code, which is guaranteed to raise, and return160 # the new traceback without this frame.161 try:162 exec(code, globals, locals)163 except BaseException:164 return sys.exc_info()[2].tb_next165166167def get_template_locals(real_locals):168 """Based on the runtime locals, get the context that would be169 available at that point in the template.170 """171 # Start with the current template context.172 ctx = real_locals.get("context")173174 if ctx:175 data = ctx.get_all().copy()176 else:177 data = {}178179 # Might be in a derived context that only sets local variables180 # rather than pushing a context. Local variables follow the scheme181 # l_depth_name. Find the highest-depth local that has a value for182 # each name.183 local_overrides = {}184185 for name, value in real_locals.items():186 if not name.startswith("l_") or value is missing:187 # Not a template variable, or no longer relevant.188 continue189190 try:191 _, depth, name = name.split("_", 2)192 depth = int(depth)193 except ValueError:194 continue195196 cur_depth = local_overrides.get(name, (-1,))[0]197198 if cur_depth < depth:199 local_overrides[name] = (depth, value)200201 # Modify the context with any derived context.202 for name, (_, value) in local_overrides.items():203 if value is missing:204 data.pop(name, None)205 else:206 data[name] = value207208 return data209210211if sys.version_info >= (3, 7):212 # tb_next is directly assignable as of Python 3.7213 def tb_set_next(tb, tb_next):214 tb.tb_next = tb_next215 return tb216217218elif PYPY:219 # PyPy might have special support, and won't work with ctypes.220 try:221 import tputil222 except ImportError:223 # Without tproxy support, use the original traceback.224 def tb_set_next(tb, tb_next):225 return tb226227 else:228 # With tproxy support, create a proxy around the traceback that229 # returns the new tb_next.230 def tb_set_next(tb, tb_next):231 def controller(op):232 if op.opname == "__getattribute__" and op.args[0] == "tb_next":233 return tb_next234235 return op.delegate()236237 return tputil.make_proxy(controller, obj=tb)238239240else:241 # Use ctypes to assign tb_next at the C level since it's read-only242 # from Python.243 import ctypes244245 class _CTraceback(ctypes.Structure):246 _fields_ = [247 # Extra PyObject slots when compiled with Py_TRACE_REFS.248 (249 "PyObject_HEAD",250 ctypes.c_byte * (32 if hasattr(sys, "getobjects") else 16),251 ),252 # Only care about tb_next as an object, not a traceback.253 ("tb_next", ctypes.py_object),254 ]255256 def tb_set_next(tb, tb_next):257 c_tb = _CTraceback.from_address(id(tb))258259 # Clear out the old tb_next.260 if tb.tb_next is not None:261 c_tb_next = ctypes.py_object(tb.tb_next)262 c_tb.tb_next = ctypes.py_object()263 ctypes.pythonapi.Py_DecRef(c_tb_next)264265 # Assign the new tb_next.266 if tb_next is not None:267 c_tb_next = ctypes.py_object(tb_next)268 ctypes.pythonapi.Py_IncRef(c_tb_next)269 c_tb.tb_next = c_tb_next270271 return tb
added:src/jinja/defaults.py+44 added
1# -*- coding: utf-8 -*-2from ._compat import range_type3from .filters import FILTERS as DEFAULT_FILTERS # noqa: F4014from .tests import TESTS as DEFAULT_TESTS # noqa: F4015from .utils import Cycler6from .utils import generate_lorem_ipsum7from .utils import Joiner8from .utils import Namespace910# defaults for the parser / lexer11BLOCK_START_STRING = "{%"12BLOCK_END_STRING = "%}"13VARIABLE_START_STRING = "{{"14VARIABLE_END_STRING = "}}"15COMMENT_START_STRING = "{#"16COMMENT_END_STRING = "#}"17LINE_STATEMENT_PREFIX = None18LINE_COMMENT_PREFIX = None19TRIM_BLOCKS = False20LSTRIP_BLOCKS = False21NEWLINE_SEQUENCE = "\n"22KEEP_TRAILING_NEWLINE = False2324# default filters, tests and namespace2526DEFAULT_NAMESPACE = {27 "range": range_type,28 "dict": dict,29 "lipsum": generate_lorem_ipsum,30 "cycler": Cycler,31 "joiner": Joiner,32 "namespace": Namespace,33}3435# default policies36DEFAULT_POLICIES = {37 "compiler.ascii_str": True,38 "urlize.rel": "noopener",39 "urlize.target": None,40 "truncate.leeway": 5,41 "json.dumps_function": None,42 "json.dumps_kwargs": {"sort_keys": True},43 "ext.i18n.trimmed": False,44}
added:src/jinja/environment.py+1361 added
1# -*- coding: utf-8 -*-2"""Classes for managing templates and their runtime and compile time3options.4"""5import os6import sys7import weakref8from functools import partial9from functools import reduce1011from . import nodes12from ._compat import encode_filename13from ._compat import implements_iterator14from ._compat import implements_to_string15from ._compat import iteritems16from ._compat import PY217from ._compat import PYPY18from ._compat import reraise19from ._compat import string_types20from ._compat import text_type21from .compiler import CodeGenerator22from .compiler import generate23from .defaults import BLOCK_END_STRING24from .defaults import BLOCK_START_STRING25from .defaults import COMMENT_END_STRING26from .defaults import COMMENT_START_STRING27from .defaults import DEFAULT_FILTERS28from .defaults import DEFAULT_NAMESPACE29from .defaults import DEFAULT_POLICIES30from .defaults import DEFAULT_TESTS31from .defaults import KEEP_TRAILING_NEWLINE32from .defaults import LINE_COMMENT_PREFIX33from .defaults import LINE_STATEMENT_PREFIX34from .defaults import LSTRIP_BLOCKS35from .defaults import NEWLINE_SEQUENCE36from .defaults import TRIM_BLOCKS37from .defaults import VARIABLE_END_STRING38from .defaults import VARIABLE_START_STRING39from .exceptions import TemplateNotFound40from .exceptions import TemplateRuntimeError41from .exceptions import TemplatesNotFound42from .exceptions import TemplateSyntaxError43from .exceptions import UndefinedError44from .lexer import get_lexer45from .lexer import TokenStream46from .nodes import EvalContext47from .parser import Parser48from .runtime import Context49from .runtime import new_context50from .runtime import Undefined51from .utils import concat52from .utils import consume53from .utils import have_async_gen54from .utils import import_string55from .utils import internalcode56from .utils import LRUCache57from .utils import Markup58from .utils import missing5960# for direct template usage we have up to ten living environments61_spontaneous_environments = LRUCache(10)626364def get_spontaneous_environment(cls, *args):65 """Return a new spontaneous environment. A spontaneous environment66 is used for templates created directly rather than through an67 existing environment.6869 :param cls: Environment class to create.70 :param args: Positional arguments passed to environment.71 """72 key = (cls, args)7374 try:75 return _spontaneous_environments[key]76 except KeyError:77 _spontaneous_environments[key] = env = cls(*args)78 env.shared = True79 return env808182def create_cache(size):83 """Return the cache class for the given size."""84 if size == 0:85 return None86 if size < 0:87 return {}88 return LRUCache(size)899091def copy_cache(cache):92 """Create an empty copy of the given cache."""93 if cache is None:94 return None95 elif type(cache) is dict:96 return {}97 return LRUCache(cache.capacity)9899100def load_extensions(environment, extensions):101 """Load the extensions from the list and bind it to the environment.102 Returns a dict of instantiated environments.103 """104 result = {}105 for extension in extensions:106 if isinstance(extension, string_types):107 extension = import_string(extension)108 result[extension.identifier] = extension(environment)109 return result110111112def fail_for_missing_callable(string, name):113 msg = string % name114 if isinstance(name, Undefined):115 try:116 name._fail_with_undefined_error()117 except Exception as e:118 msg = "%s (%s; did you forget to quote the callable name?)" % (msg, e)119 raise TemplateRuntimeError(msg)120121122def _environment_sanity_check(environment):123 """Perform a sanity check on the environment."""124 assert issubclass(125 environment.undefined, Undefined126 ), "undefined must be a subclass of undefined because filters depend on it."127 assert (128 environment.block_start_string129 != environment.variable_start_string130 != environment.comment_start_string131 ), "block, variable and comment start strings must be different"132 assert environment.newline_sequence in (133 "\r",134 "\r\n",135 "\n",136 ), "newline_sequence set to unknown line ending string."137 return environment138139140class Environment(object):141 r"""The core component of Jinja is the `Environment`. It contains142 important shared variables like configuration, filters, tests,143 globals and others. Instances of this class may be modified if144 they are not shared and if no template was loaded so far.145 Modifications on environments after the first template was loaded146 will lead to surprising effects and undefined behavior.147148 Here are the possible initialization parameters:149150 `block_start_string`151 The string marking the beginning of a block. Defaults to ``'{%'``.152153 `block_end_string`154 The string marking the end of a block. Defaults to ``'%}'``.155156 `variable_start_string`157 The string marking the beginning of a print statement.158 Defaults to ``'{{'``.159160 `variable_end_string`161 The string marking the end of a print statement. Defaults to162 ``'}}'``.163164 `comment_start_string`165 The string marking the beginning of a comment. Defaults to ``'{#'``.166167 `comment_end_string`168 The string marking the end of a comment. Defaults to ``'#}'``.169170 `line_statement_prefix`171 If given and a string, this will be used as prefix for line based172 statements. See also :ref:`line-statements`.173174 `line_comment_prefix`175 If given and a string, this will be used as prefix for line based176 comments. See also :ref:`line-statements`.177178 .. versionadded:: 2.2179180 `trim_blocks`181 If this is set to ``True`` the first newline after a block is182 removed (block, not variable tag!). Defaults to `False`.183184 `lstrip_blocks`185 If this is set to ``True`` leading spaces and tabs are stripped186 from the start of a line to a block. Defaults to `False`.187188 `newline_sequence`189 The sequence that starts a newline. Must be one of ``'\r'``,190 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a191 useful default for Linux and OS X systems as well as web192 applications.193194 `keep_trailing_newline`195 Preserve the trailing newline when rendering templates.196 The default is ``False``, which causes a single newline,197 if present, to be stripped from the end of the template.198199 .. versionadded:: 2.7200201 `extensions`202 List of Jinja extensions to use. This can either be import paths203 as strings or extension classes. For more information have a204 look at :ref:`the extensions documentation <jinja-extensions>`.205206 `optimized`207 should the optimizer be enabled? Default is ``True``.208209 `undefined`210 :class:`Undefined` or a subclass of it that is used to represent211 undefined values in the template.212213 `finalize`214 A callable that can be used to process the result of a variable215 expression before it is output. For example one can convert216 ``None`` implicitly into an empty string here.217218 `autoescape`219 If set to ``True`` the XML/HTML autoescaping feature is enabled by220 default. For more details about autoescaping see221 :class:`~markupsafe.Markup`. This can also222 be a callable that is passed the template name and has to223 return ``True`` or ``False`` depending on autoescape should be224 enabled by default.225226 .. versionchanged:: 2.4227 `autoescape` can now be a function228229 `loader`230 The template loader for this environment.231232 `cache_size`233 The size of the cache. Per default this is ``400`` which means234 that if more than 400 templates are loaded the loader will clean235 out the least recently used template. If the cache size is set to236 ``0`` templates are recompiled all the time, if the cache size is237 ``-1`` the cache will not be cleaned.238239 .. versionchanged:: 2.8240 The cache size was increased to 400 from a low 50.241242 `auto_reload`243 Some loaders load templates from locations where the template244 sources may change (ie: file system or database). If245 ``auto_reload`` is set to ``True`` (default) every time a template is246 requested the loader checks if the source changed and if yes, it247 will reload the template. For higher performance it's possible to248 disable that.249250 `bytecode_cache`251 If set to a bytecode cache object, this object will provide a252 cache for the internal Jinja bytecode so that templates don't253 have to be parsed if they were not changed.254255 See :ref:`bytecode-cache` for more information.256257 `enable_async`258 If set to true this enables async template execution which allows259 you to take advantage of newer Python features. This requires260 Python 3.6 or later.261 """262263 #: if this environment is sandboxed. Modifying this variable won't make264 #: the environment sandboxed though. For a real sandboxed environment265 #: have a look at jinja.sandbox. This flag alone controls the code266 #: generation by the compiler.267 sandboxed = False268269 #: True if the environment is just an overlay270 overlayed = False271272 #: the environment this environment is linked to if it is an overlay273 linked_to = None274275 #: shared environments have this set to `True`. A shared environment276 #: must not be modified277 shared = False278279 #: the class that is used for code generation. See280 #: :class:`~jinja.compiler.CodeGenerator` for more information.281 code_generator_class = CodeGenerator282283 #: the context class thatis used for templates. See284 #: :class:`~jinja.runtime.Context` for more information.285 context_class = Context286287 def __init__(288 self,289 block_start_string=BLOCK_START_STRING,290 block_end_string=BLOCK_END_STRING,291 variable_start_string=VARIABLE_START_STRING,292 variable_end_string=VARIABLE_END_STRING,293 comment_start_string=COMMENT_START_STRING,294 comment_end_string=COMMENT_END_STRING,295 line_statement_prefix=LINE_STATEMENT_PREFIX,296 line_comment_prefix=LINE_COMMENT_PREFIX,297 trim_blocks=TRIM_BLOCKS,298 lstrip_blocks=LSTRIP_BLOCKS,299 newline_sequence=NEWLINE_SEQUENCE,300 keep_trailing_newline=KEEP_TRAILING_NEWLINE,301 extensions=(),302 optimized=True,303 undefined=Undefined,304 finalize=None,305 autoescape=False,306 loader=None,307 cache_size=400,308 auto_reload=True,309 bytecode_cache=None,310 enable_async=False,311 ):312 # !!Important notice!!313 # The constructor accepts quite a few arguments that should be314 # passed by keyword rather than position. However it's important to315 # not change the order of arguments because it's used at least316 # internally in those cases:317 # - spontaneous environments (i18n extension and Template)318 # - unittests319 # If parameter changes are required only add parameters at the end320 # and don't change the arguments (or the defaults!) of the arguments321 # existing already.322323 # lexer / parser information324 self.block_start_string = block_start_string325 self.block_end_string = block_end_string326 self.variable_start_string = variable_start_string327 self.variable_end_string = variable_end_string328 self.comment_start_string = comment_start_string329 self.comment_end_string = comment_end_string330 self.line_statement_prefix = line_statement_prefix331 self.line_comment_prefix = line_comment_prefix332 self.trim_blocks = trim_blocks333 self.lstrip_blocks = lstrip_blocks334 self.newline_sequence = newline_sequence335 self.keep_trailing_newline = keep_trailing_newline336337 # runtime information338 self.undefined = undefined339 self.optimized = optimized340 self.finalize = finalize341 self.autoescape = autoescape342343 # defaults344 self.filters = DEFAULT_FILTERS.copy()345 self.tests = DEFAULT_TESTS.copy()346 self.globals = DEFAULT_NAMESPACE.copy()347348 # set the loader provided349 self.loader = loader350 self.cache = create_cache(cache_size)351 self.bytecode_cache = bytecode_cache352 self.auto_reload = auto_reload353354 # configurable policies355 self.policies = DEFAULT_POLICIES.copy()356357 # load extensions358 self.extensions = load_extensions(self, extensions)359360 self.enable_async = enable_async361 self.is_async = self.enable_async and have_async_gen362 if self.is_async:363 # runs patch_all() to enable async support364 from . import asyncsupport # noqa: F401365366 _environment_sanity_check(self)367368 def add_extension(self, extension):369 """Adds an extension after the environment was created.370371 .. versionadded:: 2.5372 """373 self.extensions.update(load_extensions(self, [extension]))374375 def extend(self, **attributes):376 """Add the items to the instance of the environment if they do not exist377 yet. This is used by :ref:`extensions <writing-extensions>` to register378 callbacks and configuration values without breaking inheritance.379 """380 for key, value in iteritems(attributes):381 if not hasattr(self, key):382 setattr(self, key, value)383384 def overlay(385 self,386 block_start_string=missing,387 block_end_string=missing,388 variable_start_string=missing,389 variable_end_string=missing,390 comment_start_string=missing,391 comment_end_string=missing,392 line_statement_prefix=missing,393 line_comment_prefix=missing,394 trim_blocks=missing,395 lstrip_blocks=missing,396 extensions=missing,397 optimized=missing,398 undefined=missing,399 finalize=missing,400 autoescape=missing,401 loader=missing,402 cache_size=missing,403 auto_reload=missing,404 bytecode_cache=missing,405 ):406 """Create a new overlay environment that shares all the data with the407 current environment except for cache and the overridden attributes.408 Extensions cannot be removed for an overlayed environment. An overlayed409 environment automatically gets all the extensions of the environment it410 is linked to plus optional extra extensions.411412 Creating overlays should happen after the initial environment was set413 up completely. Not all attributes are truly linked, some are just414 copied over so modifications on the original environment may not shine415 through.416 """417 args = dict(locals())418 del args["self"], args["cache_size"], args["extensions"]419420 rv = object.__new__(self.__class__)421 rv.__dict__.update(self.__dict__)422 rv.overlayed = True423 rv.linked_to = self424425 for key, value in iteritems(args):426 if value is not missing:427 setattr(rv, key, value)428429 if cache_size is not missing:430 rv.cache = create_cache(cache_size)431 else:432 rv.cache = copy_cache(self.cache)433434 rv.extensions = {}435 for key, value in iteritems(self.extensions):436 rv.extensions[key] = value.bind(rv)437 if extensions is not missing:438 rv.extensions.update(load_extensions(rv, extensions))439440 return _environment_sanity_check(rv)441442 lexer = property(get_lexer, doc="The lexer for this environment.")443444 def iter_extensions(self):445 """Iterates over the extensions by priority."""446 return iter(sorted(self.extensions.values(), key=lambda x: x.priority))447448 def getitem(self, obj, argument):449 """Get an item or attribute of an object but prefer the item."""450 try:451 return obj[argument]452 except (AttributeError, TypeError, LookupError):453 if isinstance(argument, string_types):454 try:455 attr = str(argument)456 except Exception:457 pass458 else:459 try:460 return getattr(obj, attr)461 except AttributeError:462 pass463 return self.undefined(obj=obj, name=argument)464465 def getattr(self, obj, attribute):466 """Get an item or attribute of an object but prefer the attribute.467 Unlike :meth:`getitem` the attribute *must* be a bytestring.468 """469 try:470 return getattr(obj, attribute)471 except AttributeError:472 pass473 try:474 return obj[attribute]475 except (TypeError, LookupError, AttributeError):476 return self.undefined(obj=obj, name=attribute)477478 def call_filter(479 self, name, value, args=None, kwargs=None, context=None, eval_ctx=None480 ):481 """Invokes a filter on a value the same way the compiler does it.482483 Note that on Python 3 this might return a coroutine in case the484 filter is running from an environment in async mode and the filter485 supports async execution. It's your responsibility to await this486 if needed.487488 .. versionadded:: 2.7489 """490 func = self.filters.get(name)491 if func is None:492 fail_for_missing_callable("no filter named %r", name)493 args = [value] + list(args or ())494 if getattr(func, "contextfilter", False):495 if context is None:496 raise TemplateRuntimeError(497 "Attempted to invoke context filter without context"498 )499 args.insert(0, context)500 elif getattr(func, "evalcontextfilter", False):501 if eval_ctx is None:502 if context is not None:503 eval_ctx = context.eval_ctx504 else:505 eval_ctx = EvalContext(self)506 args.insert(0, eval_ctx)507 elif getattr(func, "environmentfilter", False):508 args.insert(0, self)509 return func(*args, **(kwargs or {}))510511 def call_test(self, name, value, args=None, kwargs=None):512 """Invokes a test on a value the same way the compiler does it.513514 .. versionadded:: 2.7515 """516 func = self.tests.get(name)517 if func is None:518 fail_for_missing_callable("no test named %r", name)519 return func(value, *(args or ()), **(kwargs or {}))520521 @internalcode522 def parse(self, source, name=None, filename=None):523 """Parse the sourcecode and return the abstract syntax tree. This524 tree of nodes is used by the compiler to convert the template into525 executable source- or bytecode. This is useful for debugging or to526 extract information from templates.527528 If you are :ref:`developing Jinja extensions <writing-extensions>`529 this gives you a good overview of the node tree generated.530 """531 try:532 return self._parse(source, name, filename)533 except TemplateSyntaxError:534 self.handle_exception(source=source)535536 def _parse(self, source, name, filename):537 """Internal parsing function used by `parse` and `compile`."""538 return Parser(self, source, name, encode_filename(filename)).parse()539540 def lex(self, source, name=None, filename=None):541 """Lex the given sourcecode and return a generator that yields542 tokens as tuples in the form ``(lineno, token_type, value)``.543 This can be useful for :ref:`extension development <writing-extensions>`544 and debugging templates.545546 This does not perform preprocessing. If you want the preprocessing547 of the extensions to be applied you have to filter source through548 the :meth:`preprocess` method.549 """550 source = text_type(source)551 try:552 return self.lexer.tokeniter(source, name, filename)553 except TemplateSyntaxError:554 self.handle_exception(source=source)555556 def preprocess(self, source, name=None, filename=None):557 """Preprocesses the source with all extensions. This is automatically558 called for all parsing and compiling methods but *not* for :meth:`lex`559 because there you usually only want the actual source tokenized.560 """561 return reduce(562 lambda s, e: e.preprocess(s, name, filename),563 self.iter_extensions(),564 text_type(source),565 )566567 def _tokenize(self, source, name, filename=None, state=None):568 """Called by the parser to do the preprocessing and filtering569 for all the extensions. Returns a :class:`~jinja.lexer.TokenStream`.570 """571 source = self.preprocess(source, name, filename)572 stream = self.lexer.tokenize(source, name, filename, state)573 for ext in self.iter_extensions():574 stream = ext.filter_stream(stream)575 if not isinstance(stream, TokenStream):576 stream = TokenStream(stream, name, filename)577 return stream578579 def _generate(self, source, name, filename, defer_init=False):580 """Internal hook that can be overridden to hook a different generate581 method in.582583 .. versionadded:: 2.5584 """585 return generate(586 source,587 self,588 name,589 filename,590 defer_init=defer_init,591 optimized=self.optimized,592 )593594 def _compile(self, source, filename):595 """Internal hook that can be overridden to hook a different compile596 method in.597598 .. versionadded:: 2.5599 """600 return compile(source, filename, "exec")601602 @internalcode603 def compile(self, source, name=None, filename=None, raw=False, defer_init=False):604 """Compile a node or template source code. The `name` parameter is605 the load name of the template after it was joined using606 :meth:`join_path` if necessary, not the filename on the file system.607 the `filename` parameter is the estimated filename of the template on608 the file system. If the template came from a database or memory this609 can be omitted.610611 The return value of this method is a python code object. If the `raw`612 parameter is `True` the return value will be a string with python613 code equivalent to the bytecode returned otherwise. This method is614 mainly used internally.615616 `defer_init` is use internally to aid the module code generator. This617 causes the generated code to be able to import without the global618 environment variable to be set.619620 .. versionadded:: 2.4621 `defer_init` parameter added.622 """623 source_hint = None624 try:625 if isinstance(source, string_types):626 source_hint = source627 source = self._parse(source, name, filename)628 source = self._generate(source, name, filename, defer_init=defer_init)629 if raw:630 return source631 if filename is None:632 filename = "<template>"633 else:634 filename = encode_filename(filename)635 return self._compile(source, filename)636 except TemplateSyntaxError:637 self.handle_exception(source=source_hint)638639 def compile_expression(self, source, undefined_to_none=True):640 """A handy helper method that returns a callable that accepts keyword641 arguments that appear as variables in the expression. If called it642 returns the result of the expression.643644 This is useful if applications want to use the same rules as Jinja645 in template "configuration files" or similar situations.646647 Example usage:648649 >>> env = Environment()650 >>> expr = env.compile_expression('foo == 42')651 >>> expr(foo=23)652 False653 >>> expr(foo=42)654 True655656 Per default the return value is converted to `None` if the657 expression returns an undefined value. This can be changed658 by setting `undefined_to_none` to `False`.659660 >>> env.compile_expression('var')() is None661 True662 >>> env.compile_expression('var', undefined_to_none=False)()663 Undefined664665 .. versionadded:: 2.1666 """667 parser = Parser(self, source, state="variable")668 try:669 expr = parser.parse_expression()670 if not parser.stream.eos:671 raise TemplateSyntaxError(672 "chunk after expression", parser.stream.current.lineno, None, None673 )674 expr.set_environment(self)675 except TemplateSyntaxError:676 if sys.exc_info() is not None:677 self.handle_exception(source=source)678679 body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]680 template = self.from_string(nodes.Template(body, lineno=1))681 return TemplateExpression(template, undefined_to_none)682683 def compile_templates(684 self,685 target,686 extensions=None,687 filter_func=None,688 zip="deflated",689 log_function=None,690 ignore_errors=True,691 py_compile=False,692 ):693 """Finds all the templates the loader can find, compiles them694 and stores them in `target`. If `zip` is `None`, instead of in a695 zipfile, the templates will be stored in a directory.696 By default a deflate zip algorithm is used. To switch to697 the stored algorithm, `zip` can be set to ``'stored'``.698699 `extensions` and `filter_func` are passed to :meth:`list_templates`.700 Each template returned will be compiled to the target folder or701 zipfile.702703 By default template compilation errors are ignored. In case a704 log function is provided, errors are logged. If you want template705 syntax errors to abort the compilation you can set `ignore_errors`706 to `False` and you will get an exception on syntax errors.707708 If `py_compile` is set to `True` .pyc files will be written to the709 target instead of standard .py files. This flag does not do anything710 on pypy and Python 3 where pyc files are not picked up by itself and711 don't give much benefit.712713 .. versionadded:: 2.4714 """715 from .loaders import ModuleLoader716717 if log_function is None:718719 def log_function(x):720 pass721722 if py_compile:723 if not PY2 or PYPY:724 import warnings725726 warnings.warn(727 "'py_compile=True' has no effect on PyPy or Python"728 " 3 and will be removed in version 3.0",729 DeprecationWarning,730 stacklevel=2,731 )732 py_compile = False733 else:734 import imp735 import marshal736737 py_header = imp.get_magic() + u"\xff\xff\xff\xff".encode("iso-8859-15")738739 # Python 3.3 added a source filesize to the header740 if sys.version_info >= (3, 3):741 py_header += u"\x00\x00\x00\x00".encode("iso-8859-15")742743 def write_file(filename, data):744 if zip:745 info = ZipInfo(filename)746 info.external_attr = 0o755 << 16747 zip_file.writestr(info, data)748 else:749 if isinstance(data, text_type):750 data = data.encode("utf8")751752 with open(os.path.join(target, filename), "wb") as f:753 f.write(data)754755 if zip is not None:756 from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED757758 zip_file = ZipFile(759 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]760 )761 log_function('Compiling into Zip archive "%s"' % target)762 else:763 if not os.path.isdir(target):764 os.makedirs(target)765 log_function('Compiling into folder "%s"' % target)766767 try:768 for name in self.list_templates(extensions, filter_func):769 source, filename, _ = self.loader.get_source(self, name)770 try:771 code = self.compile(source, name, filename, True, True)772 except TemplateSyntaxError as e:773 if not ignore_errors:774 raise775 log_function('Could not compile "%s": %s' % (name, e))776 continue777778 filename = ModuleLoader.get_module_filename(name)779780 if py_compile:781 c = self._compile(code, encode_filename(filename))782 write_file(filename + "c", py_header + marshal.dumps(c))783 log_function('Byte-compiled "%s" as %s' % (name, filename + "c"))784 else:785 write_file(filename, code)786 log_function('Compiled "%s" as %s' % (name, filename))787 finally:788 if zip:789 zip_file.close()790791 log_function("Finished compiling templates")792793 def list_templates(self, extensions=None, filter_func=None):794 """Returns a list of templates for this environment. This requires795 that the loader supports the loader's796 :meth:`~BaseLoader.list_templates` method.797798 If there are other files in the template folder besides the799 actual templates, the returned list can be filtered. There are two800 ways: either `extensions` is set to a list of file extensions for801 templates, or a `filter_func` can be provided which is a callable that802 is passed a template name and should return `True` if it should end up803 in the result list.804805 If the loader does not support that, a :exc:`TypeError` is raised.806807 .. versionadded:: 2.4808 """809 names = self.loader.list_templates()810811 if extensions is not None:812 if filter_func is not None:813 raise TypeError(814 "either extensions or filter_func can be passed, but not both"815 )816817 def filter_func(x):818 return "." in x and x.rsplit(".", 1)[1] in extensions819820 if filter_func is not None:821 names = [name for name in names if filter_func(name)]822823 return names824825 def handle_exception(self, source=None):826 """Exception handling helper. This is used internally to either raise827 rewritten exceptions or return a rendered traceback for the template.828 """829 from .debug import rewrite_traceback_stack830831 reraise(*rewrite_traceback_stack(source=source))832833 def join_path(self, template, parent):834 """Join a template with the parent. By default all the lookups are835 relative to the loader root so this method returns the `template`836 parameter unchanged, but if the paths should be relative to the837 parent template, this function can be used to calculate the real838 template name.839840 Subclasses may override this method and implement template path841 joining here.842 """843 return template844845 @internalcode846 def _load_template(self, name, globals):847 if self.loader is None:848 raise TypeError("no loader for this environment specified")849 cache_key = (weakref.ref(self.loader), name)850 if self.cache is not None:851 template = self.cache.get(cache_key)852 if template is not None and (853 not self.auto_reload or template.is_up_to_date854 ):855 return template856 template = self.loader.load(self, name, globals)857 if self.cache is not None:858 self.cache[cache_key] = template859 return template860861 @internalcode862 def get_template(self, name, parent=None, globals=None):863 """Load a template from the loader. If a loader is configured this864 method asks the loader for the template and returns a :class:`Template`.865 If the `parent` parameter is not `None`, :meth:`join_path` is called866 to get the real template name before loading.867868 The `globals` parameter can be used to provide template wide globals.869 These variables are available in the context at render time.870871 If the template does not exist a :exc:`TemplateNotFound` exception is872 raised.873874 .. versionchanged:: 2.4875 If `name` is a :class:`Template` object it is returned from the876 function unchanged.877 """878 if isinstance(name, Template):879 return name880 if parent is not None:881 name = self.join_path(name, parent)882 return self._load_template(name, self.make_globals(globals))883884 @internalcode885 def select_template(self, names, parent=None, globals=None):886 """Works like :meth:`get_template` but tries a number of templates887 before it fails. If it cannot find any of the templates, it will888 raise a :exc:`TemplatesNotFound` exception.889890 .. versionchanged:: 2.11891 If names is :class:`Undefined`, an :exc:`UndefinedError` is892 raised instead. If no templates were found and names893 contains :class:`Undefined`, the message is more helpful.894895 .. versionchanged:: 2.4896 If `names` contains a :class:`Template` object it is returned897 from the function unchanged.898899 .. versionadded:: 2.3900 """901 if isinstance(names, Undefined):902 names._fail_with_undefined_error()903904 if not names:905 raise TemplatesNotFound(906 message=u"Tried to select from an empty list " u"of templates."907 )908 globals = self.make_globals(globals)909 for name in names:910 if isinstance(name, Template):911 return name912 if parent is not None:913 name = self.join_path(name, parent)914 try:915 return self._load_template(name, globals)916 except (TemplateNotFound, UndefinedError):917 pass918 raise TemplatesNotFound(names)919920 @internalcode921 def get_or_select_template(self, template_name_or_list, parent=None, globals=None):922 """Does a typecheck and dispatches to :meth:`select_template`923 if an iterable of template names is given, otherwise to924 :meth:`get_template`.925926 .. versionadded:: 2.3927 """928 if isinstance(template_name_or_list, (string_types, Undefined)):929 return self.get_template(template_name_or_list, parent, globals)930 elif isinstance(template_name_or_list, Template):931 return template_name_or_list932 return self.select_template(template_name_or_list, parent, globals)933934 def from_string(self, source, globals=None, template_class=None):935 """Load a template from a string. This parses the source given and936 returns a :class:`Template` object.937 """938 globals = self.make_globals(globals)939 cls = template_class or self.template_class940 return cls.from_code(self, self.compile(source), globals, None)941942 def make_globals(self, d):943 """Return a dict for the globals."""944 if not d:945 return self.globals946 return dict(self.globals, **d)947948949class Template(object):950 """The central template object. This class represents a compiled template951 and is used to evaluate it.952953 Normally the template object is generated from an :class:`Environment` but954 it also has a constructor that makes it possible to create a template955 instance directly using the constructor. It takes the same arguments as956 the environment constructor but it's not possible to specify a loader.957958 Every template object has a few methods and members that are guaranteed959 to exist. However it's important that a template object should be960 considered immutable. Modifications on the object are not supported.961962 Template objects created from the constructor rather than an environment963 do have an `environment` attribute that points to a temporary environment964 that is probably shared with other templates created with the constructor965 and compatible settings.966967 >>> template = Template('Hello {{ name }}!')968 >>> template.render(name='John Doe') == u'Hello John Doe!'969 True970 >>> stream = template.stream(name='John Doe')971 >>> next(stream) == u'Hello John Doe!'972 True973 >>> next(stream)974 Traceback (most recent call last):975 ...976 StopIteration977 """978979 #: Type of environment to create when creating a template directly980 #: rather than through an existing environment.981 environment_class = Environment982983 def __new__(984 cls,985 source,986 block_start_string=BLOCK_START_STRING,987 block_end_string=BLOCK_END_STRING,988 variable_start_string=VARIABLE_START_STRING,989 variable_end_string=VARIABLE_END_STRING,990 comment_start_string=COMMENT_START_STRING,991 comment_end_string=COMMENT_END_STRING,992 line_statement_prefix=LINE_STATEMENT_PREFIX,993 line_comment_prefix=LINE_COMMENT_PREFIX,994 trim_blocks=TRIM_BLOCKS,995 lstrip_blocks=LSTRIP_BLOCKS,996 newline_sequence=NEWLINE_SEQUENCE,997 keep_trailing_newline=KEEP_TRAILING_NEWLINE,998 extensions=(),999 optimized=True,1000 undefined=Undefined,1001 finalize=None,1002 autoescape=False,1003 enable_async=False,1004 ):1005 env = get_spontaneous_environment(1006 cls.environment_class,1007 block_start_string,1008 block_end_string,1009 variable_start_string,1010 variable_end_string,1011 comment_start_string,1012 comment_end_string,1013 line_statement_prefix,1014 line_comment_prefix,1015 trim_blocks,1016 lstrip_blocks,1017 newline_sequence,1018 keep_trailing_newline,1019 frozenset(extensions),1020 optimized,1021 undefined,1022 finalize,1023 autoescape,1024 None,1025 0,1026 False,1027 None,1028 enable_async,1029 )1030 return env.from_string(source, template_class=cls)10311032 @classmethod1033 def from_code(cls, environment, code, globals, uptodate=None):1034 """Creates a template object from compiled code and the globals. This1035 is used by the loaders and environment to create a template object.1036 """1037 namespace = {"environment": environment, "__file__": code.co_filename}1038 exec(code, namespace)1039 rv = cls._from_namespace(environment, namespace, globals)1040 rv._uptodate = uptodate1041 return rv10421043 @classmethod1044 def from_module_dict(cls, environment, module_dict, globals):1045 """Creates a template object from a module. This is used by the1046 module loader to create a template object.10471048 .. versionadded:: 2.41049 """1050 return cls._from_namespace(environment, module_dict, globals)10511052 @classmethod1053 def _from_namespace(cls, environment, namespace, globals):1054 t = object.__new__(cls)1055 t.environment = environment1056 t.globals = globals1057 t.name = namespace["name"]1058 t.filename = namespace["__file__"]1059 t.blocks = namespace["blocks"]10601061 # render function and module1062 t.root_render_func = namespace["root"]1063 t._module = None10641065 # debug and loader helpers1066 t._debug_info = namespace["debug_info"]1067 t._uptodate = None10681069 # store the reference1070 namespace["environment"] = environment1071 namespace["__jinja_template__"] = t10721073 return t10741075 def render(self, *args, **kwargs):1076 """This method accepts the same arguments as the `dict` constructor:1077 A dict, a dict subclass or some keyword arguments. If no arguments1078 are given the context will be empty. These two calls do the same::10791080 template.render(knights='that say nih')1081 template.render({'knights': 'that say nih'})10821083 This will return the rendered template as unicode string.1084 """1085 vars = dict(*args, **kwargs)1086 try:1087 return concat(self.root_render_func(self.new_context(vars)))1088 except Exception:1089 self.environment.handle_exception()10901091 def render_async(self, *args, **kwargs):1092 """This works similar to :meth:`render` but returns a coroutine1093 that when awaited returns the entire rendered template string. This1094 requires the async feature to be enabled.10951096 Example usage::10971098 await template.render_async(knights='that say nih; asynchronously')1099 """1100 # see asyncsupport for the actual implementation1101 raise NotImplementedError(1102 "This feature is not available for this version of Python"1103 )11041105 def stream(self, *args, **kwargs):1106 """Works exactly like :meth:`generate` but returns a1107 :class:`TemplateStream`.1108 """1109 return TemplateStream(self.generate(*args, **kwargs))11101111 def generate(self, *args, **kwargs):1112 """For very large templates it can be useful to not render the whole1113 template at once but evaluate each statement after another and yield1114 piece for piece. This method basically does exactly that and returns1115 a generator that yields one item after another as unicode strings.11161117 It accepts the same arguments as :meth:`render`.1118 """1119 vars = dict(*args, **kwargs)1120 try:1121 for event in self.root_render_func(self.new_context(vars)):1122 yield event1123 except Exception:1124 yield self.environment.handle_exception()11251126 def generate_async(self, *args, **kwargs):1127 """An async version of :meth:`generate`. Works very similarly but1128 returns an async iterator instead.1129 """1130 # see asyncsupport for the actual implementation1131 raise NotImplementedError(1132 "This feature is not available for this version of Python"1133 )11341135 def new_context(self, vars=None, shared=False, locals=None):1136 """Create a new :class:`Context` for this template. The vars1137 provided will be passed to the template. Per default the globals1138 are added to the context. If shared is set to `True` the data1139 is passed as is to the context without adding the globals.11401141 `locals` can be a dict of local variables for internal usage.1142 """1143 return new_context(1144 self.environment, self.name, self.blocks, vars, shared, self.globals, locals1145 )11461147 def make_module(self, vars=None, shared=False, locals=None):1148 """This method works like the :attr:`module` attribute when called1149 without arguments but it will evaluate the template on every call1150 rather than caching it. It's also possible to provide1151 a dict which is then used as context. The arguments are the same1152 as for the :meth:`new_context` method.1153 """1154 return TemplateModule(self, self.new_context(vars, shared, locals))11551156 def make_module_async(self, vars=None, shared=False, locals=None):1157 """As template module creation can invoke template code for1158 asynchronous executions this method must be used instead of the1159 normal :meth:`make_module` one. Likewise the module attribute1160 becomes unavailable in async mode.1161 """1162 # see asyncsupport for the actual implementation1163 raise NotImplementedError(1164 "This feature is not available for this version of Python"1165 )11661167 @internalcode1168 def _get_default_module(self):1169 if self._module is not None:1170 return self._module1171 self._module = rv = self.make_module()1172 return rv11731174 @property1175 def module(self):1176 """The template as module. This is used for imports in the1177 template runtime but is also useful if one wants to access1178 exported template variables from the Python layer:11791180 >>> t = Template('{% macro foo() %}42{% endmacro %}23')1181 >>> str(t.module)1182 '23'1183 >>> t.module.foo() == u'42'1184 True11851186 This attribute is not available if async mode is enabled.1187 """1188 return self._get_default_module()11891190 def get_corresponding_lineno(self, lineno):1191 """Return the source line number of a line number in the1192 generated bytecode as they are not in sync.1193 """1194 for template_line, code_line in reversed(self.debug_info):1195 if code_line <= lineno:1196 return template_line1197 return 111981199 @property1200 def is_up_to_date(self):1201 """If this variable is `False` there is a newer version available."""1202 if self._uptodate is None:1203 return True1204 return self._uptodate()12051206 @property1207 def debug_info(self):1208 """The debug info mapping."""1209 if self._debug_info:1210 return [tuple(map(int, x.split("="))) for x in self._debug_info.split("&")]1211 return []12121213 def __repr__(self):1214 if self.name is None:1215 name = "memory:%x" % id(self)1216 else:1217 name = repr(self.name)1218 return "<%s %s>" % (self.__class__.__name__, name)121912201221@implements_to_string1222class TemplateModule(object):1223 """Represents an imported template. All the exported names of the1224 template are available as attributes on this object. Additionally1225 converting it into an unicode- or bytestrings renders the contents.1226 """12271228 def __init__(self, template, context, body_stream=None):1229 if body_stream is None:1230 if context.environment.is_async:1231 raise RuntimeError(1232 "Async mode requires a body stream "1233 "to be passed to a template module. Use "1234 "the async methods of the API you are "1235 "using."1236 )1237 body_stream = list(template.root_render_func(context))1238 self._body_stream = body_stream1239 self.__dict__.update(context.get_exported())1240 self.__name__ = template.name12411242 def __html__(self):1243 return Markup(concat(self._body_stream))12441245 def __str__(self):1246 return concat(self._body_stream)12471248 def __repr__(self):1249 if self.__name__ is None:1250 name = "memory:%x" % id(self)1251 else:1252 name = repr(self.__name__)1253 return "<%s %s>" % (self.__class__.__name__, name)125412551256class TemplateExpression(object):1257 """The :meth:`jinja.Environment.compile_expression` method returns an1258 instance of this object. It encapsulates the expression-like access1259 to the template with an expression it wraps.1260 """12611262 def __init__(self, template, undefined_to_none):1263 self._template = template1264 self._undefined_to_none = undefined_to_none12651266 def __call__(self, *args, **kwargs):1267 context = self._template.new_context(dict(*args, **kwargs))1268 consume(self._template.root_render_func(context))1269 rv = context.vars["result"]1270 if self._undefined_to_none and isinstance(rv, Undefined):1271 rv = None1272 return rv127312741275@implements_iterator1276class TemplateStream(object):1277 """A template stream works pretty much like an ordinary python generator1278 but it can buffer multiple items to reduce the number of total iterations.1279 Per default the output is unbuffered which means that for every unbuffered1280 instruction in the template one unicode string is yielded.12811282 If buffering is enabled with a buffer size of 5, five items are combined1283 into a new unicode string. This is mainly useful if you are streaming1284 big templates to a client via WSGI which flushes after each iteration.1285 """12861287 def __init__(self, gen):1288 self._gen = gen1289 self.disable_buffering()12901291 def dump(self, fp, encoding=None, errors="strict"):1292 """Dump the complete stream into a file or file-like object.1293 Per default unicode strings are written, if you want to encode1294 before writing specify an `encoding`.12951296 Example usage::12971298 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1299 """1300 close = False1301 if isinstance(fp, string_types):1302 if encoding is None:1303 encoding = "utf-8"1304 fp = open(fp, "wb")1305 close = True1306 try:1307 if encoding is not None:1308 iterable = (x.encode(encoding, errors) for x in self)1309 else:1310 iterable = self1311 if hasattr(fp, "writelines"):1312 fp.writelines(iterable)1313 else:1314 for item in iterable:1315 fp.write(item)1316 finally:1317 if close:1318 fp.close()13191320 def disable_buffering(self):1321 """Disable the output buffering."""1322 self._next = partial(next, self._gen)1323 self.buffered = False13241325 def _buffered_generator(self, size):1326 buf = []1327 c_size = 01328 push = buf.append13291330 while 1:1331 try:1332 while c_size < size:1333 c = next(self._gen)1334 push(c)1335 if c:1336 c_size += 11337 except StopIteration:1338 if not c_size:1339 return1340 yield concat(buf)1341 del buf[:]1342 c_size = 013431344 def enable_buffering(self, size=5):1345 """Enable buffering. Buffer `size` items before yielding them."""1346 if size <= 1:1347 raise ValueError("buffer size too small")13481349 self.buffered = True1350 self._next = partial(next, self._buffered_generator(size))13511352 def __iter__(self):1353 return self13541355 def __next__(self):1356 return self._next()135713581359# hook in default template class. if anyone reads this comment: ignore that1360# it's possible to use custom templates ;-)1361Environment.template_class = Template
added:src/jinja/exceptions.py+177 added
1# -*- coding: utf-8 -*-2from ._compat import imap3from ._compat import implements_to_string4from ._compat import PY25from ._compat import text_type678class TemplateError(Exception):9 """Baseclass for all template errors."""1011 if PY2:1213 def __init__(self, message=None):14 if message is not None:15 message = text_type(message).encode("utf-8")16 Exception.__init__(self, message)1718 @property19 def message(self):20 if self.args:21 message = self.args[0]22 if message is not None:23 return message.decode("utf-8", "replace")2425 def __unicode__(self):26 return self.message or u""2728 else:2930 def __init__(self, message=None):31 Exception.__init__(self, message)3233 @property34 def message(self):35 if self.args:36 message = self.args[0]37 if message is not None:38 return message394041@implements_to_string42class TemplateNotFound(IOError, LookupError, TemplateError):43 """Raised if a template does not exist.4445 .. versionchanged:: 2.1146 If the given name is :class:`Undefined` and no message was47 provided, an :exc:`UndefinedError` is raised.48 """4950 # looks weird, but removes the warning descriptor that just51 # bogusly warns us about message being deprecated52 message = None5354 def __init__(self, name, message=None):55 IOError.__init__(self, name)5657 if message is None:58 from .runtime import Undefined5960 if isinstance(name, Undefined):61 name._fail_with_undefined_error()6263 message = name6465 self.message = message66 self.name = name67 self.templates = [name]6869 def __str__(self):70 return self.message717273class TemplatesNotFound(TemplateNotFound):74 """Like :class:`TemplateNotFound` but raised if multiple templates75 are selected. This is a subclass of :class:`TemplateNotFound`76 exception, so just catching the base exception will catch both.7778 .. versionchanged:: 2.1179 If a name in the list of names is :class:`Undefined`, a message80 about it being undefined is shown rather than the empty string.8182 .. versionadded:: 2.283 """8485 def __init__(self, names=(), message=None):86 if message is None:87 from .runtime import Undefined8889 parts = []9091 for name in names:92 if isinstance(name, Undefined):93 parts.append(name._undefined_message)94 else:95 parts.append(name)9697 message = u"none of the templates given were found: " + u", ".join(98 imap(text_type, parts)99 )100 TemplateNotFound.__init__(self, names and names[-1] or None, message)101 self.templates = list(names)102103104@implements_to_string105class TemplateSyntaxError(TemplateError):106 """Raised to tell the user that there is a problem with the template."""107108 def __init__(self, message, lineno, name=None, filename=None):109 TemplateError.__init__(self, message)110 self.lineno = lineno111 self.name = name112 self.filename = filename113 self.source = None114115 # this is set to True if the debug.translate_syntax_error116 # function translated the syntax error into a new traceback117 self.translated = False118119 def __str__(self):120 # for translated errors we only return the message121 if self.translated:122 return self.message123124 # otherwise attach some stuff125 location = "line %d" % self.lineno126 name = self.filename or self.name127 if name:128 location = 'File "%s", %s' % (name, location)129 lines = [self.message, " " + location]130131 # if the source is set, add the line to the output132 if self.source is not None:133 try:134 line = self.source.splitlines()[self.lineno - 1]135 except IndexError:136 line = None137 if line:138 lines.append(" " + line.strip())139140 return u"\n".join(lines)141142 def __reduce__(self):143 # https://bugs.python.org/issue1692335 Exceptions that take144 # multiple required arguments have problems with pickling.145 # Without this, raises TypeError: __init__() missing 1 required146 # positional argument: 'lineno'147 return self.__class__, (self.message, self.lineno, self.name, self.filename)148149150class TemplateAssertionError(TemplateSyntaxError):151 """Like a template syntax error, but covers cases where something in the152 template caused an error at compile time that wasn't necessarily caused153 by a syntax error. However it's a direct subclass of154 :exc:`TemplateSyntaxError` and has the same attributes.155 """156157158class TemplateRuntimeError(TemplateError):159 """A generic runtime error in the template engine. Under some situations160 Jinja may raise this exception.161 """162163164class UndefinedError(TemplateRuntimeError):165 """Raised if a template tries to operate on :class:`Undefined`."""166167168class SecurityError(TemplateRuntimeError):169 """Raised if a template tries to do something insecure if the170 sandbox is enabled.171 """172173174class FilterArgumentError(TemplateRuntimeError):175 """This error is raised if a filter was called with inappropriate176 arguments177 """
added:src/jinja/ext.py+703 added
1# -*- coding: utf-8 -*-2"""Extension API for adding custom tags and behavior."""3import pprint4import re5from sys import version_info67from . import nodes8from ._compat import iteritems9from ._compat import string_types10from ._compat import with_metaclass11from .defaults import BLOCK_END_STRING12from .defaults import BLOCK_START_STRING13from .defaults import COMMENT_END_STRING14from .defaults import COMMENT_START_STRING15from .defaults import KEEP_TRAILING_NEWLINE16from .defaults import LINE_COMMENT_PREFIX17from .defaults import LINE_STATEMENT_PREFIX18from .defaults import LSTRIP_BLOCKS19from .defaults import NEWLINE_SEQUENCE20from .defaults import TRIM_BLOCKS21from .defaults import VARIABLE_END_STRING22from .defaults import VARIABLE_START_STRING23from .environment import Environment24from .exceptions import TemplateAssertionError25from .exceptions import TemplateSyntaxError26from .nodes import ContextReference27from .runtime import concat28from .utils import contextfunction29from .utils import import_string30from .utils import Markup3132# the only real useful gettext functions for a Jinja template. Note33# that ugettext must be assigned to gettext as Jinja doesn't support34# non unicode strings.35GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext")3637_ws_re = re.compile(r"\s*\n\s*")383940class ExtensionRegistry(type):41 """Gives the extension an unique identifier."""4243 def __new__(mcs, name, bases, d):44 rv = type.__new__(mcs, name, bases, d)45 rv.identifier = rv.__module__ + "." + rv.__name__46 return rv474849class Extension(with_metaclass(ExtensionRegistry, object)):50 """Extensions can be used to add extra functionality to the Jinja template51 system at the parser level. Custom extensions are bound to an environment52 but may not store environment specific data on `self`. The reason for53 this is that an extension can be bound to another environment (for54 overlays) by creating a copy and reassigning the `environment` attribute.5556 As extensions are created by the environment they cannot accept any57 arguments for configuration. One may want to work around that by using58 a factory function, but that is not possible as extensions are identified59 by their import name. The correct way to configure the extension is60 storing the configuration values on the environment. Because this way the61 environment ends up acting as central configuration storage the62 attributes may clash which is why extensions have to ensure that the names63 they choose for configuration are not too generic. ``prefix`` for example64 is a terrible name, ``fragment_cache_prefix`` on the other hand is a good65 name as includes the name of the extension (fragment cache).66 """6768 #: if this extension parses this is the list of tags it's listening to.69 tags = set()7071 #: the priority of that extension. This is especially useful for72 #: extensions that preprocess values. A lower value means higher73 #: priority.74 #:75 #: .. versionadded:: 2.476 priority = 1007778 def __init__(self, environment):79 self.environment = environment8081 def bind(self, environment):82 """Create a copy of this extension bound to another environment."""83 rv = object.__new__(self.__class__)84 rv.__dict__.update(self.__dict__)85 rv.environment = environment86 return rv8788 def preprocess(self, source, name, filename=None):89 """This method is called before the actual lexing and can be used to90 preprocess the source. The `filename` is optional. The return value91 must be the preprocessed source.92 """93 return source9495 def filter_stream(self, stream):96 """It's passed a :class:`~jinja.lexer.TokenStream` that can be used97 to filter tokens returned. This method has to return an iterable of98 :class:`~jinja.lexer.Token`\\s, but it doesn't have to return a99 :class:`~jinja.lexer.TokenStream`.100 """101 return stream102103 def parse(self, parser):104 """If any of the :attr:`tags` matched this method is called with the105 parser as first argument. The token the parser stream is pointing at106 is the name token that matched. This method has to return one or a107 list of multiple nodes.108 """109 raise NotImplementedError()110111 def attr(self, name, lineno=None):112 """Return an attribute node for the current extension. This is useful113 to pass constants on extensions to generated template code.114115 ::116117 self.attr('_my_attribute', lineno=lineno)118 """119 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)120121 def call_method(122 self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None123 ):124 """Call a method of the extension. This is a shortcut for125 :meth:`attr` + :class:`jinja.nodes.Call`.126 """127 if args is None:128 args = []129 if kwargs is None:130 kwargs = []131 return nodes.Call(132 self.attr(name, lineno=lineno),133 args,134 kwargs,135 dyn_args,136 dyn_kwargs,137 lineno=lineno,138 )139140141@contextfunction142def _gettext_alias(__context, *args, **kwargs):143 return __context.call(__context.resolve("gettext"), *args, **kwargs)144145146def _make_new_gettext(func):147 @contextfunction148 def gettext(__context, __string, **variables):149 rv = __context.call(func, __string)150 if __context.eval_ctx.autoescape:151 rv = Markup(rv)152 # Always treat as a format string, even if there are no153 # variables. This makes translation strings more consistent154 # and predictable. This requires escaping155 return rv % variables156157 return gettext158159160def _make_new_ngettext(func):161 @contextfunction162 def ngettext(__context, __singular, __plural, __num, **variables):163 variables.setdefault("num", __num)164 rv = __context.call(func, __singular, __plural, __num)165 if __context.eval_ctx.autoescape:166 rv = Markup(rv)167 # Always treat as a format string, see gettext comment above.168 return rv % variables169170 return ngettext171172173class InternationalizationExtension(Extension):174 """This extension adds gettext support to Jinja."""175176 tags = {"trans"}177178 # TODO: the i18n extension is currently reevaluating values in a few179 # situations. Take this example:180 # {% trans count=something() %}{{ count }} foo{% pluralize181 # %}{{ count }} fooss{% endtrans %}182 # something is called twice here. One time for the gettext value and183 # the other time for the n-parameter of the ngettext function.184185 def __init__(self, environment):186 Extension.__init__(self, environment)187 environment.globals["_"] = _gettext_alias188 environment.extend(189 install_gettext_translations=self._install,190 install_null_translations=self._install_null,191 install_gettext_callables=self._install_callables,192 uninstall_gettext_translations=self._uninstall,193 extract_translations=self._extract,194 newstyle_gettext=False,195 )196197 def _install(self, translations, newstyle=None):198 gettext = getattr(translations, "ugettext", None)199 if gettext is None:200 gettext = translations.gettext201 ngettext = getattr(translations, "ungettext", None)202 if ngettext is None:203 ngettext = translations.ngettext204 self._install_callables(gettext, ngettext, newstyle)205206 def _install_null(self, newstyle=None):207 self._install_callables(208 lambda x: x, lambda s, p, n: (n != 1 and (p,) or (s,))[0], newstyle209 )210211 def _install_callables(self, gettext, ngettext, newstyle=None):212 if newstyle is not None:213 self.environment.newstyle_gettext = newstyle214 if self.environment.newstyle_gettext:215 gettext = _make_new_gettext(gettext)216 ngettext = _make_new_ngettext(ngettext)217 self.environment.globals.update(gettext=gettext, ngettext=ngettext)218219 def _uninstall(self, translations):220 for key in "gettext", "ngettext":221 self.environment.globals.pop(key, None)222223 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):224 if isinstance(source, string_types):225 source = self.environment.parse(source)226 return extract_from_ast(source, gettext_functions)227228 def parse(self, parser):229 """Parse a translatable tag."""230 lineno = next(parser.stream).lineno231 num_called_num = False232233 # find all the variables referenced. Additionally a variable can be234 # defined in the body of the trans block too, but this is checked at235 # a later state.236 plural_expr = None237 plural_expr_assignment = None238 variables = {}239 trimmed = None240 while parser.stream.current.type != "block_end":241 if variables:242 parser.stream.expect("comma")243244 # skip colon for python compatibility245 if parser.stream.skip_if("colon"):246 break247248 name = parser.stream.expect("name")249 if name.value in variables:250 parser.fail(251 "translatable variable %r defined twice." % name.value,252 name.lineno,253 exc=TemplateAssertionError,254 )255256 # expressions257 if parser.stream.current.type == "assign":258 next(parser.stream)259 variables[name.value] = var = parser.parse_expression()260 elif trimmed is None and name.value in ("trimmed", "notrimmed"):261 trimmed = name.value == "trimmed"262 continue263 else:264 variables[name.value] = var = nodes.Name(name.value, "load")265266 if plural_expr is None:267 if isinstance(var, nodes.Call):268 plural_expr = nodes.Name("_trans", "load")269 variables[name.value] = plural_expr270 plural_expr_assignment = nodes.Assign(271 nodes.Name("_trans", "store"), var272 )273 else:274 plural_expr = var275 num_called_num = name.value == "num"276277 parser.stream.expect("block_end")278279 plural = None280 have_plural = False281 referenced = set()282283 # now parse until endtrans or pluralize284 singular_names, singular = self._parse_block(parser, True)285 if singular_names:286 referenced.update(singular_names)287 if plural_expr is None:288 plural_expr = nodes.Name(singular_names[0], "load")289 num_called_num = singular_names[0] == "num"290291 # if we have a pluralize block, we parse that too292 if parser.stream.current.test("name:pluralize"):293 have_plural = True294 next(parser.stream)295 if parser.stream.current.type != "block_end":296 name = parser.stream.expect("name")297 if name.value not in variables:298 parser.fail(299 "unknown variable %r for pluralization" % name.value,300 name.lineno,301 exc=TemplateAssertionError,302 )303 plural_expr = variables[name.value]304 num_called_num = name.value == "num"305 parser.stream.expect("block_end")306 plural_names, plural = self._parse_block(parser, False)307 next(parser.stream)308 referenced.update(plural_names)309 else:310 next(parser.stream)311312 # register free names as simple name expressions313 for var in referenced:314 if var not in variables:315 variables[var] = nodes.Name(var, "load")316317 if not have_plural:318 plural_expr = None319 elif plural_expr is None:320 parser.fail("pluralize without variables", lineno)321322 if trimmed is None:323 trimmed = self.environment.policies["ext.i18n.trimmed"]324 if trimmed:325 singular = self._trim_whitespace(singular)326 if plural:327 plural = self._trim_whitespace(plural)328329 node = self._make_node(330 singular,331 plural,332 variables,333 plural_expr,334 bool(referenced),335 num_called_num and have_plural,336 )337 node.set_lineno(lineno)338 if plural_expr_assignment is not None:339 return [plural_expr_assignment, node]340 else:341 return node342343 def _trim_whitespace(self, string, _ws_re=_ws_re):344 return _ws_re.sub(" ", string.strip())345346 def _parse_block(self, parser, allow_pluralize):347 """Parse until the next block tag with a given name."""348 referenced = []349 buf = []350 while 1:351 if parser.stream.current.type == "data":352 buf.append(parser.stream.current.value.replace("%", "%%"))353 next(parser.stream)354 elif parser.stream.current.type == "variable_begin":355 next(parser.stream)356 name = parser.stream.expect("name").value357 referenced.append(name)358 buf.append("%%(%s)s" % name)359 parser.stream.expect("variable_end")360 elif parser.stream.current.type == "block_begin":361 next(parser.stream)362 if parser.stream.current.test("name:endtrans"):363 break364 elif parser.stream.current.test("name:pluralize"):365 if allow_pluralize:366 break367 parser.fail(368 "a translatable section can have only one pluralize section"369 )370 parser.fail(371 "control structures in translatable sections are not allowed"372 )373 elif parser.stream.eos:374 parser.fail("unclosed translation block")375 else:376 raise RuntimeError("internal parser error")377378 return referenced, concat(buf)379380 def _make_node(381 self, singular, plural, variables, plural_expr, vars_referenced, num_called_num382 ):383 """Generates a useful node from the data provided."""384 # no variables referenced? no need to escape for old style385 # gettext invocations only if there are vars.386 if not vars_referenced and not self.environment.newstyle_gettext:387 singular = singular.replace("%%", "%")388 if plural:389 plural = plural.replace("%%", "%")390391 # singular only:392 if plural_expr is None:393 gettext = nodes.Name("gettext", "load")394 node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None)395396 # singular and plural397 else:398 ngettext = nodes.Name("ngettext", "load")399 node = nodes.Call(400 ngettext,401 [nodes.Const(singular), nodes.Const(plural), plural_expr],402 [],403 None,404 None,405 )406407 # in case newstyle gettext is used, the method is powerful408 # enough to handle the variable expansion and autoescape409 # handling itself410 if self.environment.newstyle_gettext:411 for key, value in iteritems(variables):412 # the function adds that later anyways in case num was413 # called num, so just skip it.414 if num_called_num and key == "num":415 continue416 node.kwargs.append(nodes.Keyword(key, value))417418 # otherwise do that here419 else:420 # mark the return value as safe if we are in an421 # environment with autoescaping turned on422 node = nodes.MarkSafeIfAutoescape(node)423 if variables:424 node = nodes.Mod(425 node,426 nodes.Dict(427 [428 nodes.Pair(nodes.Const(key), value)429 for key, value in variables.items()430 ]431 ),432 )433 return nodes.Output([node])434435436class ExprStmtExtension(Extension):437 """Adds a `do` tag to Jinja that works like the print statement just438 that it doesn't print the return value.439 """440441 tags = set(["do"])442443 def parse(self, parser):444 node = nodes.ExprStmt(lineno=next(parser.stream).lineno)445 node.node = parser.parse_tuple()446 return node447448449class LoopControlExtension(Extension):450 """Adds break and continue to the template engine."""451452 tags = set(["break", "continue"])453454 def parse(self, parser):455 token = next(parser.stream)456 if token.value == "break":457 return nodes.Break(lineno=token.lineno)458 return nodes.Continue(lineno=token.lineno)459460461class WithExtension(Extension):462 pass463464465class AutoEscapeExtension(Extension):466 pass467468469class DebugExtension(Extension):470 """A ``{% debug %}`` tag that dumps the available variables,471 filters, and tests.472473 .. code-block:: html+jinja474475 <pre>{% debug %}</pre>476477 .. code-block:: text478479 {'context': {'cycler': <class 'jinja.utils.Cycler'>,480 ...,481 'namespace': <class 'jinja.utils.Namespace'>},482 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',483 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],484 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',485 ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}486487 .. versionadded:: 2.11.0488 """489490 tags = {"debug"}491492 def parse(self, parser):493 lineno = parser.stream.expect("name:debug").lineno494 context = ContextReference()495 result = self.call_method("_render", [context], lineno=lineno)496 return nodes.Output([result], lineno=lineno)497498 def _render(self, context):499 result = {500 "context": context.get_all(),501 "filters": sorted(self.environment.filters.keys()),502 "tests": sorted(self.environment.tests.keys()),503 }504505 # Set the depth since the intent is to show the top few names.506 if version_info[:2] >= (3, 4):507 return pprint.pformat(result, depth=3, compact=True)508 else:509 return pprint.pformat(result, depth=3)510511512def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True):513 """Extract localizable strings from the given template node. Per514 default this function returns matches in babel style that means non string515 parameters as well as keyword arguments are returned as `None`. This516 allows Babel to figure out what you really meant if you are using517 gettext functions that allow keyword arguments for placeholder expansion.518 If you don't want that behavior set the `babel_style` parameter to `False`519 which causes only strings to be returned and parameters are always stored520 in tuples. As a consequence invalid gettext calls (calls without a single521 string parameter or string parameters after non-string parameters) are522 skipped.523524 This example explains the behavior:525526 >>> from jinja import Environment527 >>> env = Environment()528 >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')529 >>> list(extract_from_ast(node))530 [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]531 >>> list(extract_from_ast(node, babel_style=False))532 [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]533534 For every string found this function yields a ``(lineno, function,535 message)`` tuple, where:536537 * ``lineno`` is the number of the line on which the string was found,538 * ``function`` is the name of the ``gettext`` function used (if the539 string was extracted from embedded Python code), and540 * ``message`` is the string itself (a ``unicode`` object, or a tuple541 of ``unicode`` objects for functions with multiple string arguments).542543 This extraction function operates on the AST and is because of that unable544 to extract any comments. For comment support you have to use the babel545 extraction interface or extract comments yourself.546 """547 for node in node.find_all(nodes.Call):548 if (549 not isinstance(node.node, nodes.Name)550 or node.node.name not in gettext_functions551 ):552 continue553554 strings = []555 for arg in node.args:556 if isinstance(arg, nodes.Const) and isinstance(arg.value, string_types):557 strings.append(arg.value)558 else:559 strings.append(None)560561 for _ in node.kwargs:562 strings.append(None)563 if node.dyn_args is not None:564 strings.append(None)565 if node.dyn_kwargs is not None:566 strings.append(None)567568 if not babel_style:569 strings = tuple(x for x in strings if x is not None)570 if not strings:571 continue572 else:573 if len(strings) == 1:574 strings = strings[0]575 else:576 strings = tuple(strings)577 yield node.lineno, node.node.name, strings578579580class _CommentFinder(object):581 """Helper class to find comments in a token stream. Can only582 find comments for gettext calls forwards. Once the comment583 from line 4 is found, a comment for line 1 will not return a584 usable value.585 """586587 def __init__(self, tokens, comment_tags):588 self.tokens = tokens589 self.comment_tags = comment_tags590 self.offset = 0591 self.last_lineno = 0592593 def find_backwards(self, offset):594 try:595 for _, token_type, token_value in reversed(596 self.tokens[self.offset : offset]597 ):598 if token_type in ("comment", "linecomment"):599 try:600 prefix, comment = token_value.split(None, 1)601 except ValueError:602 continue603 if prefix in self.comment_tags:604 return [comment.rstrip()]605 return []606 finally:607 self.offset = offset608609 def find_comments(self, lineno):610 if not self.comment_tags or self.last_lineno > lineno:611 return []612 for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):613 if token_lineno > lineno:614 return self.find_backwards(self.offset + idx)615 return self.find_backwards(len(self.tokens))616617618def babel_extract(fileobj, keywords, comment_tags, options):619 """Babel extraction method for Jinja templates.620621 .. versionchanged:: 2.3622 Basic support for translation comments was added. If `comment_tags`623 is now set to a list of keywords for extraction, the extractor will624 try to find the best preceding comment that begins with one of the625 keywords. For best results, make sure to not have more than one626 gettext call in one line of code and the matching comment in the627 same line or the line before.628629 .. versionchanged:: 2.5.1630 The `newstyle_gettext` flag can be set to `True` to enable newstyle631 gettext calls.632633 .. versionchanged:: 2.7634 A `silent` option can now be provided. If set to `False` template635 syntax errors are propagated instead of being ignored.636637 :param fileobj: the file-like object the messages should be extracted from638 :param keywords: a list of keywords (i.e. function names) that should be639 recognized as translation functions640 :param comment_tags: a list of translator tags to search for and include641 in the results.642 :param options: a dictionary of additional options (optional)643 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.644 (comments will be empty currently)645 """646 extensions = set()647 for extension in options.get("extensions", "").split(","):648 extension = extension.strip()649 if not extension:650 continue651 extensions.add(import_string(extension))652 if InternationalizationExtension not in extensions:653 extensions.add(InternationalizationExtension)654655 def getbool(options, key, default=False):656 return options.get(key, str(default)).lower() in ("1", "on", "yes", "true")657658 silent = getbool(options, "silent", True)659 environment = Environment(660 options.get("block_start_string", BLOCK_START_STRING),661 options.get("block_end_string", BLOCK_END_STRING),662 options.get("variable_start_string", VARIABLE_START_STRING),663 options.get("variable_end_string", VARIABLE_END_STRING),664 options.get("comment_start_string", COMMENT_START_STRING),665 options.get("comment_end_string", COMMENT_END_STRING),666 options.get("line_statement_prefix") or LINE_STATEMENT_PREFIX,667 options.get("line_comment_prefix") or LINE_COMMENT_PREFIX,668 getbool(options, "trim_blocks", TRIM_BLOCKS),669 getbool(options, "lstrip_blocks", LSTRIP_BLOCKS),670 NEWLINE_SEQUENCE,671 getbool(options, "keep_trailing_newline", KEEP_TRAILING_NEWLINE),672 frozenset(extensions),673 cache_size=0,674 auto_reload=False,675 )676677 if getbool(options, "trimmed"):678 environment.policies["ext.i18n.trimmed"] = True679 if getbool(options, "newstyle_gettext"):680 environment.newstyle_gettext = True681682 source = fileobj.read().decode(options.get("encoding", "utf-8"))683 try:684 node = environment.parse(source)685 tokens = list(environment.lex(environment.preprocess(source)))686 except TemplateSyntaxError:687 if not silent:688 raise689 # skip templates with syntax errors690 return691692 finder = _CommentFinder(tokens, comment_tags)693 for lineno, func, message in extract_from_ast(node, keywords):694 yield lineno, func, message, finder.find_comments(lineno)695696697#: nicer import names698i18n = InternationalizationExtension699do = ExprStmtExtension700loopcontrols = LoopControlExtension701with_ = WithExtension702autoescape = AutoEscapeExtension703debug = DebugExtension
added:src/jinja/filters.py+1382 added
1# -*- coding: utf-8 -*-2"""Built-in template filters used with the ``|`` operator."""3import math4import random5import re6import warnings7from collections import namedtuple8from itertools import chain9from itertools import groupby1011from markupsafe import escape12from markupsafe import Markup13from markupsafe import soft_unicode1415from ._compat import abc16from ._compat import imap17from ._compat import iteritems18from ._compat import string_types19from ._compat import text_type20from .exceptions import FilterArgumentError21from .runtime import Undefined22from .utils import htmlsafe_json_dumps23from .utils import pformat24from .utils import unicode_urlencode25from .utils import urlize2627_word_re = re.compile(r"\w+", re.UNICODE)28_word_beginning_split_re = re.compile(r"([-\s\(\{\[\<]+)", re.UNICODE)293031def contextfilter(f):32 """Decorator for marking context dependent filters. The current33 :class:`Context` will be passed as first argument.34 """35 f.contextfilter = True36 return f373839def evalcontextfilter(f):40 """Decorator for marking eval-context dependent filters. An eval41 context object is passed as first argument. For more information42 about the eval context, see :ref:`eval-context`.4344 .. versionadded:: 2.445 """46 f.evalcontextfilter = True47 return f484950def environmentfilter(f):51 """Decorator for marking environment dependent filters. The current52 :class:`Environment` is passed to the filter as first argument.53 """54 f.environmentfilter = True55 return f565758def ignore_case(value):59 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings60 to lowercase and returns other types as-is."""61 return value.lower() if isinstance(value, string_types) else value626364def make_attrgetter(environment, attribute, postprocess=None, default=None):65 """Returns a callable that looks up the given attribute from a66 passed object with the rules of the environment. Dots are allowed67 to access attributes of attributes. Integer parts in paths are68 looked up as integers.69 """70 attribute = _prepare_attribute_parts(attribute)7172 def attrgetter(item):73 for part in attribute:74 item = environment.getitem(item, part)7576 if default and isinstance(item, Undefined):77 item = default7879 if postprocess is not None:80 item = postprocess(item)8182 return item8384 return attrgetter858687def make_multi_attrgetter(environment, attribute, postprocess=None):88 """Returns a callable that looks up the given comma separated89 attributes from a passed object with the rules of the environment.90 Dots are allowed to access attributes of each attribute. Integer91 parts in paths are looked up as integers.9293 The value returned by the returned callable is a list of extracted94 attribute values.9596 Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.97 """98 attribute_parts = (99 attribute.split(",") if isinstance(attribute, string_types) else [attribute]100 )101 attribute = [102 _prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts103 ]104105 def attrgetter(item):106 items = [None] * len(attribute)107 for i, attribute_part in enumerate(attribute):108 item_i = item109 for part in attribute_part:110 item_i = environment.getitem(item_i, part)111112 if postprocess is not None:113 item_i = postprocess(item_i)114115 items[i] = item_i116 return items117118 return attrgetter119120121def _prepare_attribute_parts(attr):122 if attr is None:123 return []124 elif isinstance(attr, string_types):125 return [int(x) if x.isdigit() else x for x in attr.split(".")]126 else:127 return [attr]128129130def do_forceescape(value):131 """Enforce HTML escaping. This will probably double escape variables."""132 if hasattr(value, "__html__"):133 value = value.__html__()134 return escape(text_type(value))135136137def do_urlencode(value):138 """Quote data for use in a URL path or query using UTF-8.139140 Basic wrapper around :func:`urllib.parse.quote` when given a141 string, or :func:`urllib.parse.urlencode` for a dict or iterable.142143 :param value: Data to quote. A string will be quoted directly. A144 dict or iterable of ``(key, value)`` pairs will be joined as a145 query string.146147 When given a string, "/" is not quoted. HTTP servers treat "/" and148 "%2F" equivalently in paths. If you need quoted slashes, use the149 ``|replace("/", "%2F")`` filter.150151 .. versionadded:: 2.7152 """153 if isinstance(value, string_types) or not isinstance(value, abc.Iterable):154 return unicode_urlencode(value)155156 if isinstance(value, dict):157 items = iteritems(value)158 else:159 items = iter(value)160161 return u"&".join(162 "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))163 for k, v in items164 )165166167@evalcontextfilter168def do_replace(eval_ctx, s, old, new, count=None):169 """Return a copy of the value with all occurrences of a substring170 replaced with a new one. The first argument is the substring171 that should be replaced, the second is the replacement string.172 If the optional third argument ``count`` is given, only the first173 ``count`` occurrences are replaced:174175 .. sourcecode:: jinja176177 {{ "Hello World"|replace("Hello", "Goodbye") }}178 -> Goodbye World179180 {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}181 -> d'oh, d'oh, aaargh182 """183 if count is None:184 count = -1185 if not eval_ctx.autoescape:186 return text_type(s).replace(text_type(old), text_type(new), count)187 if (188 hasattr(old, "__html__")189 or hasattr(new, "__html__")190 and not hasattr(s, "__html__")191 ):192 s = escape(s)193 else:194 s = soft_unicode(s)195 return s.replace(soft_unicode(old), soft_unicode(new), count)196197198def do_upper(s):199 """Convert a value to uppercase."""200 return soft_unicode(s).upper()201202203def do_lower(s):204 """Convert a value to lowercase."""205 return soft_unicode(s).lower()206207208@evalcontextfilter209def do_xmlattr(_eval_ctx, d, autospace=True):210 """Create an SGML/XML attribute string based on the items in a dict.211 All values that are neither `none` nor `undefined` are automatically212 escaped:213214 .. sourcecode:: html+jinja215216 <ul{{ {'class': 'my_list', 'missing': none,217 'id': 'list-%d'|format(variable)}|xmlattr }}>218 ...219 </ul>220221 Results in something like this:222223 .. sourcecode:: html224225 <ul class="my_list" id="list-42">226 ...227 </ul>228229 As you can see it automatically prepends a space in front of the item230 if the filter returned something unless the second parameter is false.231 """232 rv = u" ".join(233 u'%s="%s"' % (escape(key), escape(value))234 for key, value in iteritems(d)235 if value is not None and not isinstance(value, Undefined)236 )237 if autospace and rv:238 rv = u" " + rv239 if _eval_ctx.autoescape:240 rv = Markup(rv)241 return rv242243244def do_capitalize(s):245 """Capitalize a value. The first character will be uppercase, all others246 lowercase.247 """248 return soft_unicode(s).capitalize()249250251def do_title(s):252 """Return a titlecased version of the value. I.e. words will start with253 uppercase letters, all remaining characters are lowercase.254 """255 return "".join(256 [257 item[0].upper() + item[1:].lower()258 for item in _word_beginning_split_re.split(soft_unicode(s))259 if item260 ]261 )262263264def do_dictsort(value, case_sensitive=False, by="key", reverse=False):265 """Sort a dict and yield (key, value) pairs. Because python dicts are266 unsorted you may want to use this function to order them by either267 key or value:268269 .. sourcecode:: jinja270271 {% for item in mydict|dictsort %}272 sort the dict by key, case insensitive273274 {% for item in mydict|dictsort(reverse=true) %}275 sort the dict by key, case insensitive, reverse order276277 {% for item in mydict|dictsort(true) %}278 sort the dict by key, case sensitive279280 {% for item in mydict|dictsort(false, 'value') %}281 sort the dict by value, case insensitive282 """283 if by == "key":284 pos = 0285 elif by == "value":286 pos = 1287 else:288 raise FilterArgumentError('You can only sort by either "key" or "value"')289290 def sort_func(item):291 value = item[pos]292293 if not case_sensitive:294 value = ignore_case(value)295296 return value297298 return sorted(value.items(), key=sort_func, reverse=reverse)299300301@environmentfilter302def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):303 """Sort an iterable using Python's :func:`sorted`.304305 .. sourcecode:: jinja306307 {% for city in cities|sort %}308 ...309 {% endfor %}310311 :param reverse: Sort descending instead of ascending.312 :param case_sensitive: When sorting strings, sort upper and lower313 case separately.314 :param attribute: When sorting objects or dicts, an attribute or315 key to sort by. Can use dot notation like ``"address.city"``.316 Can be a list of attributes like ``"age,name"``.317318 The sort is stable, it does not change the relative order of319 elements that compare equal. This makes it is possible to chain320 sorts on different attributes and ordering.321322 .. sourcecode:: jinja323324 {% for user in users|sort(attribute="name")325 |sort(reverse=true, attribute="age") %}326 ...327 {% endfor %}328329 As a shortcut to chaining when the direction is the same for all330 attributes, pass a comma separate list of attributes.331332 .. sourcecode:: jinja333334 {% for user users|sort(attribute="age,name") %}335 ...336 {% endfor %}337338 .. versionchanged:: 2.11.0339 The ``attribute`` parameter can be a comma separated list of340 attributes, e.g. ``"age,name"``.341342 .. versionchanged:: 2.6343 The ``attribute`` parameter was added.344 """345 key_func = make_multi_attrgetter(346 environment, attribute, postprocess=ignore_case if not case_sensitive else None347 )348 return sorted(value, key=key_func, reverse=reverse)349350351@environmentfilter352def do_unique(environment, value, case_sensitive=False, attribute=None):353 """Returns a list of unique items from the given iterable.354355 .. sourcecode:: jinja356357 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}358 -> ['foo', 'bar', 'foobar']359360 The unique items are yielded in the same order as their first occurrence in361 the iterable passed to the filter.362363 :param case_sensitive: Treat upper and lower case strings as distinct.364 :param attribute: Filter objects with unique values for this attribute.365 """366 getter = make_attrgetter(367 environment, attribute, postprocess=ignore_case if not case_sensitive else None368 )369 seen = set()370371 for item in value:372 key = getter(item)373374 if key not in seen:375 seen.add(key)376 yield item377378379def _min_or_max(environment, value, func, case_sensitive, attribute):380 it = iter(value)381382 try:383 first = next(it)384 except StopIteration:385 return environment.undefined("No aggregated item, sequence was empty.")386387 key_func = make_attrgetter(388 environment, attribute, postprocess=ignore_case if not case_sensitive else None389 )390 return func(chain([first], it), key=key_func)391392393@environmentfilter394def do_min(environment, value, case_sensitive=False, attribute=None):395 """Return the smallest item from the sequence.396397 .. sourcecode:: jinja398399 {{ [1, 2, 3]|min }}400 -> 1401402 :param case_sensitive: Treat upper and lower case strings as distinct.403 :param attribute: Get the object with the min value of this attribute.404 """405 return _min_or_max(environment, value, min, case_sensitive, attribute)406407408@environmentfilter409def do_max(environment, value, case_sensitive=False, attribute=None):410 """Return the largest item from the sequence.411412 .. sourcecode:: jinja413414 {{ [1, 2, 3]|max }}415 -> 3416417 :param case_sensitive: Treat upper and lower case strings as distinct.418 :param attribute: Get the object with the max value of this attribute.419 """420 return _min_or_max(environment, value, max, case_sensitive, attribute)421422423def do_default(value, default_value=u"", boolean=False):424 """If the value is undefined it will return the passed default value,425 otherwise the value of the variable:426427 .. sourcecode:: jinja428429 {{ my_variable|default('my_variable is not defined') }}430431 This will output the value of ``my_variable`` if the variable was432 defined, otherwise ``'my_variable is not defined'``. If you want433 to use default with variables that evaluate to false you have to434 set the second parameter to `true`:435436 .. sourcecode:: jinja437438 {{ ''|default('the string was empty', true) }}439440 .. versionchanged:: 2.11441 It's now possible to configure the :class:`~jinja.Environment` with442 :class:`~jinja.ChainableUndefined` to make the `default` filter work443 on nested elements and attributes that may contain undefined values444 in the chain without getting an :exc:`~jinja.UndefinedError`.445 """446 if isinstance(value, Undefined) or (boolean and not value):447 return default_value448 return value449450451@evalcontextfilter452def do_join(eval_ctx, value, d=u"", attribute=None):453 """Return a string which is the concatenation of the strings in the454 sequence. The separator between elements is an empty string per455 default, you can define it with the optional parameter:456457 .. sourcecode:: jinja458459 {{ [1, 2, 3]|join('|') }}460 -> 1|2|3461462 {{ [1, 2, 3]|join }}463 -> 123464465 It is also possible to join certain attributes of an object:466467 .. sourcecode:: jinja468469 {{ users|join(', ', attribute='username') }}470471 .. versionadded:: 2.6472 The `attribute` parameter was added.473 """474 if attribute is not None:475 value = imap(make_attrgetter(eval_ctx.environment, attribute), value)476477 # no automatic escaping? joining is a lot easier then478 if not eval_ctx.autoescape:479 return text_type(d).join(imap(text_type, value))480481 # if the delimiter doesn't have an html representation we check482 # if any of the items has. If yes we do a coercion to Markup483 if not hasattr(d, "__html__"):484 value = list(value)485 do_escape = False486 for idx, item in enumerate(value):487 if hasattr(item, "__html__"):488 do_escape = True489 else:490 value[idx] = text_type(item)491 if do_escape:492 d = escape(d)493 else:494 d = text_type(d)495 return d.join(value)496497 # no html involved, to normal joining498 return soft_unicode(d).join(imap(soft_unicode, value))499500501def do_center(value, width=80):502 """Centers the value in a field of a given width."""503 return text_type(value).center(width)504505506@environmentfilter507def do_first(environment, seq):508 """Return the first item of a sequence."""509 try:510 return next(iter(seq))511 except StopIteration:512 return environment.undefined("No first item, sequence was empty.")513514515@environmentfilter516def do_last(environment, seq):517 """518 Return the last item of a sequence.519520 Note: Does not work with generators. You may want to explicitly521 convert it to a list:522523 .. sourcecode:: jinja524525 {{ data | selectattr('name', '==', 'Jinja') | list | last }}526 """527 try:528 return next(iter(reversed(seq)))529 except StopIteration:530 return environment.undefined("No last item, sequence was empty.")531532533@contextfilter534def do_random(context, seq):535 """Return a random item from the sequence."""536 try:537 return random.choice(seq)538 except IndexError:539 return context.environment.undefined("No random item, sequence was empty.")540541542def do_filesizeformat(value, binary=False):543 """Format the value like a 'human-readable' file size (i.e. 13 kB,544 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,545 Giga, etc.), if the second parameter is set to `True` the binary546 prefixes are used (Mebi, Gibi).547 """548 bytes = float(value)549 base = binary and 1024 or 1000550 prefixes = [551 (binary and "KiB" or "kB"),552 (binary and "MiB" or "MB"),553 (binary and "GiB" or "GB"),554 (binary and "TiB" or "TB"),555 (binary and "PiB" or "PB"),556 (binary and "EiB" or "EB"),557 (binary and "ZiB" or "ZB"),558 (binary and "YiB" or "YB"),559 ]560 if bytes == 1:561 return "1 Byte"562 elif bytes < base:563 return "%d Bytes" % bytes564 else:565 for i, prefix in enumerate(prefixes):566 unit = base ** (i + 2)567 if bytes < unit:568 return "%.1f %s" % ((base * bytes / unit), prefix)569 return "%.1f %s" % ((base * bytes / unit), prefix)570571572def do_pprint(value, verbose=False):573 """Pretty print a variable. Useful for debugging.574575 With Jinja 1.2 onwards you can pass it a parameter. If this parameter576 is truthy the output will be more verbose (this requires `pretty`)577 """578 return pformat(value, verbose=verbose)579580581@evalcontextfilter582def do_urlize(583 eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None584):585 """Converts URLs in plain text into clickable links.586587 If you pass the filter an additional integer it will shorten the urls588 to that number. Also a third argument exists that makes the urls589 "nofollow":590591 .. sourcecode:: jinja592593 {{ mytext|urlize(40, true) }}594 links are shortened to 40 chars and defined with rel="nofollow"595596 If *target* is specified, the ``target`` attribute will be added to the597 ``<a>`` tag:598599 .. sourcecode:: jinja600601 {{ mytext|urlize(40, target='_blank') }}602603 .. versionchanged:: 2.8+604 The *target* parameter was added.605 """606 policies = eval_ctx.environment.policies607 rel = set((rel or "").split() or [])608 if nofollow:609 rel.add("nofollow")610 rel.update((policies["urlize.rel"] or "").split())611 if target is None:612 target = policies["urlize.target"]613 rel = " ".join(sorted(rel)) or None614 rv = urlize(value, trim_url_limit, rel=rel, target=target)615 if eval_ctx.autoescape:616 rv = Markup(rv)617 return rv618619620def do_indent(s, width=4, first=False, blank=False, indentfirst=None):621 """Return a copy of the string with each line indented by 4 spaces. The622 first line and blank lines are not indented by default.623624 :param width: Number of spaces to indent by.625 :param first: Don't skip indenting the first line.626 :param blank: Don't skip indenting empty lines.627628 .. versionchanged:: 2.10629 Blank lines are not indented by default.630631 Rename the ``indentfirst`` argument to ``first``.632 """633 if indentfirst is not None:634 warnings.warn(635 "The 'indentfirst' argument is renamed to 'first' and will"636 " be removed in version 3.0.",637 DeprecationWarning,638 stacklevel=2,639 )640 first = indentfirst641642 indention = u" " * width643 newline = u"\n"644645 if isinstance(s, Markup):646 indention = Markup(indention)647 newline = Markup(newline)648649 s += newline # this quirk is necessary for splitlines method650651 if blank:652 rv = (newline + indention).join(s.splitlines())653 else:654 lines = s.splitlines()655 rv = lines.pop(0)656657 if lines:658 rv += newline + newline.join(659 indention + line if line else line for line in lines660 )661662 if first:663 rv = indention + rv664665 return rv666667668@environmentfilter669def do_truncate(env, s, length=255, killwords=False, end="...", leeway=None):670 """Return a truncated copy of the string. The length is specified671 with the first parameter which defaults to ``255``. If the second672 parameter is ``true`` the filter will cut the text at length. Otherwise673 it will discard the last word. If the text was in fact674 truncated it will append an ellipsis sign (``"..."``). If you want a675 different ellipsis sign than ``"..."`` you can specify it using the676 third parameter. Strings that only exceed the length by the tolerance677 margin given in the fourth parameter will not be truncated.678679 .. sourcecode:: jinja680681 {{ "foo bar baz qux"|truncate(9) }}682 -> "foo..."683 {{ "foo bar baz qux"|truncate(9, True) }}684 -> "foo ba..."685 {{ "foo bar baz qux"|truncate(11) }}686 -> "foo bar baz qux"687 {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}688 -> "foo bar..."689690 The default leeway on newer Jinja versions is 5 and was 0 before but691 can be reconfigured globally.692 """693 if leeway is None:694 leeway = env.policies["truncate.leeway"]695 assert length >= len(end), "expected length >= %s, got %s" % (len(end), length)696 assert leeway >= 0, "expected leeway >= 0, got %s" % leeway697 if len(s) <= length + leeway:698 return s699 if killwords:700 return s[: length - len(end)] + end701 result = s[: length - len(end)].rsplit(" ", 1)[0]702 return result + end703704705@environmentfilter706def do_wordwrap(707 environment,708 s,709 width=79,710 break_long_words=True,711 wrapstring=None,712 break_on_hyphens=True,713):714 """Wrap a string to the given width. Existing newlines are treated715 as paragraphs to be wrapped separately.716717 :param s: Original text to wrap.718 :param width: Maximum length of wrapped lines.719 :param break_long_words: If a word is longer than ``width``, break720 it across lines.721 :param break_on_hyphens: If a word contains hyphens, it may be split722 across lines.723 :param wrapstring: String to join each wrapped line. Defaults to724 :attr:`Environment.newline_sequence`.725726 .. versionchanged:: 2.11727 Existing newlines are treated as paragraphs wrapped separately.728729 .. versionchanged:: 2.11730 Added the ``break_on_hyphens`` parameter.731732 .. versionchanged:: 2.7733 Added the ``wrapstring`` parameter.734 """735736 import textwrap737738 if not wrapstring:739 wrapstring = environment.newline_sequence740741 # textwrap.wrap doesn't consider existing newlines when wrapping.742 # If the string has a newline before width, wrap will still insert743 # a newline at width, resulting in a short line. Instead, split and744 # wrap each paragraph individually.745 return wrapstring.join(746 [747 wrapstring.join(748 textwrap.wrap(749 line,750 width=width,751 expand_tabs=False,752 replace_whitespace=False,753 break_long_words=break_long_words,754 break_on_hyphens=break_on_hyphens,755 )756 )757 for line in s.splitlines()758 ]759 )760761762def do_wordcount(s):763 """Count the words in that string."""764 return len(_word_re.findall(s))765766767def do_int(value, default=0, base=10):768 """Convert the value into an integer. If the769 conversion doesn't work it will return ``0``. You can770 override this default using the first parameter. You771 can also override the default base (10) in the second772 parameter, which handles input with prefixes such as773 0b, 0o and 0x for bases 2, 8 and 16 respectively.774 The base is ignored for decimal numbers and non-string values.775 """776 try:777 if isinstance(value, string_types):778 return int(value, base)779 return int(value)780 except (TypeError, ValueError):781 # this quirk is necessary so that "42.23"|int gives 42.782 try:783 return int(float(value))784 except (TypeError, ValueError):785 return default786787788def do_float(value, default=0.0):789 """Convert the value into a floating point number. If the790 conversion doesn't work it will return ``0.0``. You can791 override this default using the first parameter.792 """793 try:794 return float(value)795 except (TypeError, ValueError):796 return default797798799def do_format(value, *args, **kwargs):800 """Apply the given values to a `printf-style`_ format string, like801 ``string % values``.802803 .. sourcecode:: jinja804805 {{ "%s, %s!"|format(greeting, name) }}806 Hello, World!807808 In most cases it should be more convenient and efficient to use the809 ``%`` operator or :meth:`str.format`.810811 .. code-block:: text812813 {{ "%s, %s!" % (greeting, name) }}814 {{ "{}, {}!".format(greeting, name) }}815816 .. _printf-style: https://docs.python.org/library/stdtypes.html817 #printf-style-string-formatting818 """819 if args and kwargs:820 raise FilterArgumentError(821 "can't handle positional and keyword arguments at the same time"822 )823 return soft_unicode(value) % (kwargs or args)824825826def do_trim(value, chars=None):827 """Strip leading and trailing characters, by default whitespace."""828 return soft_unicode(value).strip(chars)829830831def do_striptags(value):832 """Strip SGML/XML tags and replace adjacent whitespace by one space."""833 if hasattr(value, "__html__"):834 value = value.__html__()835 return Markup(text_type(value)).striptags()836837838def do_slice(value, slices, fill_with=None):839 """Slice an iterator and return a list of lists containing840 those items. Useful if you want to create a div containing841 three ul tags that represent columns:842843 .. sourcecode:: html+jinja844845 <div class="columnwrapper">846 {%- for column in items|slice(3) %}847 <ul class="column-{{ loop.index }}">848 {%- for item in column %}849 <li>{{ item }}</li>850 {%- endfor %}851 </ul>852 {%- endfor %}853 </div>854855 If you pass it a second argument it's used to fill missing856 values on the last iteration.857 """858 seq = list(value)859 length = len(seq)860 items_per_slice = length // slices861 slices_with_extra = length % slices862 offset = 0863 for slice_number in range(slices):864 start = offset + slice_number * items_per_slice865 if slice_number < slices_with_extra:866 offset += 1867 end = offset + (slice_number + 1) * items_per_slice868 tmp = seq[start:end]869 if fill_with is not None and slice_number >= slices_with_extra:870 tmp.append(fill_with)871 yield tmp872873874def do_batch(value, linecount, fill_with=None):875 """876 A filter that batches items. It works pretty much like `slice`877 just the other way round. It returns a list of lists with the878 given number of items. If you provide a second parameter this879 is used to fill up missing items. See this example:880881 .. sourcecode:: html+jinja882883 <table>884 {%- for row in items|batch(3, '&nbsp;') %}885 <tr>886 {%- for column in row %}887 <td>{{ column }}</td>888 {%- endfor %}889 </tr>890 {%- endfor %}891 </table>892 """893 tmp = []894 for item in value:895 if len(tmp) == linecount:896 yield tmp897 tmp = []898 tmp.append(item)899 if tmp:900 if fill_with is not None and len(tmp) < linecount:901 tmp += [fill_with] * (linecount - len(tmp))902 yield tmp903904905def do_round(value, precision=0, method="common"):906 """Round the number to a given precision. The first907 parameter specifies the precision (default is ``0``), the908 second the rounding method:909910 - ``'common'`` rounds either up or down911 - ``'ceil'`` always rounds up912 - ``'floor'`` always rounds down913914 If you don't specify a method ``'common'`` is used.915916 .. sourcecode:: jinja917918 {{ 42.55|round }}919 -> 43.0920 {{ 42.55|round(1, 'floor') }}921 -> 42.5922923 Note that even if rounded to 0 precision, a float is returned. If924 you need a real integer, pipe it through `int`:925926 .. sourcecode:: jinja927928 {{ 42.55|round|int }}929 -> 43930 """931 if method not in {"common", "ceil", "floor"}:932 raise FilterArgumentError("method must be common, ceil or floor")933 if method == "common":934 return round(value, precision)935 func = getattr(math, method)936 return func(value * (10 ** precision)) / (10 ** precision)937938939# Use a regular tuple repr here. This is what we did in the past and we940# really want to hide this custom type as much as possible. In particular941# we do not want to accidentally expose an auto generated repr in case942# people start to print this out in comments or something similar for943# debugging.944_GroupTuple = namedtuple("_GroupTuple", ["grouper", "list"])945_GroupTuple.__repr__ = tuple.__repr__946_GroupTuple.__str__ = tuple.__str__947948949@environmentfilter950def do_groupby(environment, value, attribute):951 """Group a sequence of objects by an attribute using Python's952 :func:`itertools.groupby`. The attribute can use dot notation for953 nested access, like ``"address.city"``. Unlike Python's ``groupby``,954 the values are sorted first so only one group is returned for each955 unique value.956957 For example, a list of ``User`` objects with a ``city`` attribute958 can be rendered in groups. In this example, ``grouper`` refers to959 the ``city`` value of the group.960961 .. sourcecode:: html+jinja962963 <ul>{% for city, items in users|groupby("city") %}964 <li>{{ city }}965 <ul>{% for user in items %}966 <li>{{ user.name }}967 {% endfor %}</ul>968 </li>969 {% endfor %}</ul>970971 ``groupby`` yields namedtuples of ``(grouper, list)``, which972 can be used instead of the tuple unpacking above. ``grouper`` is the973 value of the attribute, and ``list`` is the items with that value.974975 .. sourcecode:: html+jinja976977 <ul>{% for group in users|groupby("city") %}978 <li>{{ group.grouper }}: {{ group.list|join(", ") }}979 {% endfor %}</ul>980981 .. versionchanged:: 2.6982 The attribute supports dot notation for nested access.983 """984 expr = make_attrgetter(environment, attribute)985 return [986 _GroupTuple(key, list(values))987 for key, values in groupby(sorted(value, key=expr), expr)988 ]989990991@environmentfilter992def do_sum(environment, iterable, attribute=None, start=0):993 """Returns the sum of a sequence of numbers plus the value of parameter994 'start' (which defaults to 0). When the sequence is empty it returns995 start.996997 It is also possible to sum up only certain attributes:998999 .. sourcecode:: jinja10001001 Total: {{ items|sum(attribute='price') }}10021003 .. versionchanged:: 2.61004 The `attribute` parameter was added to allow suming up over1005 attributes. Also the `start` parameter was moved on to the right.1006 """1007 if attribute is not None:1008 iterable = imap(make_attrgetter(environment, attribute), iterable)1009 return sum(iterable, start)101010111012def do_list(value):1013 """Convert the value into a list. If it was a string the returned list1014 will be a list of characters.1015 """1016 return list(value)101710181019def do_mark_safe(value):1020 """Mark the value as safe which means that in an environment with automatic1021 escaping enabled this variable will not be escaped.1022 """1023 return Markup(value)102410251026def do_mark_unsafe(value):1027 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1028 return text_type(value)102910301031def do_reverse(value):1032 """Reverse the object or return an iterator that iterates over it the other1033 way round.1034 """1035 if isinstance(value, string_types):1036 return value[::-1]1037 try:1038 return reversed(value)1039 except TypeError:1040 try:1041 rv = list(value)1042 rv.reverse()1043 return rv1044 except TypeError:1045 raise FilterArgumentError("argument must be iterable")104610471048@environmentfilter1049def do_attr(environment, obj, name):1050 """Get an attribute of an object. ``foo|attr("bar")`` works like1051 ``foo.bar`` just that always an attribute is returned and items are not1052 looked up.10531054 See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.1055 """1056 try:1057 name = str(name)1058 except UnicodeError:1059 pass1060 else:1061 try:1062 value = getattr(obj, name)1063 except AttributeError:1064 pass1065 else:1066 if environment.sandboxed and not environment.is_safe_attribute(1067 obj, name, value1068 ):1069 return environment.unsafe_undefined(obj, name)1070 return value1071 return environment.undefined(obj=obj, name=name)107210731074@contextfilter1075def do_map(*args, **kwargs):1076 """Applies a filter on a sequence of objects or looks up an attribute.1077 This is useful when dealing with lists of objects but you are really1078 only interested in a certain value of it.10791080 The basic usage is mapping on an attribute. Imagine you have a list1081 of users but you are only interested in a list of usernames:10821083 .. sourcecode:: jinja10841085 Users on this page: {{ users|map(attribute='username')|join(', ') }}10861087 You can specify a ``default`` value to use if an object in the list1088 does not have the given attribute.10891090 .. sourcecode:: jinja10911092 {{ users|map(attribute="username", default="Anonymous")|join(", ") }}10931094 Alternatively you can let it invoke a filter by passing the name of the1095 filter and the arguments afterwards. A good example would be applying a1096 text conversion filter on a sequence:10971098 .. sourcecode:: jinja10991100 Users on this page: {{ titles|map('lower')|join(', ') }}11011102 Similar to a generator comprehension such as:11031104 .. code-block:: python11051106 (u.username for u in users)1107 (u.username or "Anonymous" for u in users)1108 (do_lower(x) for x in titles)11091110 .. versionchanged:: 2.11.01111 Added the ``default`` parameter.11121113 .. versionadded:: 2.71114 """1115 seq, func = prepare_map(args, kwargs)1116 if seq:1117 for item in seq:1118 yield func(item)111911201121@contextfilter1122def do_select(*args, **kwargs):1123 """Filters a sequence of objects by applying a test to each object,1124 and only selecting the objects with the test succeeding.11251126 If no test is specified, each object will be evaluated as a boolean.11271128 Example usage:11291130 .. sourcecode:: jinja11311132 {{ numbers|select("odd") }}1133 {{ numbers|select("odd") }}1134 {{ numbers|select("divisibleby", 3) }}1135 {{ numbers|select("lessthan", 42) }}1136 {{ strings|select("equalto", "mystring") }}11371138 Similar to a generator comprehension such as:11391140 .. code-block:: python11411142 (n for n in numbers if test_odd(n))1143 (n for n in numbers if test_divisibleby(n, 3))11441145 .. versionadded:: 2.71146 """1147 return select_or_reject(args, kwargs, lambda x: x, False)114811491150@contextfilter1151def do_reject(*args, **kwargs):1152 """Filters a sequence of objects by applying a test to each object,1153 and rejecting the objects with the test succeeding.11541155 If no test is specified, each object will be evaluated as a boolean.11561157 Example usage:11581159 .. sourcecode:: jinja11601161 {{ numbers|reject("odd") }}11621163 Similar to a generator comprehension such as:11641165 .. code-block:: python11661167 (n for n in numbers if not test_odd(n))11681169 .. versionadded:: 2.71170 """1171 return select_or_reject(args, kwargs, lambda x: not x, False)117211731174@contextfilter1175def do_selectattr(*args, **kwargs):1176 """Filters a sequence of objects by applying a test to the specified1177 attribute of each object, and only selecting the objects with the1178 test succeeding.11791180 If no test is specified, the attribute's value will be evaluated as1181 a boolean.11821183 Example usage:11841185 .. sourcecode:: jinja11861187 {{ users|selectattr("is_active") }}1188 {{ users|selectattr("email", "none") }}11891190 Similar to a generator comprehension such as:11911192 .. code-block:: python11931194 (u for user in users if user.is_active)1195 (u for user in users if test_none(user.email))11961197 .. versionadded:: 2.71198 """1199 return select_or_reject(args, kwargs, lambda x: x, True)120012011202@contextfilter1203def do_rejectattr(*args, **kwargs):1204 """Filters a sequence of objects by applying a test to the specified1205 attribute of each object, and rejecting the objects with the test1206 succeeding.12071208 If no test is specified, the attribute's value will be evaluated as1209 a boolean.12101211 .. sourcecode:: jinja12121213 {{ users|rejectattr("is_active") }}1214 {{ users|rejectattr("email", "none") }}12151216 Similar to a generator comprehension such as:12171218 .. code-block:: python12191220 (u for user in users if not user.is_active)1221 (u for user in users if not test_none(user.email))12221223 .. versionadded:: 2.71224 """1225 return select_or_reject(args, kwargs, lambda x: not x, True)122612271228@evalcontextfilter1229def do_tojson(eval_ctx, value, indent=None):1230 """Dumps a structure to JSON so that it's safe to use in ``<script>``1231 tags. It accepts the same arguments and returns a JSON string. Note that1232 this is available in templates through the ``|tojson`` filter which will1233 also mark the result as safe. Due to how this function escapes certain1234 characters this is safe even if used outside of ``<script>`` tags.12351236 The following characters are escaped in strings:12371238 - ``<``1239 - ``>``1240 - ``&``1241 - ``'``12421243 This makes it safe to embed such strings in any place in HTML with the1244 notable exception of double quoted attributes. In that case single1245 quote your attributes or HTML escape it in addition.12461247 The indent parameter can be used to enable pretty printing. Set it to1248 the number of spaces that the structures should be indented with.12491250 Note that this filter is for use in HTML contexts only.12511252 .. versionadded:: 2.91253 """1254 policies = eval_ctx.environment.policies1255 dumper = policies["json.dumps_function"]1256 options = policies["json.dumps_kwargs"]1257 if indent is not None:1258 options = dict(options)1259 options["indent"] = indent1260 return htmlsafe_json_dumps(value, dumper=dumper, **options)126112621263def prepare_map(args, kwargs):1264 context = args[0]1265 seq = args[1]1266 default = None12671268 if len(args) == 2 and "attribute" in kwargs:1269 attribute = kwargs.pop("attribute")1270 default = kwargs.pop("default", None)1271 if kwargs:1272 raise FilterArgumentError(1273 "Unexpected keyword argument %r" % next(iter(kwargs))1274 )1275 func = make_attrgetter(context.environment, attribute, default=default)1276 else:1277 try:1278 name = args[2]1279 args = args[3:]1280 except LookupError:1281 raise FilterArgumentError("map requires a filter argument")12821283 def func(item):1284 return context.environment.call_filter(1285 name, item, args, kwargs, context=context1286 )12871288 return seq, func128912901291def prepare_select_or_reject(args, kwargs, modfunc, lookup_attr):1292 context = args[0]1293 seq = args[1]1294 if lookup_attr:1295 try:1296 attr = args[2]1297 except LookupError:1298 raise FilterArgumentError("Missing parameter for attribute name")1299 transfunc = make_attrgetter(context.environment, attr)1300 off = 11301 else:1302 off = 013031304 def transfunc(x):1305 return x13061307 try:1308 name = args[2 + off]1309 args = args[3 + off :]13101311 def func(item):1312 return context.environment.call_test(name, item, args, kwargs)13131314 except LookupError:1315 func = bool13161317 return seq, lambda item: modfunc(func(transfunc(item)))131813191320def select_or_reject(args, kwargs, modfunc, lookup_attr):1321 seq, func = prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)1322 if seq:1323 for item in seq:1324 if func(item):1325 yield item132613271328FILTERS = {1329 "abs": abs,1330 "attr": do_attr,1331 "batch": do_batch,1332 "capitalize": do_capitalize,1333 "center": do_center,1334 "count": len,1335 "d": do_default,1336 "default": do_default,1337 "dictsort": do_dictsort,1338 "e": escape,1339 "escape": escape,1340 "filesizeformat": do_filesizeformat,1341 "first": do_first,1342 "float": do_float,1343 "forceescape": do_forceescape,1344 "format": do_format,1345 "groupby": do_groupby,1346 "indent": do_indent,1347 "int": do_int,1348 "join": do_join,1349 "last": do_last,1350 "length": len,1351 "list": do_list,1352 "lower": do_lower,1353 "map": do_map,1354 "min": do_min,1355 "max": do_max,1356 "pprint": do_pprint,1357 "random": do_random,1358 "reject": do_reject,1359 "rejectattr": do_rejectattr,1360 "replace": do_replace,1361 "reverse": do_reverse,1362 "round": do_round,1363 "safe": do_mark_safe,1364 "select": do_select,1365 "selectattr": do_selectattr,1366 "slice": do_slice,1367 "sort": do_sort,1368 "string": soft_unicode,1369 "striptags": do_striptags,1370 "sum": do_sum,1371 "title": do_title,1372 "trim": do_trim,1373 "truncate": do_truncate,1374 "unique": do_unique,1375 "upper": do_upper,1376 "urlencode": do_urlencode,1377 "urlize": do_urlize,1378 "wordcount": do_wordcount,1379 "wordwrap": do_wordwrap,1380 "xmlattr": do_xmlattr,1381 "tojson": do_tojson,1382}
added:src/jinja/idtracking.py+290 added
1from ._compat import iteritems2from .visitor import NodeVisitor34VAR_LOAD_PARAMETER = "param"5VAR_LOAD_RESOLVE = "resolve"6VAR_LOAD_ALIAS = "alias"7VAR_LOAD_UNDEFINED = "undefined"8910def find_symbols(nodes, parent_symbols=None):11 sym = Symbols(parent=parent_symbols)12 visitor = FrameSymbolVisitor(sym)13 for node in nodes:14 visitor.visit(node)15 return sym161718def symbols_for_node(node, parent_symbols=None):19 sym = Symbols(parent=parent_symbols)20 sym.analyze_node(node)21 return sym222324class Symbols(object):25 def __init__(self, parent=None, level=None):26 if level is None:27 if parent is None:28 level = 029 else:30 level = parent.level + 131 self.level = level32 self.parent = parent33 self.refs = {}34 self.loads = {}35 self.stores = set()3637 def analyze_node(self, node, **kwargs):38 visitor = RootVisitor(self)39 visitor.visit(node, **kwargs)4041 def _define_ref(self, name, load=None):42 ident = "l_%d_%s" % (self.level, name)43 self.refs[name] = ident44 if load is not None:45 self.loads[ident] = load46 return ident4748 def find_load(self, target):49 if target in self.loads:50 return self.loads[target]51 if self.parent is not None:52 return self.parent.find_load(target)5354 def find_ref(self, name):55 if name in self.refs:56 return self.refs[name]57 if self.parent is not None:58 return self.parent.find_ref(name)5960 def ref(self, name):61 rv = self.find_ref(name)62 if rv is None:63 raise AssertionError(64 "Tried to resolve a name to a reference that "65 "was unknown to the frame (%r)" % name66 )67 return rv6869 def copy(self):70 rv = object.__new__(self.__class__)71 rv.__dict__.update(self.__dict__)72 rv.refs = self.refs.copy()73 rv.loads = self.loads.copy()74 rv.stores = self.stores.copy()75 return rv7677 def store(self, name):78 self.stores.add(name)7980 # If we have not see the name referenced yet, we need to figure81 # out what to set it to.82 if name not in self.refs:83 # If there is a parent scope we check if the name has a84 # reference there. If it does it means we might have to alias85 # to a variable there.86 if self.parent is not None:87 outer_ref = self.parent.find_ref(name)88 if outer_ref is not None:89 self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref))90 return9192 # Otherwise we can just set it to undefined.93 self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))9495 def declare_parameter(self, name):96 self.stores.add(name)97 return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))9899 def load(self, name):100 target = self.find_ref(name)101 if target is None:102 self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))103104 def branch_update(self, branch_symbols):105 stores = {}106 for branch in branch_symbols:107 for target in branch.stores:108 if target in self.stores:109 continue110 stores[target] = stores.get(target, 0) + 1111112 for sym in branch_symbols:113 self.refs.update(sym.refs)114 self.loads.update(sym.loads)115 self.stores.update(sym.stores)116117 for name, branch_count in iteritems(stores):118 if branch_count == len(branch_symbols):119 continue120 target = self.find_ref(name)121 assert target is not None, "should not happen"122123 if self.parent is not None:124 outer_target = self.parent.find_ref(name)125 if outer_target is not None:126 self.loads[target] = (VAR_LOAD_ALIAS, outer_target)127 continue128 self.loads[target] = (VAR_LOAD_RESOLVE, name)129130 def dump_stores(self):131 rv = {}132 node = self133 while node is not None:134 for name in node.stores:135 if name not in rv:136 rv[name] = self.find_ref(name)137 node = node.parent138 return rv139140 def dump_param_targets(self):141 rv = set()142 node = self143 while node is not None:144 for target, (instr, _) in iteritems(self.loads):145 if instr == VAR_LOAD_PARAMETER:146 rv.add(target)147 node = node.parent148 return rv149150151class RootVisitor(NodeVisitor):152 def __init__(self, symbols):153 self.sym_visitor = FrameSymbolVisitor(symbols)154155 def _simple_visit(self, node, **kwargs):156 for child in node.iter_child_nodes():157 self.sym_visitor.visit(child)158159 visit_Template = (160 visit_Block161 ) = (162 visit_Macro163 ) = (164 visit_FilterBlock165 ) = visit_Scope = visit_If = visit_ScopedEvalContextModifier = _simple_visit166167 def visit_AssignBlock(self, node, **kwargs):168 for child in node.body:169 self.sym_visitor.visit(child)170171 def visit_CallBlock(self, node, **kwargs):172 for child in node.iter_child_nodes(exclude=("call",)):173 self.sym_visitor.visit(child)174175 def visit_OverlayScope(self, node, **kwargs):176 for child in node.body:177 self.sym_visitor.visit(child)178179 def visit_For(self, node, for_branch="body", **kwargs):180 if for_branch == "body":181 self.sym_visitor.visit(node.target, store_as_param=True)182 branch = node.body183 elif for_branch == "else":184 branch = node.else_185 elif for_branch == "test":186 self.sym_visitor.visit(node.target, store_as_param=True)187 if node.test is not None:188 self.sym_visitor.visit(node.test)189 return190 else:191 raise RuntimeError("Unknown for branch")192 for item in branch or ():193 self.sym_visitor.visit(item)194195 def visit_With(self, node, **kwargs):196 for target in node.targets:197 self.sym_visitor.visit(target)198 for child in node.body:199 self.sym_visitor.visit(child)200201 def generic_visit(self, node, *args, **kwargs):202 raise NotImplementedError(203 "Cannot find symbols for %r" % node.__class__.__name__204 )205206207class FrameSymbolVisitor(NodeVisitor):208 """A visitor for `Frame.inspect`."""209210 def __init__(self, symbols):211 self.symbols = symbols212213 def visit_Name(self, node, store_as_param=False, **kwargs):214 """All assignments to names go through this function."""215 if store_as_param or node.ctx == "param":216 self.symbols.declare_parameter(node.name)217 elif node.ctx == "store":218 self.symbols.store(node.name)219 elif node.ctx == "load":220 self.symbols.load(node.name)221222 def visit_NSRef(self, node, **kwargs):223 self.symbols.load(node.name)224225 def visit_If(self, node, **kwargs):226 self.visit(node.test, **kwargs)227228 original_symbols = self.symbols229230 def inner_visit(nodes):231 self.symbols = rv = original_symbols.copy()232 for subnode in nodes:233 self.visit(subnode, **kwargs)234 self.symbols = original_symbols235 return rv236237 body_symbols = inner_visit(node.body)238 elif_symbols = inner_visit(node.elif_)239 else_symbols = inner_visit(node.else_ or ())240241 self.symbols.branch_update([body_symbols, elif_symbols, else_symbols])242243 def visit_Macro(self, node, **kwargs):244 self.symbols.store(node.name)245246 def visit_Import(self, node, **kwargs):247 self.generic_visit(node, **kwargs)248 self.symbols.store(node.target)249250 def visit_FromImport(self, node, **kwargs):251 self.generic_visit(node, **kwargs)252 for name in node.names:253 if isinstance(name, tuple):254 self.symbols.store(name[1])255 else:256 self.symbols.store(name)257258 def visit_Assign(self, node, **kwargs):259 """Visit assignments in the correct order."""260 self.visit(node.node, **kwargs)261 self.visit(node.target, **kwargs)262263 def visit_For(self, node, **kwargs):264 """Visiting stops at for blocks. However the block sequence265 is visited as part of the outer scope.266 """267 self.visit(node.iter, **kwargs)268269 def visit_CallBlock(self, node, **kwargs):270 self.visit(node.call, **kwargs)271272 def visit_FilterBlock(self, node, **kwargs):273 self.visit(node.filter, **kwargs)274275 def visit_With(self, node, **kwargs):276 for target in node.values:277 self.visit(target)278279 def visit_AssignBlock(self, node, **kwargs):280 """Stop visiting at block assigns."""281 self.visit(node.target, **kwargs)282283 def visit_Scope(self, node, **kwargs):284 """Stop visiting at scopes."""285286 def visit_Block(self, node, **kwargs):287 """Stop visiting at blocks."""288289 def visit_OverlayScope(self, node, **kwargs):290 """Do not visit into overlay scopes."""
added:src/jinja/lexer.py+841 added
1# -*- coding: utf-8 -*-2"""Implements a Jinja / Python combination lexer. The ``Lexer`` class3is used to do some preprocessing. It filters out invalid operators like4the bitshift operators we don't allow in templates. It separates5template code and python code in expressions.6"""7import re8from ast import literal_eval9from collections import deque10from operator import itemgetter1112from ._compat import implements_iterator13from ._compat import intern14from ._compat import iteritems15from ._compat import text_type16from .exceptions import TemplateSyntaxError17from .utils import LRUCache1819# cache for the lexers. Exists in order to be able to have multiple20# environments with the same lexer21_lexer_cache = LRUCache(50)2223# static regular expressions24whitespace_re = re.compile(r"\s+", re.U)25newline_re = re.compile(r"(\r\n|\r|\n)")26string_re = re.compile(27 r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S28)29integer_re = re.compile(r"(\d+_)*\d+")30float_re = re.compile(31 r"""32 (?<!\.) # doesn't start with a .33 (\d+_)*\d+ # digits, possibly _ separated34 (35 (\.(\d+_)*\d+)? # optional fractional part36 e[+\-]?(\d+_)*\d+ # exponent part37 |38 \.(\d+_)*\d+ # required fractional part39 )40 """,41 re.IGNORECASE | re.VERBOSE,42)4344try:45 # check if this Python supports Unicode identifiers46 compile("föö", "<unknown>", "eval")47except SyntaxError:48 # Python 2, no Unicode support, use ASCII identifiers49 name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*")50 check_ident = False51else:52 # Unicode support, import generated re pattern and set flag to use53 # str.isidentifier to validate during lexing.54 from ._identifier import pattern as name_re5556 check_ident = True5758# internal the tokens and keep references to them59TOKEN_ADD = intern("add")60TOKEN_ASSIGN = intern("assign")61TOKEN_COLON = intern("colon")62TOKEN_COMMA = intern("comma")63TOKEN_DIV = intern("div")64TOKEN_DOT = intern("dot")65TOKEN_EQ = intern("eq")66TOKEN_FLOORDIV = intern("floordiv")67TOKEN_GT = intern("gt")68TOKEN_GTEQ = intern("gteq")69TOKEN_LBRACE = intern("lbrace")70TOKEN_LBRACKET = intern("lbracket")71TOKEN_LPAREN = intern("lparen")72TOKEN_LT = intern("lt")73TOKEN_LTEQ = intern("lteq")74TOKEN_MOD = intern("mod")75TOKEN_MUL = intern("mul")76TOKEN_NE = intern("ne")77TOKEN_PIPE = intern("pipe")78TOKEN_POW = intern("pow")79TOKEN_RBRACE = intern("rbrace")80TOKEN_RBRACKET = intern("rbracket")81TOKEN_RPAREN = intern("rparen")82TOKEN_SEMICOLON = intern("semicolon")83TOKEN_SUB = intern("sub")84TOKEN_TILDE = intern("tilde")85TOKEN_WHITESPACE = intern("whitespace")86TOKEN_FLOAT = intern("float")87TOKEN_INTEGER = intern("integer")88TOKEN_NAME = intern("name")89TOKEN_STRING = intern("string")90TOKEN_OPERATOR = intern("operator")91TOKEN_BLOCK_BEGIN = intern("block_begin")92TOKEN_BLOCK_END = intern("block_end")93TOKEN_VARIABLE_BEGIN = intern("variable_begin")94TOKEN_VARIABLE_END = intern("variable_end")95TOKEN_RAW_BEGIN = intern("raw_begin")96TOKEN_RAW_END = intern("raw_end")97TOKEN_COMMENT_BEGIN = intern("comment_begin")98TOKEN_COMMENT_END = intern("comment_end")99TOKEN_COMMENT = intern("comment")100TOKEN_LINESTATEMENT_BEGIN = intern("linestatement_begin")101TOKEN_LINESTATEMENT_END = intern("linestatement_end")102TOKEN_LINECOMMENT_BEGIN = intern("linecomment_begin")103TOKEN_LINECOMMENT_END = intern("linecomment_end")104TOKEN_LINECOMMENT = intern("linecomment")105TOKEN_DATA = intern("data")106TOKEN_INITIAL = intern("initial")107TOKEN_EOF = intern("eof")108109# bind operators to token types110operators = {111 "+": TOKEN_ADD,112 "-": TOKEN_SUB,113 "/": TOKEN_DIV,114 "//": TOKEN_FLOORDIV,115 "*": TOKEN_MUL,116 "%": TOKEN_MOD,117 "**": TOKEN_POW,118 "~": TOKEN_TILDE,119 "[": TOKEN_LBRACKET,120 "]": TOKEN_RBRACKET,121 "(": TOKEN_LPAREN,122 ")": TOKEN_RPAREN,123 "{": TOKEN_LBRACE,124 "}": TOKEN_RBRACE,125 "==": TOKEN_EQ,126 "!=": TOKEN_NE,127 ">": TOKEN_GT,128 ">=": TOKEN_GTEQ,129 "<": TOKEN_LT,130 "<=": TOKEN_LTEQ,131 "=": TOKEN_ASSIGN,132 ".": TOKEN_DOT,133 ":": TOKEN_COLON,134 "|": TOKEN_PIPE,135 ",": TOKEN_COMMA,136 ";": TOKEN_SEMICOLON,137}138139reverse_operators = dict([(v, k) for k, v in iteritems(operators)])140assert len(operators) == len(reverse_operators), "operators dropped"141operator_re = re.compile(142 "(%s)" % "|".join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))143)144145ignored_tokens = frozenset(146 [147 TOKEN_COMMENT_BEGIN,148 TOKEN_COMMENT,149 TOKEN_COMMENT_END,150 TOKEN_WHITESPACE,151 TOKEN_LINECOMMENT_BEGIN,152 TOKEN_LINECOMMENT_END,153 TOKEN_LINECOMMENT,154 ]155)156ignore_if_empty = frozenset(157 [TOKEN_WHITESPACE, TOKEN_DATA, TOKEN_COMMENT, TOKEN_LINECOMMENT]158)159160161def _describe_token_type(token_type):162 if token_type in reverse_operators:163 return reverse_operators[token_type]164 return {165 TOKEN_COMMENT_BEGIN: "begin of comment",166 TOKEN_COMMENT_END: "end of comment",167 TOKEN_COMMENT: "comment",168 TOKEN_LINECOMMENT: "comment",169 TOKEN_BLOCK_BEGIN: "begin of statement block",170 TOKEN_BLOCK_END: "end of statement block",171 TOKEN_VARIABLE_BEGIN: "begin of print statement",172 TOKEN_VARIABLE_END: "end of print statement",173 TOKEN_LINESTATEMENT_BEGIN: "begin of line statement",174 TOKEN_LINESTATEMENT_END: "end of line statement",175 TOKEN_DATA: "template data / text",176 TOKEN_EOF: "end of template",177 }.get(token_type, token_type)178179180def describe_token(token):181 """Returns a description of the token."""182 if token.type == TOKEN_NAME:183 return token.value184 return _describe_token_type(token.type)185186187def describe_token_expr(expr):188 """Like `describe_token` but for token expressions."""189 if ":" in expr:190 type, value = expr.split(":", 1)191 if type == TOKEN_NAME:192 return value193 else:194 type = expr195 return _describe_token_type(type)196197198def count_newlines(value):199 """Count the number of newline characters in the string. This is200 useful for extensions that filter a stream.201 """202 return len(newline_re.findall(value))203204205def compile_rules(environment):206 """Compiles all the rules from the environment into a list of rules."""207 e = re.escape208 rules = [209 (210 len(environment.comment_start_string),211 TOKEN_COMMENT_BEGIN,212 e(environment.comment_start_string),213 ),214 (215 len(environment.block_start_string),216 TOKEN_BLOCK_BEGIN,217 e(environment.block_start_string),218 ),219 (220 len(environment.variable_start_string),221 TOKEN_VARIABLE_BEGIN,222 e(environment.variable_start_string),223 ),224 ]225226 if environment.line_statement_prefix is not None:227 rules.append(228 (229 len(environment.line_statement_prefix),230 TOKEN_LINESTATEMENT_BEGIN,231 r"^[ \t\v]*" + e(environment.line_statement_prefix),232 )233 )234 if environment.line_comment_prefix is not None:235 rules.append(236 (237 len(environment.line_comment_prefix),238 TOKEN_LINECOMMENT_BEGIN,239 r"(?:^|(?<=\S))[^\S\r\n]*" + e(environment.line_comment_prefix),240 )241 )242243 return [x[1:] for x in sorted(rules, reverse=True)]244245246class Failure(object):247 """Class that raises a `TemplateSyntaxError` if called.248 Used by the `Lexer` to specify known errors.249 """250251 def __init__(self, message, cls=TemplateSyntaxError):252 self.message = message253 self.error_class = cls254255 def __call__(self, lineno, filename):256 raise self.error_class(self.message, lineno, filename)257258259class Token(tuple):260 """Token class."""261262 __slots__ = ()263 lineno, type, value = (property(itemgetter(x)) for x in range(3))264265 def __new__(cls, lineno, type, value):266 return tuple.__new__(cls, (lineno, intern(str(type)), value))267268 def __str__(self):269 if self.type in reverse_operators:270 return reverse_operators[self.type]271 elif self.type == "name":272 return self.value273 return self.type274275 def test(self, expr):276 """Test a token against a token expression. This can either be a277 token type or ``'token_type:token_value'``. This can only test278 against string values and types.279 """280 # here we do a regular string equality check as test_any is usually281 # passed an iterable of not interned strings.282 if self.type == expr:283 return True284 elif ":" in expr:285 return expr.split(":", 1) == [self.type, self.value]286 return False287288 def test_any(self, *iterable):289 """Test against multiple token expressions."""290 for expr in iterable:291 if self.test(expr):292 return True293 return False294295 def __repr__(self):296 return "Token(%r, %r, %r)" % (self.lineno, self.type, self.value)297298299@implements_iterator300class TokenStreamIterator(object):301 """The iterator for tokenstreams. Iterate over the stream302 until the eof token is reached.303 """304305 def __init__(self, stream):306 self.stream = stream307308 def __iter__(self):309 return self310311 def __next__(self):312 token = self.stream.current313 if token.type is TOKEN_EOF:314 self.stream.close()315 raise StopIteration()316 next(self.stream)317 return token318319320@implements_iterator321class TokenStream(object):322 """A token stream is an iterable that yields :class:`Token`\\s. The323 parser however does not iterate over it but calls :meth:`next` to go324 one token ahead. The current active token is stored as :attr:`current`.325 """326327 def __init__(self, generator, name, filename):328 self._iter = iter(generator)329 self._pushed = deque()330 self.name = name331 self.filename = filename332 self.closed = False333 self.current = Token(1, TOKEN_INITIAL, "")334 next(self)335336 def __iter__(self):337 return TokenStreamIterator(self)338339 def __bool__(self):340 return bool(self._pushed) or self.current.type is not TOKEN_EOF341342 __nonzero__ = __bool__ # py2343344 @property345 def eos(self):346 """Are we at the end of the stream?"""347 return not self348349 def push(self, token):350 """Push a token back to the stream."""351 self._pushed.append(token)352353 def look(self):354 """Look at the next token."""355 old_token = next(self)356 result = self.current357 self.push(result)358 self.current = old_token359 return result360361 def skip(self, n=1):362 """Got n tokens ahead."""363 for _ in range(n):364 next(self)365366 def next_if(self, expr):367 """Perform the token test and return the token if it matched.368 Otherwise the return value is `None`.369 """370 if self.current.test(expr):371 return next(self)372373 def skip_if(self, expr):374 """Like :meth:`next_if` but only returns `True` or `False`."""375 return self.next_if(expr) is not None376377 def __next__(self):378 """Go one token ahead and return the old one.379380 Use the built-in :func:`next` instead of calling this directly.381 """382 rv = self.current383 if self._pushed:384 self.current = self._pushed.popleft()385 elif self.current.type is not TOKEN_EOF:386 try:387 self.current = next(self._iter)388 except StopIteration:389 self.close()390 return rv391392 def close(self):393 """Close the stream."""394 self.current = Token(self.current.lineno, TOKEN_EOF, "")395 self._iter = None396 self.closed = True397398 def expect(self, expr):399 """Expect a given token type and return it. This accepts the same400 argument as :meth:`jinja.lexer.Token.test`.401 """402 if not self.current.test(expr):403 expr = describe_token_expr(expr)404 if self.current.type is TOKEN_EOF:405 raise TemplateSyntaxError(406 "unexpected end of template, expected %r." % expr,407 self.current.lineno,408 self.name,409 self.filename,410 )411 raise TemplateSyntaxError(412 "expected token %r, got %r" % (expr, describe_token(self.current)),413 self.current.lineno,414 self.name,415 self.filename,416 )417 try:418 return self.current419 finally:420 next(self)421422423def get_lexer(environment):424 """Return a lexer which is probably cached."""425 key = (426 environment.block_start_string,427 environment.block_end_string,428 environment.variable_start_string,429 environment.variable_end_string,430 environment.comment_start_string,431 environment.comment_end_string,432 environment.line_statement_prefix,433 environment.line_comment_prefix,434 environment.trim_blocks,435 environment.lstrip_blocks,436 environment.newline_sequence,437 environment.keep_trailing_newline,438 )439 lexer = _lexer_cache.get(key)440 if lexer is None:441 lexer = Lexer(environment)442 _lexer_cache[key] = lexer443 return lexer444445446class OptionalLStrip(tuple):447 """A special tuple for marking a point in the state that can have448 lstrip applied.449 """450451 __slots__ = ()452453 # Even though it looks like a no-op, creating instances fails454 # without this.455 def __new__(cls, *members, **kwargs):456 return super(OptionalLStrip, cls).__new__(cls, members)457458459class Lexer(object):460 """Class that implements a lexer for a given environment. Automatically461 created by the environment class, usually you don't have to do that.462463 Note that the lexer is not automatically bound to an environment.464 Multiple environments can share the same lexer.465 """466467 def __init__(self, environment):468 # shortcuts469 e = re.escape470471 def c(x):472 return re.compile(x, re.M | re.S)473474 # lexing rules for tags475 tag_rules = [476 (whitespace_re, TOKEN_WHITESPACE, None),477 (float_re, TOKEN_FLOAT, None),478 (integer_re, TOKEN_INTEGER, None),479 (name_re, TOKEN_NAME, None),480 (string_re, TOKEN_STRING, None),481 (operator_re, TOKEN_OPERATOR, None),482 ]483484 # assemble the root lexing rule. because "|" is ungreedy485 # we have to sort by length so that the lexer continues working486 # as expected when we have parsing rules like <% for block and487 # <%= for variables. (if someone wants asp like syntax)488 # variables are just part of the rules if variable processing489 # is required.490 root_tag_rules = compile_rules(environment)491492 # block suffix if trimming is enabled493 block_suffix_re = environment.trim_blocks and "\\n?" or ""494495 # If lstrip is enabled, it should not be applied if there is any496 # non-whitespace between the newline and block.497 self.lstrip_unless_re = c(r"[^ \t]") if environment.lstrip_blocks else None498499 self.newline_sequence = environment.newline_sequence500 self.keep_trailing_newline = environment.keep_trailing_newline501502 # global lexing rules503 self.rules = {504 "root": [505 # directives506 (507 c(508 "(.*?)(?:%s)"509 % "|".join(510 [511 r"(?P<raw_begin>%s(\-|\+|)\s*raw\s*(?:\-%s\s*|%s))"512 % (513 e(environment.block_start_string),514 e(environment.block_end_string),515 e(environment.block_end_string),516 )517 ]518 + [519 r"(?P<%s>%s(\-|\+|))" % (n, r)520 for n, r in root_tag_rules521 ]522 )523 ),524 OptionalLStrip(TOKEN_DATA, "#bygroup"),525 "#bygroup",526 ),527 # data528 (c(".+"), TOKEN_DATA, None),529 ],530 # comments531 TOKEN_COMMENT_BEGIN: [532 (533 c(534 r"(.*?)((?:\-%s\s*|%s)%s)"535 % (536 e(environment.comment_end_string),537 e(environment.comment_end_string),538 block_suffix_re,539 )540 ),541 (TOKEN_COMMENT, TOKEN_COMMENT_END),542 "#pop",543 ),544 (c("(.)"), (Failure("Missing end of comment tag"),), None),545 ],546 # blocks547 TOKEN_BLOCK_BEGIN: [548 (549 c(550 r"(?:\-%s\s*|%s)%s"551 % (552 e(environment.block_end_string),553 e(environment.block_end_string),554 block_suffix_re,555 )556 ),557 TOKEN_BLOCK_END,558 "#pop",559 ),560 ]561 + tag_rules,562 # variables563 TOKEN_VARIABLE_BEGIN: [564 (565 c(566 r"\-%s\s*|%s"567 % (568 e(environment.variable_end_string),569 e(environment.variable_end_string),570 )571 ),572 TOKEN_VARIABLE_END,573 "#pop",574 )575 ]576 + tag_rules,577 # raw block578 TOKEN_RAW_BEGIN: [579 (580 c(581 r"(.*?)((?:%s(\-|\+|))\s*endraw\s*(?:\-%s\s*|%s%s))"582 % (583 e(environment.block_start_string),584 e(environment.block_end_string),585 e(environment.block_end_string),586 block_suffix_re,587 )588 ),589 OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END),590 "#pop",591 ),592 (c("(.)"), (Failure("Missing end of raw directive"),), None),593 ],594 # line statements595 TOKEN_LINESTATEMENT_BEGIN: [596 (c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")597 ]598 + tag_rules,599 # line comments600 TOKEN_LINECOMMENT_BEGIN: [601 (602 c(r"(.*?)()(?=\n|$)"),603 (TOKEN_LINECOMMENT, TOKEN_LINECOMMENT_END),604 "#pop",605 )606 ],607 }608609 def _normalize_newlines(self, value):610 """Called for strings and template data to normalize it to unicode."""611 return newline_re.sub(self.newline_sequence, value)612613 def tokenize(self, source, name=None, filename=None, state=None):614 """Calls tokeniter + tokenize and wraps it in a token stream."""615 stream = self.tokeniter(source, name, filename, state)616 return TokenStream(self.wrap(stream, name, filename), name, filename)617618 def wrap(self, stream, name=None, filename=None):619 """This is called with the stream as returned by `tokenize` and wraps620 every token in a :class:`Token` and converts the value.621 """622 for lineno, token, value in stream:623 if token in ignored_tokens:624 continue625 elif token == TOKEN_LINESTATEMENT_BEGIN:626 token = TOKEN_BLOCK_BEGIN627 elif token == TOKEN_LINESTATEMENT_END:628 token = TOKEN_BLOCK_END629 # we are not interested in those tokens in the parser630 elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END):631 continue632 elif token == TOKEN_DATA:633 value = self._normalize_newlines(value)634 elif token == "keyword":635 token = value636 elif token == TOKEN_NAME:637 value = str(value)638 if check_ident and not value.isidentifier():639 raise TemplateSyntaxError(640 "Invalid character in identifier", lineno, name, filename641 )642 elif token == TOKEN_STRING:643 # try to unescape string644 try:645 value = (646 self._normalize_newlines(value[1:-1])647 .encode("ascii", "backslashreplace")648 .decode("unicode-escape")649 )650 except Exception as e:651 msg = str(e).split(":")[-1].strip()652 raise TemplateSyntaxError(msg, lineno, name, filename)653 elif token == TOKEN_INTEGER:654 value = int(value.replace("_", ""))655 elif token == TOKEN_FLOAT:656 # remove all "_" first to support more Python versions657 value = literal_eval(value.replace("_", ""))658 elif token == TOKEN_OPERATOR:659 token = operators[value]660 yield Token(lineno, token, value)661662 def tokeniter(self, source, name, filename=None, state=None):663 """This method tokenizes the text and returns the tokens in a664 generator. Use this method if you just want to tokenize a template.665 """666 source = text_type(source)667 lines = source.splitlines()668 if self.keep_trailing_newline and source:669 for newline in ("\r\n", "\r", "\n"):670 if source.endswith(newline):671 lines.append("")672 break673 source = "\n".join(lines)674 pos = 0675 lineno = 1676 stack = ["root"]677 if state is not None and state != "root":678 assert state in ("variable", "block"), "invalid state"679 stack.append(state + "_begin")680 statetokens = self.rules[stack[-1]]681 source_length = len(source)682 balancing_stack = []683 lstrip_unless_re = self.lstrip_unless_re684685 while 1:686 # tokenizer loop687 for regex, tokens, new_state in statetokens:688 m = regex.match(source, pos)689 # if no match we try again with the next rule690 if m is None:691 continue692693 # we only match blocks and variables if braces / parentheses694 # are balanced. continue parsing with the lower rule which695 # is the operator rule. do this only if the end tags look696 # like operators697 if balancing_stack and tokens in (698 TOKEN_VARIABLE_END,699 TOKEN_BLOCK_END,700 TOKEN_LINESTATEMENT_END,701 ):702 continue703704 # tuples support more options705 if isinstance(tokens, tuple):706 groups = m.groups()707708 if isinstance(tokens, OptionalLStrip):709 # Rule supports lstrip. Match will look like710 # text, block type, whitespace control, type, control, ...711 text = groups[0]712713 # Skipping the text and first type, every other group is the714 # whitespace control for each type. One of the groups will be715 # -, +, or empty string instead of None.716 strip_sign = next(g for g in groups[2::2] if g is not None)717718 if strip_sign == "-":719 # Strip all whitespace between the text and the tag.720 groups = (text.rstrip(),) + groups[1:]721 elif (722 # Not marked for preserving whitespace.723 strip_sign != "+"724 # lstrip is enabled.725 and lstrip_unless_re is not None726 # Not a variable expression.727 and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)728 ):729 # The start of text between the last newline and the tag.730 l_pos = text.rfind("\n") + 1731732 # If there's only whitespace between the newline and the733 # tag, strip it.734 if not lstrip_unless_re.search(text, l_pos):735 groups = (text[:l_pos],) + groups[1:]736737 for idx, token in enumerate(tokens):738 # failure group739 if token.__class__ is Failure:740 raise token(lineno, filename)741 # bygroup is a bit more complex, in that case we742 # yield for the current token the first named743 # group that matched744 elif token == "#bygroup":745 for key, value in iteritems(m.groupdict()):746 if value is not None:747 yield lineno, key, value748 lineno += value.count("\n")749 break750 else:751 raise RuntimeError(752 "%r wanted to resolve "753 "the token dynamically"754 " but no group matched" % regex755 )756 # normal group757 else:758 data = groups[idx]759 if data or token not in ignore_if_empty:760 yield lineno, token, data761 lineno += data.count("\n")762763 # strings as token just are yielded as it.764 else:765 data = m.group()766 # update brace/parentheses balance767 if tokens == TOKEN_OPERATOR:768 if data == "{":769 balancing_stack.append("}")770 elif data == "(":771 balancing_stack.append(")")772 elif data == "[":773 balancing_stack.append("]")774 elif data in ("}", ")", "]"):775 if not balancing_stack:776 raise TemplateSyntaxError(777 "unexpected '%s'" % data, lineno, name, filename778 )779 expected_op = balancing_stack.pop()780 if expected_op != data:781 raise TemplateSyntaxError(782 "unexpected '%s', "783 "expected '%s'" % (data, expected_op),784 lineno,785 name,786 filename,787 )788 # yield items789 if data or tokens not in ignore_if_empty:790 yield lineno, tokens, data791 lineno += data.count("\n")792793 # fetch new position into new variable so that we can check794 # if there is a internal parsing error which would result795 # in an infinite loop796 pos2 = m.end()797798 # handle state changes799 if new_state is not None:800 # remove the uppermost state801 if new_state == "#pop":802 stack.pop()803 # resolve the new state by group checking804 elif new_state == "#bygroup":805 for key, value in iteritems(m.groupdict()):806 if value is not None:807 stack.append(key)808 break809 else:810 raise RuntimeError(811 "%r wanted to resolve the "812 "new state dynamically but"813 " no group matched" % regex814 )815 # direct state name given816 else:817 stack.append(new_state)818 statetokens = self.rules[stack[-1]]819 # we are still at the same position and no stack change.820 # this means a loop without break condition, avoid that and821 # raise error822 elif pos2 == pos:823 raise RuntimeError(824 "%r yielded empty string without stack change" % regex825 )826 # publish new function and start again827 pos = pos2828 break829 # if loop terminated without break we haven't found a single match830 # either we are at the end of the file or we have a problem831 else:832 # end of text833 if pos >= source_length:834 return835 # something went wrong836 raise TemplateSyntaxError(837 "unexpected char %r at %d" % (source[pos], pos),838 lineno,839 name,840 filename,841 )
added:src/jinja/loaders.py+572 added
1# -*- coding: utf-8 -*-2"""API and implementations for loading templates from different data3sources.4"""5import os6import pkgutil7import sys8import weakref9from hashlib import sha110from importlib import import_module11from os import path12from types import ModuleType1314from ._compat import abc15from ._compat import fspath16from ._compat import iteritems17from ._compat import string_types18from .exceptions import TemplateNotFound19from .utils import internalcode20from .utils import open_if_exists212223def split_template_path(template):24 """Split a path into segments and perform a sanity check. If it detects25 '..' in the path it will raise a `TemplateNotFound` error.26 """27 pieces = []28 for piece in template.split("/"):29 if (30 path.sep in piece31 or (path.altsep and path.altsep in piece)32 or piece == path.pardir33 ):34 raise TemplateNotFound(template)35 elif piece and piece != ".":36 pieces.append(piece)37 return pieces383940class BaseLoader(object):41 """Baseclass for all loaders. Subclass this and override `get_source` to42 implement a custom loading mechanism. The environment provides a43 `get_template` method that calls the loader's `load` method to get the44 :class:`Template` object.4546 A very basic example for a loader that looks up templates on the file47 system could look like this::4849 from jinja import BaseLoader, TemplateNotFound50 from os.path import join, exists, getmtime5152 class MyLoader(BaseLoader):5354 def __init__(self, path):55 self.path = path5657 def get_source(self, environment, template):58 path = join(self.path, template)59 if not exists(path):60 raise TemplateNotFound(template)61 mtime = getmtime(path)62 with file(path) as f:63 source = f.read().decode('utf-8')64 return source, path, lambda: mtime == getmtime(path)65 """6667 #: if set to `False` it indicates that the loader cannot provide access68 #: to the source of templates.69 #:70 #: .. versionadded:: 2.471 has_source_access = True7273 def get_source(self, environment, template):74 """Get the template source, filename and reload helper for a template.75 It's passed the environment and template name and has to return a76 tuple in the form ``(source, filename, uptodate)`` or raise a77 `TemplateNotFound` error if it can't locate the template.7879 The source part of the returned tuple must be the source of the80 template as unicode string or a ASCII bytestring. The filename should81 be the name of the file on the filesystem if it was loaded from there,82 otherwise `None`. The filename is used by python for the tracebacks83 if no loader extension is used.8485 The last item in the tuple is the `uptodate` function. If auto86 reloading is enabled it's always called to check if the template87 changed. No arguments are passed so the function must store the88 old state somewhere (for example in a closure). If it returns `False`89 the template will be reloaded.90 """91 if not self.has_source_access:92 raise RuntimeError(93 "%s cannot provide access to the source" % self.__class__.__name__94 )95 raise TemplateNotFound(template)9697 def list_templates(self):98 """Iterates over all templates. If the loader does not support that99 it should raise a :exc:`TypeError` which is the default behavior.100 """101 raise TypeError("this loader cannot iterate over all templates")102103 @internalcode104 def load(self, environment, name, globals=None):105 """Loads a template. This method looks up the template in the cache106 or loads one by calling :meth:`get_source`. Subclasses should not107 override this method as loaders working on collections of other108 loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)109 will not call this method but `get_source` directly.110 """111 code = None112 if globals is None:113 globals = {}114115 # first we try to get the source for this template together116 # with the filename and the uptodate function.117 source, filename, uptodate = self.get_source(environment, name)118119 # try to load the code from the bytecode cache if there is a120 # bytecode cache configured.121 bcc = environment.bytecode_cache122 if bcc is not None:123 bucket = bcc.get_bucket(environment, name, filename, source)124 code = bucket.code125126 # if we don't have code so far (not cached, no longer up to127 # date) etc. we compile the template128 if code is None:129 code = environment.compile(source, name, filename)130131 # if the bytecode cache is available and the bucket doesn't132 # have a code so far, we give the bucket the new code and put133 # it back to the bytecode cache.134 if bcc is not None and bucket.code is None:135 bucket.code = code136 bcc.set_bucket(bucket)137138 return environment.template_class.from_code(139 environment, code, globals, uptodate140 )141142143class FileSystemLoader(BaseLoader):144 """Loads templates from the file system. This loader can find templates145 in folders on the file system and is the preferred way to load them.146147 The loader takes the path to the templates as string, or if multiple148 locations are wanted a list of them which is then looked up in the149 given order::150151 >>> loader = FileSystemLoader('/path/to/templates')152 >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])153154 Per default the template encoding is ``'utf-8'`` which can be changed155 by setting the `encoding` parameter to something else.156157 To follow symbolic links, set the *followlinks* parameter to ``True``::158159 >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)160161 .. versionchanged:: 2.8162 The ``followlinks`` parameter was added.163 """164165 def __init__(self, searchpath, encoding="utf-8", followlinks=False):166 if not isinstance(searchpath, abc.Iterable) or isinstance(167 searchpath, string_types168 ):169 searchpath = [searchpath]170171 # In Python 3.5, os.path.join doesn't support Path. This can be172 # simplified to list(searchpath) when Python 3.5 is dropped.173 self.searchpath = [fspath(p) for p in searchpath]174175 self.encoding = encoding176 self.followlinks = followlinks177178 def get_source(self, environment, template):179 pieces = split_template_path(template)180 for searchpath in self.searchpath:181 filename = path.join(searchpath, *pieces)182 f = open_if_exists(filename)183 if f is None:184 continue185 try:186 contents = f.read().decode(self.encoding)187 finally:188 f.close()189190 mtime = path.getmtime(filename)191192 def uptodate():193 try:194 return path.getmtime(filename) == mtime195 except OSError:196 return False197198 return contents, filename, uptodate199 raise TemplateNotFound(template)200201 def list_templates(self):202 found = set()203 for searchpath in self.searchpath:204 walk_dir = os.walk(searchpath, followlinks=self.followlinks)205 for dirpath, _, filenames in walk_dir:206 for filename in filenames:207 template = (208 os.path.join(dirpath, filename)[len(searchpath) :]209 .strip(os.path.sep)210 .replace(os.path.sep, "/")211 )212 if template[:2] == "./":213 template = template[2:]214 if template not in found:215 found.add(template)216 return sorted(found)217218219class PackageLoader(BaseLoader):220 """Load templates from a directory in a Python package.221222 :param package_name: Import name of the package that contains the223 template directory.224 :param package_path: Directory within the imported package that225 contains the templates.226 :param encoding: Encoding of template files.227228 The following example looks up templates in the ``pages`` directory229 within the ``project.ui`` package.230231 .. code-block:: python232233 loader = PackageLoader("project.ui", "pages")234235 Only packages installed as directories (standard pip behavior) or236 zip/egg files (less common) are supported. The Python API for237 introspecting data in packages is too limited to support other238 installation methods the way this loader requires.239240 There is limited support for :pep:`420` namespace packages. The241 template directory is assumed to only be in one namespace242 contributor. Zip files contributing to a namespace are not243 supported.244245 .. versionchanged:: 2.11.0246 No longer uses ``setuptools`` as a dependency.247248 .. versionchanged:: 2.11.0249 Limited PEP 420 namespace package support.250 """251252 def __init__(self, package_name, package_path="templates", encoding="utf-8"):253 if package_path == os.path.curdir:254 package_path = ""255 elif package_path[:2] == os.path.curdir + os.path.sep:256 package_path = package_path[2:]257258 package_path = os.path.normpath(package_path).rstrip(os.path.sep)259 self.package_path = package_path260 self.package_name = package_name261 self.encoding = encoding262263 # Make sure the package exists. This also makes namespace264 # packages work, otherwise get_loader returns None.265 import_module(package_name)266 self._loader = loader = pkgutil.get_loader(package_name)267268 # Zip loader's archive attribute points at the zip.269 self._archive = getattr(loader, "archive", None)270 self._template_root = None271272 if hasattr(loader, "get_filename"):273 # A standard directory package, or a zip package.274 self._template_root = os.path.join(275 os.path.dirname(loader.get_filename(package_name)), package_path276 )277 elif hasattr(loader, "_path"):278 # A namespace package, limited support. Find the first279 # contributor with the template directory.280 for root in loader._path:281 root = os.path.join(root, package_path)282283 if os.path.isdir(root):284 self._template_root = root285 break286287 if self._template_root is None:288 raise ValueError(289 "The %r package was not installed in a way that"290 " PackageLoader understands." % package_name291 )292293 def get_source(self, environment, template):294 p = os.path.join(self._template_root, *split_template_path(template))295296 if self._archive is None:297 # Package is a directory.298 if not os.path.isfile(p):299 raise TemplateNotFound(template)300301 with open(p, "rb") as f:302 source = f.read()303304 mtime = os.path.getmtime(p)305306 def up_to_date():307 return os.path.isfile(p) and os.path.getmtime(p) == mtime308309 else:310 # Package is a zip file.311 try:312 source = self._loader.get_data(p)313 except OSError:314 raise TemplateNotFound(template)315316 # Could use the zip's mtime for all template mtimes, but317 # would need to safely reload the module if it's out of318 # date, so just report it as always current.319 up_to_date = None320321 return source.decode(self.encoding), p, up_to_date322323 def list_templates(self):324 results = []325326 if self._archive is None:327 # Package is a directory.328 offset = len(self._template_root)329330 for dirpath, _, filenames in os.walk(self._template_root):331 dirpath = dirpath[offset:].lstrip(os.path.sep)332 results.extend(333 os.path.join(dirpath, name).replace(os.path.sep, "/")334 for name in filenames335 )336 else:337 if not hasattr(self._loader, "_files"):338 raise TypeError(339 "This zip import does not have the required"340 " metadata to list templates."341 )342343 # Package is a zip file.344 prefix = (345 self._template_root[len(self._archive) :].lstrip(os.path.sep)346 + os.path.sep347 )348 offset = len(prefix)349350 for name in self._loader._files.keys():351 # Find names under the templates directory that aren't directories.352 if name.startswith(prefix) and name[-1] != os.path.sep:353 results.append(name[offset:].replace(os.path.sep, "/"))354355 results.sort()356 return results357358359class DictLoader(BaseLoader):360 """Loads a template from a python dict. It's passed a dict of unicode361 strings bound to template names. This loader is useful for unittesting:362363 >>> loader = DictLoader({'index.html': 'source here'})364365 Because auto reloading is rarely useful this is disabled per default.366 """367368 def __init__(self, mapping):369 self.mapping = mapping370371 def get_source(self, environment, template):372 if template in self.mapping:373 source = self.mapping[template]374 return source, None, lambda: source == self.mapping.get(template)375 raise TemplateNotFound(template)376377 def list_templates(self):378 return sorted(self.mapping)379380381class FunctionLoader(BaseLoader):382 """A loader that is passed a function which does the loading. The383 function receives the name of the template and has to return either384 an unicode string with the template source, a tuple in the form ``(source,385 filename, uptodatefunc)`` or `None` if the template does not exist.386387 >>> def load_template(name):388 ... if name == 'index.html':389 ... return '...'390 ...391 >>> loader = FunctionLoader(load_template)392393 The `uptodatefunc` is a function that is called if autoreload is enabled394 and has to return `True` if the template is still up to date. For more395 details have a look at :meth:`BaseLoader.get_source` which has the same396 return value.397 """398399 def __init__(self, load_func):400 self.load_func = load_func401402 def get_source(self, environment, template):403 rv = self.load_func(template)404 if rv is None:405 raise TemplateNotFound(template)406 elif isinstance(rv, string_types):407 return rv, None, None408 return rv409410411class PrefixLoader(BaseLoader):412 """A loader that is passed a dict of loaders where each loader is bound413 to a prefix. The prefix is delimited from the template by a slash per414 default, which can be changed by setting the `delimiter` argument to415 something else::416417 loader = PrefixLoader({418 'app1': PackageLoader('mypackage.app1'),419 'app2': PackageLoader('mypackage.app2')420 })421422 By loading ``'app1/index.html'`` the file from the app1 package is loaded,423 by loading ``'app2/index.html'`` the file from the second.424 """425426 def __init__(self, mapping, delimiter="/"):427 self.mapping = mapping428 self.delimiter = delimiter429430 def get_loader(self, template):431 try:432 prefix, name = template.split(self.delimiter, 1)433 loader = self.mapping[prefix]434 except (ValueError, KeyError):435 raise TemplateNotFound(template)436 return loader, name437438 def get_source(self, environment, template):439 loader, name = self.get_loader(template)440 try:441 return loader.get_source(environment, name)442 except TemplateNotFound:443 # re-raise the exception with the correct filename here.444 # (the one that includes the prefix)445 raise TemplateNotFound(template)446447 @internalcode448 def load(self, environment, name, globals=None):449 loader, local_name = self.get_loader(name)450 try:451 return loader.load(environment, local_name, globals)452 except TemplateNotFound:453 # re-raise the exception with the correct filename here.454 # (the one that includes the prefix)455 raise TemplateNotFound(name)456457 def list_templates(self):458 result = []459 for prefix, loader in iteritems(self.mapping):460 for template in loader.list_templates():461 result.append(prefix + self.delimiter + template)462 return result463464465class ChoiceLoader(BaseLoader):466 """This loader works like the `PrefixLoader` just that no prefix is467 specified. If a template could not be found by one loader the next one468 is tried.469470 >>> loader = ChoiceLoader([471 ... FileSystemLoader('/path/to/user/templates'),472 ... FileSystemLoader('/path/to/system/templates')473 ... ])474475 This is useful if you want to allow users to override builtin templates476 from a different location.477 """478479 def __init__(self, loaders):480 self.loaders = loaders481482 def get_source(self, environment, template):483 for loader in self.loaders:484 try:485 return loader.get_source(environment, template)486 except TemplateNotFound:487 pass488 raise TemplateNotFound(template)489490 @internalcode491 def load(self, environment, name, globals=None):492 for loader in self.loaders:493 try:494 return loader.load(environment, name, globals)495 except TemplateNotFound:496 pass497 raise TemplateNotFound(name)498499 def list_templates(self):500 found = set()501 for loader in self.loaders:502 found.update(loader.list_templates())503 return sorted(found)504505506class _TemplateModule(ModuleType):507 """Like a normal module but with support for weak references"""508509510class ModuleLoader(BaseLoader):511 """This loader loads templates from precompiled templates.512513 Example usage:514515 >>> loader = ChoiceLoader([516 ... ModuleLoader('/path/to/compiled/templates'),517 ... FileSystemLoader('/path/to/templates')518 ... ])519520 Templates can be precompiled with :meth:`Environment.compile_templates`.521 """522523 has_source_access = False524525 def __init__(self, path):526 package_name = "_jinja_module_templates_%x" % id(self)527528 # create a fake module that looks for the templates in the529 # path given.530 mod = _TemplateModule(package_name)531532 if not isinstance(path, abc.Iterable) or isinstance(path, string_types):533 path = [path]534535 mod.__path__ = [fspath(p) for p in path]536537 sys.modules[package_name] = weakref.proxy(538 mod, lambda x: sys.modules.pop(package_name, None)539 )540541 # the only strong reference, the sys.modules entry is weak542 # so that the garbage collector can remove it once the543 # loader that created it goes out of business.544 self.module = mod545 self.package_name = package_name546547 @staticmethod548 def get_template_key(name):549 return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()550551 @staticmethod552 def get_module_filename(name):553 return ModuleLoader.get_template_key(name) + ".py"554555 @internalcode556 def load(self, environment, name, globals=None):557 key = self.get_template_key(name)558 module = "%s.%s" % (self.package_name, key)559 mod = getattr(self.module, module, None)560 if mod is None:561 try:562 mod = __import__(module, None, None, ["root"])563 except ImportError:564 raise TemplateNotFound(name)565566 # remove the entry from sys.modules, we only want the attribute567 # on the module object we have stored on the loader.568 sys.modules.pop(module, None)569570 return environment.template_class.from_module_dict(571 environment, mod.__dict__, globals572 )
added:src/jinja/meta.py+101 added
1# -*- coding: utf-8 -*-2"""Functions that expose information about templates that might be3interesting for introspection.4"""5from . import nodes6from ._compat import iteritems7from ._compat import string_types8from .compiler import CodeGenerator91011class TrackingCodeGenerator(CodeGenerator):12 """We abuse the code generator for introspection."""1314 def __init__(self, environment):15 CodeGenerator.__init__(self, environment, "<introspection>", "<introspection>")16 self.undeclared_identifiers = set()1718 def write(self, x):19 """Don't write."""2021 def enter_frame(self, frame):22 """Remember all undeclared identifiers."""23 CodeGenerator.enter_frame(self, frame)24 for _, (action, param) in iteritems(frame.symbols.loads):25 if action == "resolve" and param not in self.environment.globals:26 self.undeclared_identifiers.add(param)272829def find_undeclared_variables(ast):30 """Returns a set of all variables in the AST that will be looked up from31 the context at runtime. Because at compile time it's not known which32 variables will be used depending on the path the execution takes at33 runtime, all variables are returned.3435 >>> from jinja import Environment, meta36 >>> env = Environment()37 >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')38 >>> meta.find_undeclared_variables(ast) == set(['bar'])39 True4041 .. admonition:: Implementation4243 Internally the code generator is used for finding undeclared variables.44 This is good to know because the code generator might raise a45 :exc:`TemplateAssertionError` during compilation and as a matter of46 fact this function can currently raise that exception as well.47 """48 codegen = TrackingCodeGenerator(ast.environment)49 codegen.visit(ast)50 return codegen.undeclared_identifiers515253def find_referenced_templates(ast):54 """Finds all the referenced templates from the AST. This will return an55 iterator over all the hardcoded template extensions, inclusions and56 imports. If dynamic inheritance or inclusion is used, `None` will be57 yielded.5859 >>> from jinja import Environment, meta60 >>> env = Environment()61 >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')62 >>> list(meta.find_referenced_templates(ast))63 ['layout.html', None]6465 This function is useful for dependency tracking. For example if you want66 to rebuild parts of the website after a layout template has changed.67 """68 for node in ast.find_all(69 (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)70 ):71 if not isinstance(node.template, nodes.Const):72 # a tuple with some non consts in there73 if isinstance(node.template, (nodes.Tuple, nodes.List)):74 for template_name in node.template.items:75 # something const, only yield the strings and ignore76 # non-string consts that really just make no sense77 if isinstance(template_name, nodes.Const):78 if isinstance(template_name.value, string_types):79 yield template_name.value80 # something dynamic in there81 else:82 yield None83 # something dynamic we don't know about here84 else:85 yield None86 continue87 # constant is a basestring, direct template name88 if isinstance(node.template.value, string_types):89 yield node.template.value90 # a tuple or list (latter *should* not happen) made of consts,91 # yield the consts that are strings. We could warn here for92 # non string values93 elif isinstance(node, nodes.Include) and isinstance(94 node.template.value, (tuple, list)95 ):96 for template_name in node.template.value:97 if isinstance(template_name, string_types):98 yield template_name99 # something else we don't care about, we could warn here100 else:101 yield None
added:src/jinja/nativetypes.py+111 added
1import types2from ast import literal_eval3from itertools import chain4from itertools import islice56from . import nodes7from ._compat import text_type8from .compiler import CodeGenerator9from .compiler import has_safe_repr10from .environment import Environment11from .environment import Template121314def native_concat(nodes, preserve_quotes=True):15 """Return a native Python type from the list of compiled nodes. If16 the result is a single node, its value is returned. Otherwise, the17 nodes are concatenated as strings. If the result can be parsed with18 :func:`ast.literal_eval`, the parsed value is returned. Otherwise,19 the string is returned.2021 :param nodes: Iterable of nodes to concatenate.22 :param preserve_quotes: Whether to re-wrap literal strings with23 quotes, to preserve quotes around expressions for later parsing.24 Should be ``False`` in :meth:`NativeEnvironment.render`.25 """26 head = list(islice(nodes, 2))2728 if not head:29 return None3031 if len(head) == 1:32 raw = head[0]33 else:34 if isinstance(nodes, types.GeneratorType):35 nodes = chain(head, nodes)36 raw = u"".join([text_type(v) for v in nodes])3738 try:39 literal = literal_eval(raw)40 except (ValueError, SyntaxError, MemoryError):41 return raw4243 # If literal_eval returned a string, re-wrap with the original44 # quote character to avoid dropping quotes between expression nodes.45 # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should46 # be ('a', 'b').47 if preserve_quotes and isinstance(literal, str):48 return "{quote}{}{quote}".format(literal, quote=raw[0])4950 return literal515253class NativeCodeGenerator(CodeGenerator):54 """A code generator which renders Python types by not adding55 ``to_string()`` around output nodes, and using :func:`native_concat`56 to convert complex strings back to Python types if possible.57 """5859 @staticmethod60 def _default_finalize(value):61 return value6263 def _output_const_repr(self, group):64 return repr(native_concat(group))6566 def _output_child_to_const(self, node, frame, finalize):67 const = node.as_const(frame.eval_ctx)6869 if not has_safe_repr(const):70 raise nodes.Impossible()7172 if isinstance(node, nodes.TemplateData):73 return const7475 return finalize.const(const)7677 def _output_child_pre(self, node, frame, finalize):78 if finalize.src is not None:79 self.write(finalize.src)8081 def _output_child_post(self, node, frame, finalize):82 if finalize.src is not None:83 self.write(")")848586class NativeEnvironment(Environment):87 """An environment that renders templates to native Python types."""8889 code_generator_class = NativeCodeGenerator909192class NativeTemplate(Template):93 environment_class = NativeEnvironment9495 def render(self, *args, **kwargs):96 """Render the template to produce a native Python type. If the97 result is a single node, its value is returned. Otherwise, the98 nodes are concatenated as strings. If the result can be parsed99 with :func:`ast.literal_eval`, the parsed value is returned.100 Otherwise, the string is returned.101 """102 vars = dict(*args, **kwargs)103 try:104 return native_concat(105 self.root_render_func(self.new_context(vars)), preserve_quotes=False106 )107 except Exception:108 return self.environment.handle_exception()109110111NativeEnvironment.template_class = NativeTemplate
added:src/jinja/nodes.py+1087 added
1# -*- coding: utf-8 -*-2"""AST nodes generated by the parser for the compiler. Also provides3some node tree helper functions used by the parser and compiler in order4to normalize nodes.5"""6import operator7from collections import deque89from ._compat import izip10from ._compat import PY211from ._compat import text_type12from ._compat import with_metaclass13from .utils import Markup1415_binop_to_func = {16 "*": operator.mul,17 "/": operator.truediv,18 "//": operator.floordiv,19 "**": operator.pow,20 "%": operator.mod,21 "+": operator.add,22 "-": operator.sub,23}2425_uaop_to_func = {"not": operator.not_, "+": operator.pos, "-": operator.neg}2627_cmpop_to_func = {28 "eq": operator.eq,29 "ne": operator.ne,30 "gt": operator.gt,31 "gteq": operator.ge,32 "lt": operator.lt,33 "lteq": operator.le,34 "in": lambda a, b: a in b,35 "notin": lambda a, b: a not in b,36}373839class Impossible(Exception):40 """Raised if the node could not perform a requested action."""414243class NodeType(type):44 """A metaclass for nodes that handles the field and attribute45 inheritance. fields and attributes from the parent class are46 automatically forwarded to the child."""4748 def __new__(mcs, name, bases, d):49 for attr in "fields", "attributes":50 storage = []51 storage.extend(getattr(bases[0], attr, ()))52 storage.extend(d.get(attr, ()))53 assert len(bases) == 1, "multiple inheritance not allowed"54 assert len(storage) == len(set(storage)), "layout conflict"55 d[attr] = tuple(storage)56 d.setdefault("abstract", False)57 return type.__new__(mcs, name, bases, d)585960class EvalContext(object):61 """Holds evaluation time information. Custom attributes can be attached62 to it in extensions.63 """6465 def __init__(self, environment, template_name=None):66 self.environment = environment67 if callable(environment.autoescape):68 self.autoescape = environment.autoescape(template_name)69 else:70 self.autoescape = environment.autoescape71 self.volatile = False7273 def save(self):74 return self.__dict__.copy()7576 def revert(self, old):77 self.__dict__.clear()78 self.__dict__.update(old)798081def get_eval_context(node, ctx):82 if ctx is None:83 if node.environment is None:84 raise RuntimeError(85 "if no eval context is passed, the "86 "node must have an attached "87 "environment."88 )89 return EvalContext(node.environment)90 return ctx919293class Node(with_metaclass(NodeType, object)):94 """Baseclass for all Jinja nodes. There are a number of nodes available95 of different types. There are four major types:9697 - :class:`Stmt`: statements98 - :class:`Expr`: expressions99 - :class:`Helper`: helper nodes100 - :class:`Template`: the outermost wrapper node101102 All nodes have fields and attributes. Fields may be other nodes, lists,103 or arbitrary values. Fields are passed to the constructor as regular104 positional arguments, attributes as keyword arguments. Each node has105 two attributes: `lineno` (the line number of the node) and `environment`.106 The `environment` attribute is set at the end of the parsing process for107 all nodes automatically.108 """109110 fields = ()111 attributes = ("lineno", "environment")112 abstract = True113114 def __init__(self, *fields, **attributes):115 if self.abstract:116 raise TypeError("abstract nodes are not instantiable")117 if fields:118 if len(fields) != len(self.fields):119 if not self.fields:120 raise TypeError("%r takes 0 arguments" % self.__class__.__name__)121 raise TypeError(122 "%r takes 0 or %d argument%s"123 % (124 self.__class__.__name__,125 len(self.fields),126 len(self.fields) != 1 and "s" or "",127 )128 )129 for name, arg in izip(self.fields, fields):130 setattr(self, name, arg)131 for attr in self.attributes:132 setattr(self, attr, attributes.pop(attr, None))133 if attributes:134 raise TypeError("unknown attribute %r" % next(iter(attributes)))135136 def iter_fields(self, exclude=None, only=None):137 """This method iterates over all fields that are defined and yields138 ``(key, value)`` tuples. Per default all fields are returned, but139 it's possible to limit that to some fields by providing the `only`140 parameter or to exclude some using the `exclude` parameter. Both141 should be sets or tuples of field names.142 """143 for name in self.fields:144 if (145 (exclude is only is None)146 or (exclude is not None and name not in exclude)147 or (only is not None and name in only)148 ):149 try:150 yield name, getattr(self, name)151 except AttributeError:152 pass153154 def iter_child_nodes(self, exclude=None, only=None):155 """Iterates over all direct child nodes of the node. This iterates156 over all fields and yields the values of they are nodes. If the value157 of a field is a list all the nodes in that list are returned.158 """159 for _, item in self.iter_fields(exclude, only):160 if isinstance(item, list):161 for n in item:162 if isinstance(n, Node):163 yield n164 elif isinstance(item, Node):165 yield item166167 def find(self, node_type):168 """Find the first node of a given type. If no such node exists the169 return value is `None`.170 """171 for result in self.find_all(node_type):172 return result173174 def find_all(self, node_type):175 """Find all the nodes of a given type. If the type is a tuple,176 the check is performed for any of the tuple items.177 """178 for child in self.iter_child_nodes():179 if isinstance(child, node_type):180 yield child181 for result in child.find_all(node_type):182 yield result183184 def set_ctx(self, ctx):185 """Reset the context of a node and all child nodes. Per default the186 parser will all generate nodes that have a 'load' context as it's the187 most common one. This method is used in the parser to set assignment188 targets and other nodes to a store context.189 """190 todo = deque([self])191 while todo:192 node = todo.popleft()193 if "ctx" in node.fields:194 node.ctx = ctx195 todo.extend(node.iter_child_nodes())196 return self197198 def set_lineno(self, lineno, override=False):199 """Set the line numbers of the node and children."""200 todo = deque([self])201 while todo:202 node = todo.popleft()203 if "lineno" in node.attributes:204 if node.lineno is None or override:205 node.lineno = lineno206 todo.extend(node.iter_child_nodes())207 return self208209 def set_environment(self, environment):210 """Set the environment for all nodes."""211 todo = deque([self])212 while todo:213 node = todo.popleft()214 node.environment = environment215 todo.extend(node.iter_child_nodes())216 return self217218 def __eq__(self, other):219 return type(self) is type(other) and tuple(self.iter_fields()) == tuple(220 other.iter_fields()221 )222223 def __ne__(self, other):224 return not self.__eq__(other)225226 # Restore Python 2 hashing behavior on Python 3227 __hash__ = object.__hash__228229 def __repr__(self):230 return "%s(%s)" % (231 self.__class__.__name__,232 ", ".join("%s=%r" % (arg, getattr(self, arg, None)) for arg in self.fields),233 )234235 def dump(self):236 def _dump(node):237 if not isinstance(node, Node):238 buf.append(repr(node))239 return240241 buf.append("nodes.%s(" % node.__class__.__name__)242 if not node.fields:243 buf.append(")")244 return245 for idx, field in enumerate(node.fields):246 if idx:247 buf.append(", ")248 value = getattr(node, field)249 if isinstance(value, list):250 buf.append("[")251 for idx, item in enumerate(value):252 if idx:253 buf.append(", ")254 _dump(item)255 buf.append("]")256 else:257 _dump(value)258 buf.append(")")259260 buf = []261 _dump(self)262 return "".join(buf)263264265class Stmt(Node):266 """Base node for all statements."""267268 abstract = True269270271class Helper(Node):272 """Nodes that exist in a specific context only."""273274 abstract = True275276277class Template(Node):278 """Node that represents a template. This must be the outermost node that279 is passed to the compiler.280 """281282 fields = ("body",)283284285class Output(Stmt):286 """A node that holds multiple expressions which are then printed out.287 This is used both for the `print` statement and the regular template data.288 """289290 fields = ("nodes",)291292293class Extends(Stmt):294 """Represents an extends statement."""295296 fields = ("template",)297298299class For(Stmt):300 """The for loop. `target` is the target for the iteration (usually a301 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list302 of nodes that are used as loop-body, and `else_` a list of nodes for the303 `else` block. If no else node exists it has to be an empty list.304305 For filtered nodes an expression can be stored as `test`, otherwise `None`.306 """307308 fields = ("target", "iter", "body", "else_", "test", "recursive")309310311class If(Stmt):312 """If `test` is true, `body` is rendered, else `else_`."""313314 fields = ("test", "body", "elif_", "else_")315316317class Macro(Stmt):318 """A macro definition. `name` is the name of the macro, `args` a list of319 arguments and `defaults` a list of defaults if there are any. `body` is320 a list of nodes for the macro body.321 """322323 fields = ("name", "args", "defaults", "body")324325326class CallBlock(Stmt):327 """Like a macro without a name but a call instead. `call` is called with328 the unnamed macro as `caller` argument this node holds.329 """330331 fields = ("call", "args", "defaults", "body")332333334class FilterBlock(Stmt):335 """Node for filter sections."""336337 fields = ("body", "filter")338339340class With(Stmt):341 """Specific node for with statements. In older versions of Jinja the342 with statement was implemented on the base of the `Scope` node instead.343344 .. versionadded:: 2.9.3345 """346347 fields = ("targets", "values", "body")348349350class Block(Stmt):351 """A node that represents a block."""352353 fields = ("name", "body", "scoped")354355356class Include(Stmt):357 """A node that represents the include tag."""358359 fields = ("template", "with_context", "ignore_missing")360361362class Import(Stmt):363 """A node that represents the import tag."""364365 fields = ("template", "target", "with_context")366367368class FromImport(Stmt):369 """A node that represents the from import tag. It's important to not370 pass unsafe names to the name attribute. The compiler translates the371 attribute lookups directly into getattr calls and does *not* use the372 subscript callback of the interface. As exported variables may not373 start with double underscores (which the parser asserts) this is not a374 problem for regular Jinja code, but if this node is used in an extension375 extra care must be taken.376377 The list of names may contain tuples if aliases are wanted.378 """379380 fields = ("template", "names", "with_context")381382383class ExprStmt(Stmt):384 """A statement that evaluates an expression and discards the result."""385386 fields = ("node",)387388389class Assign(Stmt):390 """Assigns an expression to a target."""391392 fields = ("target", "node")393394395class AssignBlock(Stmt):396 """Assigns a block to a target."""397398 fields = ("target", "filter", "body")399400401class Expr(Node):402 """Baseclass for all expressions."""403404 abstract = True405406 def as_const(self, eval_ctx=None):407 """Return the value of the expression as constant or raise408 :exc:`Impossible` if this was not possible.409410 An :class:`EvalContext` can be provided, if none is given411 a default context is created which requires the nodes to have412 an attached environment.413414 .. versionchanged:: 2.4415 the `eval_ctx` parameter was added.416 """417 raise Impossible()418419 def can_assign(self):420 """Check if it's possible to assign something to this node."""421 return False422423424class BinExpr(Expr):425 """Baseclass for all binary expressions."""426427 fields = ("left", "right")428 operator = None429 abstract = True430431 def as_const(self, eval_ctx=None):432 eval_ctx = get_eval_context(self, eval_ctx)433 # intercepted operators cannot be folded at compile time434 if (435 self.environment.sandboxed436 and self.operator in self.environment.intercepted_binops437 ):438 raise Impossible()439 f = _binop_to_func[self.operator]440 try:441 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))442 except Exception:443 raise Impossible()444445446class UnaryExpr(Expr):447 """Baseclass for all unary expressions."""448449 fields = ("node",)450 operator = None451 abstract = True452453 def as_const(self, eval_ctx=None):454 eval_ctx = get_eval_context(self, eval_ctx)455 # intercepted operators cannot be folded at compile time456 if (457 self.environment.sandboxed458 and self.operator in self.environment.intercepted_unops459 ):460 raise Impossible()461 f = _uaop_to_func[self.operator]462 try:463 return f(self.node.as_const(eval_ctx))464 except Exception:465 raise Impossible()466467468class Name(Expr):469 """Looks up a name or stores a value in a name.470 The `ctx` of the node can be one of the following values:471472 - `store`: store a value in the name473 - `load`: load that name474 - `param`: like `store` but if the name was defined as function parameter.475 """476477 fields = ("name", "ctx")478479 def can_assign(self):480 return self.name not in ("true", "false", "none", "True", "False", "None")481482483class NSRef(Expr):484 """Reference to a namespace value assignment"""485486 fields = ("name", "attr")487488 def can_assign(self):489 # We don't need any special checks here; NSRef assignments have a490 # runtime check to ensure the target is a namespace object which will491 # have been checked already as it is created using a normal assignment492 # which goes through a `Name` node.493 return True494495496class Literal(Expr):497 """Baseclass for literals."""498499 abstract = True500501502class Const(Literal):503 """All constant values. The parser will return this node for simple504 constants such as ``42`` or ``"foo"`` but it can be used to store more505 complex values such as lists too. Only constants with a safe506 representation (objects where ``eval(repr(x)) == x`` is true).507 """508509 fields = ("value",)510511 def as_const(self, eval_ctx=None):512 rv = self.value513 if (514 PY2515 and type(rv) is text_type516 and self.environment.policies["compiler.ascii_str"]517 ):518 try:519 rv = rv.encode("ascii")520 except UnicodeError:521 pass522 return rv523524 @classmethod525 def from_untrusted(cls, value, lineno=None, environment=None):526 """Return a const object if the value is representable as527 constant value in the generated code, otherwise it will raise528 an `Impossible` exception.529 """530 from .compiler import has_safe_repr531532 if not has_safe_repr(value):533 raise Impossible()534 return cls(value, lineno=lineno, environment=environment)535536537class TemplateData(Literal):538 """A constant template string."""539540 fields = ("data",)541542 def as_const(self, eval_ctx=None):543 eval_ctx = get_eval_context(self, eval_ctx)544 if eval_ctx.volatile:545 raise Impossible()546 if eval_ctx.autoescape:547 return Markup(self.data)548 return self.data549550551class Tuple(Literal):552 """For loop unpacking and some other things like multiple arguments553 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple554 is used for loading the names or storing.555 """556557 fields = ("items", "ctx")558559 def as_const(self, eval_ctx=None):560 eval_ctx = get_eval_context(self, eval_ctx)561 return tuple(x.as_const(eval_ctx) for x in self.items)562563 def can_assign(self):564 for item in self.items:565 if not item.can_assign():566 return False567 return True568569570class List(Literal):571 """Any list literal such as ``[1, 2, 3]``"""572573 fields = ("items",)574575 def as_const(self, eval_ctx=None):576 eval_ctx = get_eval_context(self, eval_ctx)577 return [x.as_const(eval_ctx) for x in self.items]578579580class Dict(Literal):581 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of582 :class:`Pair` nodes.583 """584585 fields = ("items",)586587 def as_const(self, eval_ctx=None):588 eval_ctx = get_eval_context(self, eval_ctx)589 return dict(x.as_const(eval_ctx) for x in self.items)590591592class Pair(Helper):593 """A key, value pair for dicts."""594595 fields = ("key", "value")596597 def as_const(self, eval_ctx=None):598 eval_ctx = get_eval_context(self, eval_ctx)599 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)600601602class Keyword(Helper):603 """A key, value pair for keyword arguments where key is a string."""604605 fields = ("key", "value")606607 def as_const(self, eval_ctx=None):608 eval_ctx = get_eval_context(self, eval_ctx)609 return self.key, self.value.as_const(eval_ctx)610611612class CondExpr(Expr):613 """A conditional expression (inline if expression). (``{{614 foo if bar else baz }}``)615 """616617 fields = ("test", "expr1", "expr2")618619 def as_const(self, eval_ctx=None):620 eval_ctx = get_eval_context(self, eval_ctx)621 if self.test.as_const(eval_ctx):622 return self.expr1.as_const(eval_ctx)623624 # if we evaluate to an undefined object, we better do that at runtime625 if self.expr2 is None:626 raise Impossible()627628 return self.expr2.as_const(eval_ctx)629630631def args_as_const(node, eval_ctx):632 args = [x.as_const(eval_ctx) for x in node.args]633 kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)634635 if node.dyn_args is not None:636 try:637 args.extend(node.dyn_args.as_const(eval_ctx))638 except Exception:639 raise Impossible()640641 if node.dyn_kwargs is not None:642 try:643 kwargs.update(node.dyn_kwargs.as_const(eval_ctx))644 except Exception:645 raise Impossible()646647 return args, kwargs648649650class Filter(Expr):651 """This node applies a filter on an expression. `name` is the name of652 the filter, the rest of the fields are the same as for :class:`Call`.653654 If the `node` of a filter is `None` the contents of the last buffer are655 filtered. Buffers are created by macros and filter blocks.656 """657658 fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")659660 def as_const(self, eval_ctx=None):661 eval_ctx = get_eval_context(self, eval_ctx)662663 if eval_ctx.volatile or self.node is None:664 raise Impossible()665666 # we have to be careful here because we call filter_ below.667 # if this variable would be called filter, 2to3 would wrap the668 # call in a list because it is assuming we are talking about the669 # builtin filter function here which no longer returns a list in670 # python 3. because of that, do not rename filter_ to filter!671 filter_ = self.environment.filters.get(self.name)672673 if filter_ is None or getattr(filter_, "contextfilter", False):674 raise Impossible()675676 # We cannot constant handle async filters, so we need to make sure677 # to not go down this path.678 if eval_ctx.environment.is_async and getattr(679 filter_, "asyncfiltervariant", False680 ):681 raise Impossible()682683 args, kwargs = args_as_const(self, eval_ctx)684 args.insert(0, self.node.as_const(eval_ctx))685686 if getattr(filter_, "evalcontextfilter", False):687 args.insert(0, eval_ctx)688 elif getattr(filter_, "environmentfilter", False):689 args.insert(0, self.environment)690691 try:692 return filter_(*args, **kwargs)693 except Exception:694 raise Impossible()695696697class Test(Expr):698 """Applies a test on an expression. `name` is the name of the test, the699 rest of the fields are the same as for :class:`Call`.700 """701702 fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")703704 def as_const(self, eval_ctx=None):705 test = self.environment.tests.get(self.name)706707 if test is None:708 raise Impossible()709710 eval_ctx = get_eval_context(self, eval_ctx)711 args, kwargs = args_as_const(self, eval_ctx)712 args.insert(0, self.node.as_const(eval_ctx))713714 try:715 return test(*args, **kwargs)716 except Exception:717 raise Impossible()718719720class Call(Expr):721 """Calls an expression. `args` is a list of arguments, `kwargs` a list722 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`723 and `dyn_kwargs` has to be either `None` or a node that is used as724 node for dynamic positional (``*args``) or keyword (``**kwargs``)725 arguments.726 """727728 fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")729730731class Getitem(Expr):732 """Get an attribute or item from an expression and prefer the item."""733734 fields = ("node", "arg", "ctx")735736 def as_const(self, eval_ctx=None):737 eval_ctx = get_eval_context(self, eval_ctx)738 if self.ctx != "load":739 raise Impossible()740 try:741 return self.environment.getitem(742 self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)743 )744 except Exception:745 raise Impossible()746747 def can_assign(self):748 return False749750751class Getattr(Expr):752 """Get an attribute or item from an expression that is a ascii-only753 bytestring and prefer the attribute.754 """755756 fields = ("node", "attr", "ctx")757758 def as_const(self, eval_ctx=None):759 if self.ctx != "load":760 raise Impossible()761 try:762 eval_ctx = get_eval_context(self, eval_ctx)763 return self.environment.getattr(self.node.as_const(eval_ctx), self.attr)764 except Exception:765 raise Impossible()766767 def can_assign(self):768 return False769770771class Slice(Expr):772 """Represents a slice object. This must only be used as argument for773 :class:`Subscript`.774 """775776 fields = ("start", "stop", "step")777778 def as_const(self, eval_ctx=None):779 eval_ctx = get_eval_context(self, eval_ctx)780781 def const(obj):782 if obj is None:783 return None784 return obj.as_const(eval_ctx)785786 return slice(const(self.start), const(self.stop), const(self.step))787788789class Concat(Expr):790 """Concatenates the list of expressions provided after converting them to791 unicode.792 """793794 fields = ("nodes",)795796 def as_const(self, eval_ctx=None):797 eval_ctx = get_eval_context(self, eval_ctx)798 return "".join(text_type(x.as_const(eval_ctx)) for x in self.nodes)799800801class Compare(Expr):802 """Compares an expression with some other expressions. `ops` must be a803 list of :class:`Operand`\\s.804 """805806 fields = ("expr", "ops")807808 def as_const(self, eval_ctx=None):809 eval_ctx = get_eval_context(self, eval_ctx)810 result = value = self.expr.as_const(eval_ctx)811812 try:813 for op in self.ops:814 new_value = op.expr.as_const(eval_ctx)815 result = _cmpop_to_func[op.op](value, new_value)816817 if not result:818 return False819820 value = new_value821 except Exception:822 raise Impossible()823824 return result825826827class Operand(Helper):828 """Holds an operator and an expression."""829830 fields = ("op", "expr")831832833if __debug__:834 Operand.__doc__ += "\nThe following operators are available: " + ", ".join(835 sorted(836 "``%s``" % x837 for x in set(_binop_to_func) | set(_uaop_to_func) | set(_cmpop_to_func)838 )839 )840841842class Mul(BinExpr):843 """Multiplies the left with the right node."""844845 operator = "*"846847848class Div(BinExpr):849 """Divides the left by the right node."""850851 operator = "/"852853854class FloorDiv(BinExpr):855 """Divides the left by the right node and truncates conver the856 result into an integer by truncating.857 """858859 operator = "//"860861862class Add(BinExpr):863 """Add the left to the right node."""864865 operator = "+"866867868class Sub(BinExpr):869 """Subtract the right from the left node."""870871 operator = "-"872873874class Mod(BinExpr):875 """Left modulo right."""876877 operator = "%"878879880class Pow(BinExpr):881 """Left to the power of right."""882883 operator = "**"884885886class And(BinExpr):887 """Short circuited AND."""888889 operator = "and"890891 def as_const(self, eval_ctx=None):892 eval_ctx = get_eval_context(self, eval_ctx)893 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)894895896class Or(BinExpr):897 """Short circuited OR."""898899 operator = "or"900901 def as_const(self, eval_ctx=None):902 eval_ctx = get_eval_context(self, eval_ctx)903 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)904905906class Not(UnaryExpr):907 """Negate the expression."""908909 operator = "not"910911912class Neg(UnaryExpr):913 """Make the expression negative."""914915 operator = "-"916917918class Pos(UnaryExpr):919 """Make the expression positive (noop for most expressions)"""920921 operator = "+"922923924# Helpers for extensions925926927class EnvironmentAttribute(Expr):928 """Loads an attribute from the environment object. This is useful for929 extensions that want to call a callback stored on the environment.930 """931932 fields = ("name",)933934935class ExtensionAttribute(Expr):936 """Returns the attribute of an extension bound to the environment.937 The identifier is the identifier of the :class:`Extension`.938939 This node is usually constructed by calling the940 :meth:`~jinja.ext.Extension.attr` method on an extension.941 """942943 fields = ("identifier", "name")944945946class ImportedName(Expr):947 """If created with an import name the import name is returned on node948 access. For example ``ImportedName('cgi.escape')`` returns the `escape`949 function from the cgi module on evaluation. Imports are optimized by the950 compiler so there is no need to assign them to local variables.951 """952953 fields = ("importname",)954955956class InternalName(Expr):957 """An internal name in the compiler. You cannot create these nodes958 yourself but the parser provides a959 :meth:`~jinja.parser.Parser.free_identifier` method that creates960 a new identifier for you. This identifier is not available from the961 template and is not threated specially by the compiler.962 """963964 fields = ("name",)965966 def __init__(self):967 raise TypeError(968 "Can't create internal names. Use the "969 "`free_identifier` method on a parser."970 )971972973class MarkSafe(Expr):974 """Mark the wrapped expression as safe (wrap it as `Markup`)."""975976 fields = ("expr",)977978 def as_const(self, eval_ctx=None):979 eval_ctx = get_eval_context(self, eval_ctx)980 return Markup(self.expr.as_const(eval_ctx))981982983class MarkSafeIfAutoescape(Expr):984 """Mark the wrapped expression as safe (wrap it as `Markup`) but985 only if autoescaping is active.986987 .. versionadded:: 2.5988 """989990 fields = ("expr",)991992 def as_const(self, eval_ctx=None):993 eval_ctx = get_eval_context(self, eval_ctx)994 if eval_ctx.volatile:995 raise Impossible()996 expr = self.expr.as_const(eval_ctx)997 if eval_ctx.autoescape:998 return Markup(expr)999 return expr100010011002class ContextReference(Expr):1003 """Returns the current template context. It can be used like a1004 :class:`Name` node, with a ``'load'`` ctx and will return the1005 current :class:`~jinja.runtime.Context` object.10061007 Here an example that assigns the current template name to a1008 variable named `foo`::10091010 Assign(Name('foo', ctx='store'),1011 Getattr(ContextReference(), 'name'))10121013 This is basically equivalent to using the1014 :func:`~jinja.contextfunction` decorator when using the1015 high-level API, which causes a reference to the context to be passed1016 as the first argument to a function.1017 """101810191020class DerivedContextReference(Expr):1021 """Return the current template context including locals. Behaves1022 exactly like :class:`ContextReference`, but includes local1023 variables, such as from a ``for`` loop.10241025 .. versionadded:: 2.111026 """102710281029class Continue(Stmt):1030 """Continue a loop."""103110321033class Break(Stmt):1034 """Break a loop."""103510361037class Scope(Stmt):1038 """An artificial scope."""10391040 fields = ("body",)104110421043class OverlayScope(Stmt):1044 """An overlay scope for extensions. This is a largely unoptimized scope1045 that however can be used to introduce completely arbitrary variables into1046 a sub scope from a dictionary or dictionary like object. The `context`1047 field has to evaluate to a dictionary object.10481049 Example usage::10501051 OverlayScope(context=self.call_method('get_context'),1052 body=[...])10531054 .. versionadded:: 2.101055 """10561057 fields = ("context", "body")105810591060class EvalContextModifier(Stmt):1061 """Modifies the eval context. For each option that should be modified,1062 a :class:`Keyword` has to be added to the :attr:`options` list.10631064 Example to change the `autoescape` setting::10651066 EvalContextModifier(options=[Keyword('autoescape', Const(True))])1067 """10681069 fields = ("options",)107010711072class ScopedEvalContextModifier(EvalContextModifier):1073 """Modifies the eval context and reverts it later. Works exactly like1074 :class:`EvalContextModifier` but will only modify the1075 :class:`~jinja.nodes.EvalContext` for nodes in the :attr:`body`.1076 """10771078 fields = ("body",)107910801081# make sure nobody creates custom nodes1082def _failing_new(*args, **kwargs):1083 raise TypeError("can't create custom node types")108410851086NodeType.__new__ = staticmethod(_failing_new)1087del _failing_new
added:src/jinja/optimizer.py+41 added
1# -*- coding: utf-8 -*-2"""The optimizer tries to constant fold expressions and modify the AST3in place so that it should be faster to evaluate.45Because the AST does not contain all the scoping information and the6compiler has to find that out, we cannot do all the optimizations we7want. For example, loop unrolling doesn't work because unrolled loops8would have a different scope. The solution would be a second syntax tree9that stored the scoping rules.10"""11from . import nodes12from .visitor import NodeTransformer131415def optimize(node, environment):16 """The context hint can be used to perform an static optimization17 based on the context given."""18 optimizer = Optimizer(environment)19 return optimizer.visit(node)202122class Optimizer(NodeTransformer):23 def __init__(self, environment):24 self.environment = environment2526 def generic_visit(self, node, *args, **kwargs):27 node = super(Optimizer, self).generic_visit(node, *args, **kwargs)2829 # Do constant folding. Some other nodes besides Expr have30 # as_const, but folding them causes errors later on.31 if isinstance(node, nodes.Expr):32 try:33 return nodes.Const.from_untrusted(34 node.as_const(args[0] if args else None),35 lineno=node.lineno,36 environment=self.environment,37 )38 except nodes.Impossible:39 pass4041 return node
added:src/jinja/parser.py+939 added
1# -*- coding: utf-8 -*-2"""Parse tokens from the lexer into nodes for the compiler."""3from . import nodes4from ._compat import imap5from .exceptions import TemplateAssertionError6from .exceptions import TemplateSyntaxError7from .lexer import describe_token8from .lexer import describe_token_expr910_statement_keywords = frozenset(11 [12 "for",13 "if",14 "block",15 "extends",16 "print",17 "macro",18 "include",19 "from",20 "import",21 "set",22 "with",23 "autoescape",24 ]25)26_compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])2728_math_nodes = {29 "add": nodes.Add,30 "sub": nodes.Sub,31 "mul": nodes.Mul,32 "div": nodes.Div,33 "floordiv": nodes.FloorDiv,34 "mod": nodes.Mod,35}363738class Parser(object):39 """This is the central parsing class Jinja uses. It's passed to40 extensions and can be used to parse expressions or statements.41 """4243 def __init__(self, environment, source, name=None, filename=None, state=None):44 self.environment = environment45 self.stream = environment._tokenize(source, name, filename, state)46 self.name = name47 self.filename = filename48 self.closed = False49 self.extensions = {}50 for extension in environment.iter_extensions():51 for tag in extension.tags:52 self.extensions[tag] = extension.parse53 self._last_identifier = 054 self._tag_stack = []55 self._end_token_stack = []5657 def fail(self, msg, lineno=None, exc=TemplateSyntaxError):58 """Convenience method that raises `exc` with the message, passed59 line number or last line number as well as the current name and60 filename.61 """62 if lineno is None:63 lineno = self.stream.current.lineno64 raise exc(msg, lineno, self.name, self.filename)6566 def _fail_ut_eof(self, name, end_token_stack, lineno):67 expected = []68 for exprs in end_token_stack:69 expected.extend(imap(describe_token_expr, exprs))70 if end_token_stack:71 currently_looking = " or ".join(72 "'%s'" % describe_token_expr(expr) for expr in end_token_stack[-1]73 )74 else:75 currently_looking = None7677 if name is None:78 message = ["Unexpected end of template."]79 else:80 message = ["Encountered unknown tag '%s'." % name]8182 if currently_looking:83 if name is not None and name in expected:84 message.append(85 "You probably made a nesting mistake. Jinja "86 "is expecting this tag, but currently looking "87 "for %s." % currently_looking88 )89 else:90 message.append(91 "Jinja was looking for the following tags: "92 "%s." % currently_looking93 )9495 if self._tag_stack:96 message.append(97 "The innermost block that needs to be "98 "closed is '%s'." % self._tag_stack[-1]99 )100101 self.fail(" ".join(message), lineno)102103 def fail_unknown_tag(self, name, lineno=None):104 """Called if the parser encounters an unknown tag. Tries to fail105 with a human readable error message that could help to identify106 the problem.107 """108 return self._fail_ut_eof(name, self._end_token_stack, lineno)109110 def fail_eof(self, end_tokens=None, lineno=None):111 """Like fail_unknown_tag but for end of template situations."""112 stack = list(self._end_token_stack)113 if end_tokens is not None:114 stack.append(end_tokens)115 return self._fail_ut_eof(None, stack, lineno)116117 def is_tuple_end(self, extra_end_rules=None):118 """Are we at the end of a tuple?"""119 if self.stream.current.type in ("variable_end", "block_end", "rparen"):120 return True121 elif extra_end_rules is not None:122 return self.stream.current.test_any(extra_end_rules)123 return False124125 def free_identifier(self, lineno=None):126 """Return a new free identifier as :class:`~jinja.nodes.InternalName`."""127 self._last_identifier += 1128 rv = object.__new__(nodes.InternalName)129 nodes.Node.__init__(rv, "fi%d" % self._last_identifier, lineno=lineno)130 return rv131132 def parse_statement(self):133 """Parse a single statement."""134 token = self.stream.current135 if token.type != "name":136 self.fail("tag name expected", token.lineno)137 self._tag_stack.append(token.value)138 pop_tag = True139 try:140 if token.value in _statement_keywords:141 return getattr(self, "parse_" + self.stream.current.value)()142 if token.value == "call":143 return self.parse_call_block()144 if token.value == "filter":145 return self.parse_filter_block()146 ext = self.extensions.get(token.value)147 if ext is not None:148 return ext(self)149150 # did not work out, remove the token we pushed by accident151 # from the stack so that the unknown tag fail function can152 # produce a proper error message.153 self._tag_stack.pop()154 pop_tag = False155 self.fail_unknown_tag(token.value, token.lineno)156 finally:157 if pop_tag:158 self._tag_stack.pop()159160 def parse_statements(self, end_tokens, drop_needle=False):161 """Parse multiple statements into a list until one of the end tokens162 is reached. This is used to parse the body of statements as it also163 parses template data if appropriate. The parser checks first if the164 current token is a colon and skips it if there is one. Then it checks165 for the block end and parses until if one of the `end_tokens` is166 reached. Per default the active token in the stream at the end of167 the call is the matched end token. If this is not wanted `drop_needle`168 can be set to `True` and the end token is removed.169 """170 # the first token may be a colon for python compatibility171 self.stream.skip_if("colon")172173 # in the future it would be possible to add whole code sections174 # by adding some sort of end of statement token and parsing those here.175 self.stream.expect("block_end")176 result = self.subparse(end_tokens)177178 # we reached the end of the template too early, the subparser179 # does not check for this, so we do that now180 if self.stream.current.type == "eof":181 self.fail_eof(end_tokens)182183 if drop_needle:184 next(self.stream)185 return result186187 def parse_set(self):188 """Parse an assign statement."""189 lineno = next(self.stream).lineno190 target = self.parse_assign_target(with_namespace=True)191 if self.stream.skip_if("assign"):192 expr = self.parse_tuple()193 return nodes.Assign(target, expr, lineno=lineno)194 filter_node = self.parse_filter(None)195 body = self.parse_statements(("name:endset",), drop_needle=True)196 return nodes.AssignBlock(target, filter_node, body, lineno=lineno)197198 def parse_for(self):199 """Parse a for loop."""200 lineno = self.stream.expect("name:for").lineno201 target = self.parse_assign_target(extra_end_rules=("name:in",))202 self.stream.expect("name:in")203 iter = self.parse_tuple(204 with_condexpr=False, extra_end_rules=("name:recursive",)205 )206 test = None207 if self.stream.skip_if("name:if"):208 test = self.parse_expression()209 recursive = self.stream.skip_if("name:recursive")210 body = self.parse_statements(("name:endfor", "name:else"))211 if next(self.stream).value == "endfor":212 else_ = []213 else:214 else_ = self.parse_statements(("name:endfor",), drop_needle=True)215 return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)216217 def parse_if(self):218 """Parse an if construct."""219 node = result = nodes.If(lineno=self.stream.expect("name:if").lineno)220 while 1:221 node.test = self.parse_tuple(with_condexpr=False)222 node.body = self.parse_statements(("name:elif", "name:else", "name:endif"))223 node.elif_ = []224 node.else_ = []225 token = next(self.stream)226 if token.test("name:elif"):227 node = nodes.If(lineno=self.stream.current.lineno)228 result.elif_.append(node)229 continue230 elif token.test("name:else"):231 result.else_ = self.parse_statements(("name:endif",), drop_needle=True)232 break233 return result234235 def parse_with(self):236 node = nodes.With(lineno=next(self.stream).lineno)237 targets = []238 values = []239 while self.stream.current.type != "block_end":240 if targets:241 self.stream.expect("comma")242 target = self.parse_assign_target()243 target.set_ctx("param")244 targets.append(target)245 self.stream.expect("assign")246 values.append(self.parse_expression())247 node.targets = targets248 node.values = values249 node.body = self.parse_statements(("name:endwith",), drop_needle=True)250 return node251252 def parse_autoescape(self):253 node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)254 node.options = [nodes.Keyword("autoescape", self.parse_expression())]255 node.body = self.parse_statements(("name:endautoescape",), drop_needle=True)256 return nodes.Scope([node])257258 def parse_block(self):259 node = nodes.Block(lineno=next(self.stream).lineno)260 node.name = self.stream.expect("name").value261 node.scoped = self.stream.skip_if("name:scoped")262263 # common problem people encounter when switching from django264 # to jinja. we do not support hyphens in block names, so let's265 # raise a nicer error message in that case.266 if self.stream.current.type == "sub":267 self.fail(268 "Block names in Jinja have to be valid Python "269 "identifiers and may not contain hyphens, use an "270 "underscore instead."271 )272273 node.body = self.parse_statements(("name:endblock",), drop_needle=True)274 self.stream.skip_if("name:" + node.name)275 return node276277 def parse_extends(self):278 node = nodes.Extends(lineno=next(self.stream).lineno)279 node.template = self.parse_expression()280 return node281282 def parse_import_context(self, node, default):283 if self.stream.current.test_any(284 "name:with", "name:without"285 ) and self.stream.look().test("name:context"):286 node.with_context = next(self.stream).value == "with"287 self.stream.skip()288 else:289 node.with_context = default290 return node291292 def parse_include(self):293 node = nodes.Include(lineno=next(self.stream).lineno)294 node.template = self.parse_expression()295 if self.stream.current.test("name:ignore") and self.stream.look().test(296 "name:missing"297 ):298 node.ignore_missing = True299 self.stream.skip(2)300 else:301 node.ignore_missing = False302 return self.parse_import_context(node, True)303304 def parse_import(self):305 node = nodes.Import(lineno=next(self.stream).lineno)306 node.template = self.parse_expression()307 self.stream.expect("name:as")308 node.target = self.parse_assign_target(name_only=True).name309 return self.parse_import_context(node, False)310311 def parse_from(self):312 node = nodes.FromImport(lineno=next(self.stream).lineno)313 node.template = self.parse_expression()314 self.stream.expect("name:import")315 node.names = []316317 def parse_context():318 if self.stream.current.value in (319 "with",320 "without",321 ) and self.stream.look().test("name:context"):322 node.with_context = next(self.stream).value == "with"323 self.stream.skip()324 return True325 return False326327 while 1:328 if node.names:329 self.stream.expect("comma")330 if self.stream.current.type == "name":331 if parse_context():332 break333 target = self.parse_assign_target(name_only=True)334 if target.name.startswith("_"):335 self.fail(336 "names starting with an underline can not be imported",337 target.lineno,338 exc=TemplateAssertionError,339 )340 if self.stream.skip_if("name:as"):341 alias = self.parse_assign_target(name_only=True)342 node.names.append((target.name, alias.name))343 else:344 node.names.append(target.name)345 if parse_context() or self.stream.current.type != "comma":346 break347 else:348 self.stream.expect("name")349 if not hasattr(node, "with_context"):350 node.with_context = False351 return node352353 def parse_signature(self, node):354 node.args = args = []355 node.defaults = defaults = []356 self.stream.expect("lparen")357 while self.stream.current.type != "rparen":358 if args:359 self.stream.expect("comma")360 arg = self.parse_assign_target(name_only=True)361 arg.set_ctx("param")362 if self.stream.skip_if("assign"):363 defaults.append(self.parse_expression())364 elif defaults:365 self.fail("non-default argument follows default argument")366 args.append(arg)367 self.stream.expect("rparen")368369 def parse_call_block(self):370 node = nodes.CallBlock(lineno=next(self.stream).lineno)371 if self.stream.current.type == "lparen":372 self.parse_signature(node)373 else:374 node.args = []375 node.defaults = []376377 node.call = self.parse_expression()378 if not isinstance(node.call, nodes.Call):379 self.fail("expected call", node.lineno)380 node.body = self.parse_statements(("name:endcall",), drop_needle=True)381 return node382383 def parse_filter_block(self):384 node = nodes.FilterBlock(lineno=next(self.stream).lineno)385 node.filter = self.parse_filter(None, start_inline=True)386 node.body = self.parse_statements(("name:endfilter",), drop_needle=True)387 return node388389 def parse_macro(self):390 node = nodes.Macro(lineno=next(self.stream).lineno)391 node.name = self.parse_assign_target(name_only=True).name392 self.parse_signature(node)393 node.body = self.parse_statements(("name:endmacro",), drop_needle=True)394 return node395396 def parse_print(self):397 node = nodes.Output(lineno=next(self.stream).lineno)398 node.nodes = []399 while self.stream.current.type != "block_end":400 if node.nodes:401 self.stream.expect("comma")402 node.nodes.append(self.parse_expression())403 return node404405 def parse_assign_target(406 self,407 with_tuple=True,408 name_only=False,409 extra_end_rules=None,410 with_namespace=False,411 ):412 """Parse an assignment target. As Jinja allows assignments to413 tuples, this function can parse all allowed assignment targets. Per414 default assignments to tuples are parsed, that can be disable however415 by setting `with_tuple` to `False`. If only assignments to names are416 wanted `name_only` can be set to `True`. The `extra_end_rules`417 parameter is forwarded to the tuple parsing function. If418 `with_namespace` is enabled, a namespace assignment may be parsed.419 """420 if with_namespace and self.stream.look().type == "dot":421 token = self.stream.expect("name")422 next(self.stream) # dot423 attr = self.stream.expect("name")424 target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)425 elif name_only:426 token = self.stream.expect("name")427 target = nodes.Name(token.value, "store", lineno=token.lineno)428 else:429 if with_tuple:430 target = self.parse_tuple(431 simplified=True, extra_end_rules=extra_end_rules432 )433 else:434 target = self.parse_primary()435 target.set_ctx("store")436 if not target.can_assign():437 self.fail(438 "can't assign to %r" % target.__class__.__name__.lower(), target.lineno439 )440 return target441442 def parse_expression(self, with_condexpr=True):443 """Parse an expression. Per default all expressions are parsed, if444 the optional `with_condexpr` parameter is set to `False` conditional445 expressions are not parsed.446 """447 if with_condexpr:448 return self.parse_condexpr()449 return self.parse_or()450451 def parse_condexpr(self):452 lineno = self.stream.current.lineno453 expr1 = self.parse_or()454 while self.stream.skip_if("name:if"):455 expr2 = self.parse_or()456 if self.stream.skip_if("name:else"):457 expr3 = self.parse_condexpr()458 else:459 expr3 = None460 expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)461 lineno = self.stream.current.lineno462 return expr1463464 def parse_or(self):465 lineno = self.stream.current.lineno466 left = self.parse_and()467 while self.stream.skip_if("name:or"):468 right = self.parse_and()469 left = nodes.Or(left, right, lineno=lineno)470 lineno = self.stream.current.lineno471 return left472473 def parse_and(self):474 lineno = self.stream.current.lineno475 left = self.parse_not()476 while self.stream.skip_if("name:and"):477 right = self.parse_not()478 left = nodes.And(left, right, lineno=lineno)479 lineno = self.stream.current.lineno480 return left481482 def parse_not(self):483 if self.stream.current.test("name:not"):484 lineno = next(self.stream).lineno485 return nodes.Not(self.parse_not(), lineno=lineno)486 return self.parse_compare()487488 def parse_compare(self):489 lineno = self.stream.current.lineno490 expr = self.parse_math1()491 ops = []492 while 1:493 token_type = self.stream.current.type494 if token_type in _compare_operators:495 next(self.stream)496 ops.append(nodes.Operand(token_type, self.parse_math1()))497 elif self.stream.skip_if("name:in"):498 ops.append(nodes.Operand("in", self.parse_math1()))499 elif self.stream.current.test("name:not") and self.stream.look().test(500 "name:in"501 ):502 self.stream.skip(2)503 ops.append(nodes.Operand("notin", self.parse_math1()))504 else:505 break506 lineno = self.stream.current.lineno507 if not ops:508 return expr509 return nodes.Compare(expr, ops, lineno=lineno)510511 def parse_math1(self):512 lineno = self.stream.current.lineno513 left = self.parse_concat()514 while self.stream.current.type in ("add", "sub"):515 cls = _math_nodes[self.stream.current.type]516 next(self.stream)517 right = self.parse_concat()518 left = cls(left, right, lineno=lineno)519 lineno = self.stream.current.lineno520 return left521522 def parse_concat(self):523 lineno = self.stream.current.lineno524 args = [self.parse_math2()]525 while self.stream.current.type == "tilde":526 next(self.stream)527 args.append(self.parse_math2())528 if len(args) == 1:529 return args[0]530 return nodes.Concat(args, lineno=lineno)531532 def parse_math2(self):533 lineno = self.stream.current.lineno534 left = self.parse_pow()535 while self.stream.current.type in ("mul", "div", "floordiv", "mod"):536 cls = _math_nodes[self.stream.current.type]537 next(self.stream)538 right = self.parse_pow()539 left = cls(left, right, lineno=lineno)540 lineno = self.stream.current.lineno541 return left542543 def parse_pow(self):544 lineno = self.stream.current.lineno545 left = self.parse_unary()546 while self.stream.current.type == "pow":547 next(self.stream)548 right = self.parse_unary()549 left = nodes.Pow(left, right, lineno=lineno)550 lineno = self.stream.current.lineno551 return left552553 def parse_unary(self, with_filter=True):554 token_type = self.stream.current.type555 lineno = self.stream.current.lineno556 if token_type == "sub":557 next(self.stream)558 node = nodes.Neg(self.parse_unary(False), lineno=lineno)559 elif token_type == "add":560 next(self.stream)561 node = nodes.Pos(self.parse_unary(False), lineno=lineno)562 else:563 node = self.parse_primary()564 node = self.parse_postfix(node)565 if with_filter:566 node = self.parse_filter_expr(node)567 return node568569 def parse_primary(self):570 token = self.stream.current571 if token.type == "name":572 if token.value in ("true", "false", "True", "False"):573 node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)574 elif token.value in ("none", "None"):575 node = nodes.Const(None, lineno=token.lineno)576 else:577 node = nodes.Name(token.value, "load", lineno=token.lineno)578 next(self.stream)579 elif token.type == "string":580 next(self.stream)581 buf = [token.value]582 lineno = token.lineno583 while self.stream.current.type == "string":584 buf.append(self.stream.current.value)585 next(self.stream)586 node = nodes.Const("".join(buf), lineno=lineno)587 elif token.type in ("integer", "float"):588 next(self.stream)589 node = nodes.Const(token.value, lineno=token.lineno)590 elif token.type == "lparen":591 next(self.stream)592 node = self.parse_tuple(explicit_parentheses=True)593 self.stream.expect("rparen")594 elif token.type == "lbracket":595 node = self.parse_list()596 elif token.type == "lbrace":597 node = self.parse_dict()598 else:599 self.fail("unexpected '%s'" % describe_token(token), token.lineno)600 return node601602 def parse_tuple(603 self,604 simplified=False,605 with_condexpr=True,606 extra_end_rules=None,607 explicit_parentheses=False,608 ):609 """Works like `parse_expression` but if multiple expressions are610 delimited by a comma a :class:`~jinja.nodes.Tuple` node is created.611 This method could also return a regular expression instead of a tuple612 if no commas where found.613614 The default parsing mode is a full tuple. If `simplified` is `True`615 only names and literals are parsed. The `no_condexpr` parameter is616 forwarded to :meth:`parse_expression`.617618 Because tuples do not require delimiters and may end in a bogus comma619 an extra hint is needed that marks the end of a tuple. For example620 for loops support tuples between `for` and `in`. In that case the621 `extra_end_rules` is set to ``['name:in']``.622623 `explicit_parentheses` is true if the parsing was triggered by an624 expression in parentheses. This is used to figure out if an empty625 tuple is a valid expression or not.626 """627 lineno = self.stream.current.lineno628 if simplified:629 parse = self.parse_primary630 elif with_condexpr:631 parse = self.parse_expression632 else:633634 def parse():635 return self.parse_expression(with_condexpr=False)636637 args = []638 is_tuple = False639 while 1:640 if args:641 self.stream.expect("comma")642 if self.is_tuple_end(extra_end_rules):643 break644 args.append(parse())645 if self.stream.current.type == "comma":646 is_tuple = True647 else:648 break649 lineno = self.stream.current.lineno650651 if not is_tuple:652 if args:653 return args[0]654655 # if we don't have explicit parentheses, an empty tuple is656 # not a valid expression. This would mean nothing (literally657 # nothing) in the spot of an expression would be an empty658 # tuple.659 if not explicit_parentheses:660 self.fail(661 "Expected an expression, got '%s'"662 % describe_token(self.stream.current)663 )664665 return nodes.Tuple(args, "load", lineno=lineno)666667 def parse_list(self):668 token = self.stream.expect("lbracket")669 items = []670 while self.stream.current.type != "rbracket":671 if items:672 self.stream.expect("comma")673 if self.stream.current.type == "rbracket":674 break675 items.append(self.parse_expression())676 self.stream.expect("rbracket")677 return nodes.List(items, lineno=token.lineno)678679 def parse_dict(self):680 token = self.stream.expect("lbrace")681 items = []682 while self.stream.current.type != "rbrace":683 if items:684 self.stream.expect("comma")685 if self.stream.current.type == "rbrace":686 break687 key = self.parse_expression()688 self.stream.expect("colon")689 value = self.parse_expression()690 items.append(nodes.Pair(key, value, lineno=key.lineno))691 self.stream.expect("rbrace")692 return nodes.Dict(items, lineno=token.lineno)693694 def parse_postfix(self, node):695 while 1:696 token_type = self.stream.current.type697 if token_type == "dot" or token_type == "lbracket":698 node = self.parse_subscript(node)699 # calls are valid both after postfix expressions (getattr700 # and getitem) as well as filters and tests701 elif token_type == "lparen":702 node = self.parse_call(node)703 else:704 break705 return node706707 def parse_filter_expr(self, node):708 while 1:709 token_type = self.stream.current.type710 if token_type == "pipe":711 node = self.parse_filter(node)712 elif token_type == "name" and self.stream.current.value == "is":713 node = self.parse_test(node)714 # calls are valid both after postfix expressions (getattr715 # and getitem) as well as filters and tests716 elif token_type == "lparen":717 node = self.parse_call(node)718 else:719 break720 return node721722 def parse_subscript(self, node):723 token = next(self.stream)724 if token.type == "dot":725 attr_token = self.stream.current726 next(self.stream)727 if attr_token.type == "name":728 return nodes.Getattr(729 node, attr_token.value, "load", lineno=token.lineno730 )731 elif attr_token.type != "integer":732 self.fail("expected name or number", attr_token.lineno)733 arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)734 return nodes.Getitem(node, arg, "load", lineno=token.lineno)735 if token.type == "lbracket":736 args = []737 while self.stream.current.type != "rbracket":738 if args:739 self.stream.expect("comma")740 args.append(self.parse_subscribed())741 self.stream.expect("rbracket")742 if len(args) == 1:743 arg = args[0]744 else:745 arg = nodes.Tuple(args, "load", lineno=token.lineno)746 return nodes.Getitem(node, arg, "load", lineno=token.lineno)747 self.fail("expected subscript expression", token.lineno)748749 def parse_subscribed(self):750 lineno = self.stream.current.lineno751752 if self.stream.current.type == "colon":753 next(self.stream)754 args = [None]755 else:756 node = self.parse_expression()757 if self.stream.current.type != "colon":758 return node759 next(self.stream)760 args = [node]761762 if self.stream.current.type == "colon":763 args.append(None)764 elif self.stream.current.type not in ("rbracket", "comma"):765 args.append(self.parse_expression())766 else:767 args.append(None)768769 if self.stream.current.type == "colon":770 next(self.stream)771 if self.stream.current.type not in ("rbracket", "comma"):772 args.append(self.parse_expression())773 else:774 args.append(None)775 else:776 args.append(None)777778 return nodes.Slice(lineno=lineno, *args)779780 def parse_call(self, node):781 token = self.stream.expect("lparen")782 args = []783 kwargs = []784 dyn_args = dyn_kwargs = None785 require_comma = False786787 def ensure(expr):788 if not expr:789 self.fail("invalid syntax for function call expression", token.lineno)790791 while self.stream.current.type != "rparen":792 if require_comma:793 self.stream.expect("comma")794 # support for trailing comma795 if self.stream.current.type == "rparen":796 break797 if self.stream.current.type == "mul":798 ensure(dyn_args is None and dyn_kwargs is None)799 next(self.stream)800 dyn_args = self.parse_expression()801 elif self.stream.current.type == "pow":802 ensure(dyn_kwargs is None)803 next(self.stream)804 dyn_kwargs = self.parse_expression()805 else:806 if (807 self.stream.current.type == "name"808 and self.stream.look().type == "assign"809 ):810 # Parsing a kwarg811 ensure(dyn_kwargs is None)812 key = self.stream.current.value813 self.stream.skip(2)814 value = self.parse_expression()815 kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))816 else:817 # Parsing an arg818 ensure(dyn_args is None and dyn_kwargs is None and not kwargs)819 args.append(self.parse_expression())820821 require_comma = True822 self.stream.expect("rparen")823824 if node is None:825 return args, kwargs, dyn_args, dyn_kwargs826 return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)827828 def parse_filter(self, node, start_inline=False):829 while self.stream.current.type == "pipe" or start_inline:830 if not start_inline:831 next(self.stream)832 token = self.stream.expect("name")833 name = token.value834 while self.stream.current.type == "dot":835 next(self.stream)836 name += "." + self.stream.expect("name").value837 if self.stream.current.type == "lparen":838 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)839 else:840 args = []841 kwargs = []842 dyn_args = dyn_kwargs = None843 node = nodes.Filter(844 node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno845 )846 start_inline = False847 return node848849 def parse_test(self, node):850 token = next(self.stream)851 if self.stream.current.test("name:not"):852 next(self.stream)853 negated = True854 else:855 negated = False856 name = self.stream.expect("name").value857 while self.stream.current.type == "dot":858 next(self.stream)859 name += "." + self.stream.expect("name").value860 dyn_args = dyn_kwargs = None861 kwargs = []862 if self.stream.current.type == "lparen":863 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)864 elif self.stream.current.type in (865 "name",866 "string",867 "integer",868 "float",869 "lparen",870 "lbracket",871 "lbrace",872 ) and not self.stream.current.test_any("name:else", "name:or", "name:and"):873 if self.stream.current.test("name:is"):874 self.fail("You cannot chain multiple tests with is")875 arg_node = self.parse_primary()876 arg_node = self.parse_postfix(arg_node)877 args = [arg_node]878 else:879 args = []880 node = nodes.Test(881 node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno882 )883 if negated:884 node = nodes.Not(node, lineno=token.lineno)885 return node886887 def subparse(self, end_tokens=None):888 body = []889 data_buffer = []890 add_data = data_buffer.append891892 if end_tokens is not None:893 self._end_token_stack.append(end_tokens)894895 def flush_data():896 if data_buffer:897 lineno = data_buffer[0].lineno898 body.append(nodes.Output(data_buffer[:], lineno=lineno))899 del data_buffer[:]900901 try:902 while self.stream:903 token = self.stream.current904 if token.type == "data":905 if token.value:906 add_data(nodes.TemplateData(token.value, lineno=token.lineno))907 next(self.stream)908 elif token.type == "variable_begin":909 next(self.stream)910 add_data(self.parse_tuple(with_condexpr=True))911 self.stream.expect("variable_end")912 elif token.type == "block_begin":913 flush_data()914 next(self.stream)915 if end_tokens is not None and self.stream.current.test_any(916 *end_tokens917 ):918 return body919 rv = self.parse_statement()920 if isinstance(rv, list):921 body.extend(rv)922 else:923 body.append(rv)924 self.stream.expect("block_end")925 else:926 raise AssertionError("internal parsing error")927928 flush_data()929 finally:930 if end_tokens is not None:931 self._end_token_stack.pop()932933 return body934935 def parse(self):936 """Parse the whole template into a `Template` node."""937 result = nodes.Template(self.subparse(), lineno=1)938 result.set_environment(self.environment)939 return result
added:src/jinja/runtime.py+1011 added
1# -*- coding: utf-8 -*-2"""The runtime functions and state used by compiled templates."""3import sys4from itertools import chain5from types import MethodType67from markupsafe import escape # noqa: F4018from markupsafe import Markup9from markupsafe import soft_unicode1011from ._compat import abc12from ._compat import imap13from ._compat import implements_iterator14from ._compat import implements_to_string15from ._compat import iteritems16from ._compat import PY217from ._compat import string_types18from ._compat import text_type19from ._compat import with_metaclass20from .exceptions import TemplateNotFound # noqa: F40121from .exceptions import TemplateRuntimeError # noqa: F40122from .exceptions import UndefinedError23from .nodes import EvalContext24from .utils import concat25from .utils import evalcontextfunction26from .utils import internalcode27from .utils import missing28from .utils import Namespace # noqa: F40129from .utils import object_type_repr3031# these variables are exported to the template runtime32exported = [33 "LoopContext",34 "TemplateReference",35 "Macro",36 "Markup",37 "TemplateRuntimeError",38 "missing",39 "concat",40 "escape",41 "markup_join",42 "unicode_join",43 "to_string",44 "identity",45 "TemplateNotFound",46 "Namespace",47 "Undefined",48]4950#: the name of the function that is used to convert something into51#: a string. We can just use the text type here.52to_string = text_type535455def identity(x):56 """Returns its argument. Useful for certain things in the57 environment.58 """59 return x606162def markup_join(seq):63 """Concatenation that escapes if necessary and converts to unicode."""64 buf = []65 iterator = imap(soft_unicode, seq)66 for arg in iterator:67 buf.append(arg)68 if hasattr(arg, "__html__"):69 return Markup(u"").join(chain(buf, iterator))70 return concat(buf)717273def unicode_join(seq):74 """Simple args to unicode conversion and concatenation."""75 return concat(imap(text_type, seq))767778def new_context(79 environment,80 template_name,81 blocks,82 vars=None,83 shared=None,84 globals=None,85 locals=None,86):87 """Internal helper for context creation."""88 if vars is None:89 vars = {}90 if shared:91 parent = vars92 else:93 parent = dict(globals or (), **vars)94 if locals:95 # if the parent is shared a copy should be created because96 # we don't want to modify the dict passed97 if shared:98 parent = dict(parent)99 for key, value in iteritems(locals):100 if value is not missing:101 parent[key] = value102 return environment.context_class(environment, parent, template_name, blocks)103104105class TemplateReference(object):106 """The `self` in templates."""107108 def __init__(self, context):109 self.__context = context110111 def __getitem__(self, name):112 blocks = self.__context.blocks[name]113 return BlockReference(name, self.__context, blocks, 0)114115 def __repr__(self):116 return "<%s %r>" % (self.__class__.__name__, self.__context.name)117118119def _get_func(x):120 return getattr(x, "__func__", x)121122123class ContextMeta(type):124 def __new__(mcs, name, bases, d):125 rv = type.__new__(mcs, name, bases, d)126 if bases == ():127 return rv128129 resolve = _get_func(rv.resolve)130 default_resolve = _get_func(Context.resolve)131 resolve_or_missing = _get_func(rv.resolve_or_missing)132 default_resolve_or_missing = _get_func(Context.resolve_or_missing)133134 # If we have a changed resolve but no changed default or missing135 # resolve we invert the call logic.136 if (137 resolve is not default_resolve138 and resolve_or_missing is default_resolve_or_missing139 ):140 rv._legacy_resolve_mode = True141 elif (142 resolve is default_resolve143 and resolve_or_missing is default_resolve_or_missing144 ):145 rv._fast_resolve_mode = True146147 return rv148149150def resolve_or_missing(context, key, missing=missing):151 if key in context.vars:152 return context.vars[key]153 if key in context.parent:154 return context.parent[key]155 return missing156157158class Context(with_metaclass(ContextMeta)):159 """The template context holds the variables of a template. It stores the160 values passed to the template and also the names the template exports.161 Creating instances is neither supported nor useful as it's created162 automatically at various stages of the template evaluation and should not163 be created by hand.164165 The context is immutable. Modifications on :attr:`parent` **must not**166 happen and modifications on :attr:`vars` are allowed from generated167 template code only. Template filters and global functions marked as168 :func:`contextfunction`\\s get the active context passed as first argument169 and are allowed to access the context read-only.170171 The template context supports read only dict operations (`get`,172 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,173 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`174 method that doesn't fail with a `KeyError` but returns an175 :class:`Undefined` object for missing variables.176 """177178 # XXX: we want to eventually make this be a deprecation warning and179 # remove it.180 _legacy_resolve_mode = False181 _fast_resolve_mode = False182183 def __init__(self, environment, parent, name, blocks):184 self.parent = parent185 self.vars = {}186 self.environment = environment187 self.eval_ctx = EvalContext(self.environment, name)188 self.exported_vars = set()189 self.name = name190191 # create the initial mapping of blocks. Whenever template inheritance192 # takes place the runtime will update this mapping with the new blocks193 # from the template.194 self.blocks = dict((k, [v]) for k, v in iteritems(blocks))195196 # In case we detect the fast resolve mode we can set up an alias197 # here that bypasses the legacy code logic.198 if self._fast_resolve_mode:199 self.resolve_or_missing = MethodType(resolve_or_missing, self)200201 def super(self, name, current):202 """Render a parent block."""203 try:204 blocks = self.blocks[name]205 index = blocks.index(current) + 1206 blocks[index]207 except LookupError:208 return self.environment.undefined(209 "there is no parent block called %r." % name, name="super"210 )211 return BlockReference(name, self, blocks, index)212213 def get(self, key, default=None):214 """Returns an item from the template context, if it doesn't exist215 `default` is returned.216 """217 try:218 return self[key]219 except KeyError:220 return default221222 def resolve(self, key):223 """Looks up a variable like `__getitem__` or `get` but returns an224 :class:`Undefined` object with the name of the name looked up.225 """226 if self._legacy_resolve_mode:227 rv = resolve_or_missing(self, key)228 else:229 rv = self.resolve_or_missing(key)230 if rv is missing:231 return self.environment.undefined(name=key)232 return rv233234 def resolve_or_missing(self, key):235 """Resolves a variable like :meth:`resolve` but returns the236 special `missing` value if it cannot be found.237 """238 if self._legacy_resolve_mode:239 rv = self.resolve(key)240 if isinstance(rv, Undefined):241 rv = missing242 return rv243 return resolve_or_missing(self, key)244245 def get_exported(self):246 """Get a new dict with the exported variables."""247 return dict((k, self.vars[k]) for k in self.exported_vars)248249 def get_all(self):250 """Return the complete context as dict including the exported251 variables. For optimizations reasons this might not return an252 actual copy so be careful with using it.253 """254 if not self.vars:255 return self.parent256 if not self.parent:257 return self.vars258 return dict(self.parent, **self.vars)259260 @internalcode261 def call(__self, __obj, *args, **kwargs): # noqa: B902262 """Call the callable with the arguments and keyword arguments263 provided but inject the active context or environment as first264 argument if the callable is a :func:`contextfunction` or265 :func:`environmentfunction`.266 """267 if __debug__:268 __traceback_hide__ = True # noqa269270 # Allow callable classes to take a context271 if hasattr(__obj, "__call__"): # noqa: B004272 fn = __obj.__call__273 for fn_type in (274 "contextfunction",275 "evalcontextfunction",276 "environmentfunction",277 ):278 if hasattr(fn, fn_type):279 __obj = fn280 break281282 if callable(__obj):283 if getattr(__obj, "contextfunction", 0):284 args = (__self,) + args285 elif getattr(__obj, "evalcontextfunction", 0):286 args = (__self.eval_ctx,) + args287 elif getattr(__obj, "environmentfunction", 0):288 args = (__self.environment,) + args289 try:290 return __obj(*args, **kwargs)291 except StopIteration:292 return __self.environment.undefined(293 "value was undefined because "294 "a callable raised a "295 "StopIteration exception"296 )297298 def derived(self, locals=None):299 """Internal helper function to create a derived context. This is300 used in situations where the system needs a new context in the same301 template that is independent.302 """303 context = new_context(304 self.environment, self.name, {}, self.get_all(), True, None, locals305 )306 context.eval_ctx = self.eval_ctx307 context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))308 return context309310 def _all(meth): # noqa: B902311 def proxy(self):312 return getattr(self.get_all(), meth)()313314 proxy.__doc__ = getattr(dict, meth).__doc__315 proxy.__name__ = meth316 return proxy317318 keys = _all("keys")319 values = _all("values")320 items = _all("items")321322 # not available on python 3323 if PY2:324 iterkeys = _all("iterkeys")325 itervalues = _all("itervalues")326 iteritems = _all("iteritems")327 del _all328329 def __contains__(self, name):330 return name in self.vars or name in self.parent331332 def __getitem__(self, key):333 """Lookup a variable or raise `KeyError` if the variable is334 undefined.335 """336 item = self.resolve_or_missing(key)337 if item is missing:338 raise KeyError(key)339 return item340341 def __repr__(self):342 return "<%s %s of %r>" % (343 self.__class__.__name__,344 repr(self.get_all()),345 self.name,346 )347348349abc.Mapping.register(Context)350351352class BlockReference(object):353 """One block on a template reference."""354355 def __init__(self, name, context, stack, depth):356 self.name = name357 self._context = context358 self._stack = stack359 self._depth = depth360361 @property362 def super(self):363 """Super the block."""364 if self._depth + 1 >= len(self._stack):365 return self._context.environment.undefined(366 "there is no parent block called %r." % self.name, name="super"367 )368 return BlockReference(self.name, self._context, self._stack, self._depth + 1)369370 @internalcode371 def __call__(self):372 rv = concat(self._stack[self._depth](self._context))373 if self._context.eval_ctx.autoescape:374 rv = Markup(rv)375 return rv376377378@implements_iterator379class LoopContext:380 """A wrapper iterable for dynamic ``for`` loops, with information381 about the loop and iteration.382 """383384 #: Current iteration of the loop, starting at 0.385 index0 = -1386387 _length = None388 _after = missing389 _current = missing390 _before = missing391 _last_changed_value = missing392393 def __init__(self, iterable, undefined, recurse=None, depth0=0):394 """395 :param iterable: Iterable to wrap.396 :param undefined: :class:`Undefined` class to use for next and397 previous items.398 :param recurse: The function to render the loop body when the399 loop is marked recursive.400 :param depth0: Incremented when looping recursively.401 """402 self._iterable = iterable403 self._iterator = self._to_iterator(iterable)404 self._undefined = undefined405 self._recurse = recurse406 #: How many levels deep a recursive loop currently is, starting at 0.407 self.depth0 = depth0408409 @staticmethod410 def _to_iterator(iterable):411 return iter(iterable)412413 @property414 def length(self):415 """Length of the iterable.416417 If the iterable is a generator or otherwise does not have a418 size, it is eagerly evaluated to get a size.419 """420 if self._length is not None:421 return self._length422423 try:424 self._length = len(self._iterable)425 except TypeError:426 iterable = list(self._iterator)427 self._iterator = self._to_iterator(iterable)428 self._length = len(iterable) + self.index + (self._after is not missing)429430 return self._length431432 def __len__(self):433 return self.length434435 @property436 def depth(self):437 """How many levels deep a recursive loop currently is, starting at 1."""438 return self.depth0 + 1439440 @property441 def index(self):442 """Current iteration of the loop, starting at 1."""443 return self.index0 + 1444445 @property446 def revindex0(self):447 """Number of iterations from the end of the loop, ending at 0.448449 Requires calculating :attr:`length`.450 """451 return self.length - self.index452453 @property454 def revindex(self):455 """Number of iterations from the end of the loop, ending at 1.456457 Requires calculating :attr:`length`.458 """459 return self.length - self.index0460461 @property462 def first(self):463 """Whether this is the first iteration of the loop."""464 return self.index0 == 0465466 def _peek_next(self):467 """Return the next element in the iterable, or :data:`missing`468 if the iterable is exhausted. Only peeks one item ahead, caching469 the result in :attr:`_last` for use in subsequent checks. The470 cache is reset when :meth:`__next__` is called.471 """472 if self._after is not missing:473 return self._after474475 self._after = next(self._iterator, missing)476 return self._after477478 @property479 def last(self):480 """Whether this is the last iteration of the loop.481482 Causes the iterable to advance early. See483 :func:`itertools.groupby` for issues this can cause.484 The :func:`groupby` filter avoids that issue.485 """486 return self._peek_next() is missing487488 @property489 def previtem(self):490 """The item in the previous iteration. Undefined during the491 first iteration.492 """493 if self.first:494 return self._undefined("there is no previous item")495496 return self._before497498 @property499 def nextitem(self):500 """The item in the next iteration. Undefined during the last501 iteration.502503 Causes the iterable to advance early. See504 :func:`itertools.groupby` for issues this can cause.505 The :func:`groupby` filter avoids that issue.506 """507 rv = self._peek_next()508509 if rv is missing:510 return self._undefined("there is no next item")511512 return rv513514 def cycle(self, *args):515 """Return a value from the given args, cycling through based on516 the current :attr:`index0`.517518 :param args: One or more values to cycle through.519 """520 if not args:521 raise TypeError("no items for cycling given")522523 return args[self.index0 % len(args)]524525 def changed(self, *value):526 """Return ``True`` if previously called with a different value527 (including when called for the first time).528529 :param value: One or more values to compare to the last call.530 """531 if self._last_changed_value != value:532 self._last_changed_value = value533 return True534535 return False536537 def __iter__(self):538 return self539540 def __next__(self):541 if self._after is not missing:542 rv = self._after543 self._after = missing544 else:545 rv = next(self._iterator)546547 self.index0 += 1548 self._before = self._current549 self._current = rv550 return rv, self551552 @internalcode553 def __call__(self, iterable):554 """When iterating over nested data, render the body of the loop555 recursively with the given inner iterable data.556557 The loop must have the ``recursive`` marker for this to work.558 """559 if self._recurse is None:560 raise TypeError(561 "The loop must have the 'recursive' marker to be called recursively."562 )563564 return self._recurse(iterable, self._recurse, depth=self.depth)565566 def __repr__(self):567 return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)568569570class Macro(object):571 """Wraps a macro function."""572573 def __init__(574 self,575 environment,576 func,577 name,578 arguments,579 catch_kwargs,580 catch_varargs,581 caller,582 default_autoescape=None,583 ):584 self._environment = environment585 self._func = func586 self._argument_count = len(arguments)587 self.name = name588 self.arguments = arguments589 self.catch_kwargs = catch_kwargs590 self.catch_varargs = catch_varargs591 self.caller = caller592 self.explicit_caller = "caller" in arguments593 if default_autoescape is None:594 default_autoescape = environment.autoescape595 self._default_autoescape = default_autoescape596597 @internalcode598 @evalcontextfunction599 def __call__(self, *args, **kwargs):600 # This requires a bit of explanation, In the past we used to601 # decide largely based on compile-time information if a macro is602 # safe or unsafe. While there was a volatile mode it was largely603 # unused for deciding on escaping. This turns out to be604 # problematic for macros because whether a macro is safe depends not605 # on the escape mode when it was defined, but rather when it was used.606 #607 # Because however we export macros from the module system and608 # there are historic callers that do not pass an eval context (and609 # will continue to not pass one), we need to perform an instance610 # check here.611 #612 # This is considered safe because an eval context is not a valid613 # argument to callables otherwise anyway. Worst case here is614 # that if no eval context is passed we fall back to the compile615 # time autoescape flag.616 if args and isinstance(args[0], EvalContext):617 autoescape = args[0].autoescape618 args = args[1:]619 else:620 autoescape = self._default_autoescape621622 # try to consume the positional arguments623 arguments = list(args[: self._argument_count])624 off = len(arguments)625626 # For information why this is necessary refer to the handling627 # of caller in the `macro_body` handler in the compiler.628 found_caller = False629630 # if the number of arguments consumed is not the number of631 # arguments expected we start filling in keyword arguments632 # and defaults.633 if off != self._argument_count:634 for name in self.arguments[len(arguments) :]:635 try:636 value = kwargs.pop(name)637 except KeyError:638 value = missing639 if name == "caller":640 found_caller = True641 arguments.append(value)642 else:643 found_caller = self.explicit_caller644645 # it's important that the order of these arguments does not change646 # if not also changed in the compiler's `function_scoping` method.647 # the order is caller, keyword arguments, positional arguments!648 if self.caller and not found_caller:649 caller = kwargs.pop("caller", None)650 if caller is None:651 caller = self._environment.undefined("No caller defined", name="caller")652 arguments.append(caller)653654 if self.catch_kwargs:655 arguments.append(kwargs)656 elif kwargs:657 if "caller" in kwargs:658 raise TypeError(659 "macro %r was invoked with two values for "660 "the special caller argument. This is "661 "most likely a bug." % self.name662 )663 raise TypeError(664 "macro %r takes no keyword argument %r"665 % (self.name, next(iter(kwargs)))666 )667 if self.catch_varargs:668 arguments.append(args[self._argument_count :])669 elif len(args) > self._argument_count:670 raise TypeError(671 "macro %r takes not more than %d argument(s)"672 % (self.name, len(self.arguments))673 )674675 return self._invoke(arguments, autoescape)676677 def _invoke(self, arguments, autoescape):678 """This method is being swapped out by the async implementation."""679 rv = self._func(*arguments)680 if autoescape:681 rv = Markup(rv)682 return rv683684 def __repr__(self):685 return "<%s %s>" % (686 self.__class__.__name__,687 self.name is None and "anonymous" or repr(self.name),688 )689690691@implements_to_string692class Undefined(object):693 """The default undefined type. This undefined type can be printed and694 iterated over, but every other access will raise an :exc:`UndefinedError`:695696 >>> foo = Undefined(name='foo')697 >>> str(foo)698 ''699 >>> not foo700 True701 >>> foo + 42702 Traceback (most recent call last):703 ...704 jinja.exceptions.UndefinedError: 'foo' is undefined705 """706707 __slots__ = (708 "_undefined_hint",709 "_undefined_obj",710 "_undefined_name",711 "_undefined_exception",712 )713714 def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):715 self._undefined_hint = hint716 self._undefined_obj = obj717 self._undefined_name = name718 self._undefined_exception = exc719720 @property721 def _undefined_message(self):722 """Build a message about the undefined value based on how it was723 accessed.724 """725 if self._undefined_hint:726 return self._undefined_hint727728 if self._undefined_obj is missing:729 return "%r is undefined" % self._undefined_name730731 if not isinstance(self._undefined_name, string_types):732 return "%s has no element %r" % (733 object_type_repr(self._undefined_obj),734 self._undefined_name,735 )736737 return "%r has no attribute %r" % (738 object_type_repr(self._undefined_obj),739 self._undefined_name,740 )741742 @internalcode743 def _fail_with_undefined_error(self, *args, **kwargs):744 """Raise an :exc:`UndefinedError` when operations are performed745 on the undefined value.746 """747 raise self._undefined_exception(self._undefined_message)748749 @internalcode750 def __getattr__(self, name):751 if name[:2] == "__":752 raise AttributeError(name)753 return self._fail_with_undefined_error()754755 __add__ = (756 __radd__757 ) = (758 __mul__759 ) = (760 __rmul__761 ) = (762 __div__763 ) = (764 __rdiv__765 ) = (766 __truediv__767 ) = (768 __rtruediv__769 ) = (770 __floordiv__771 ) = (772 __rfloordiv__773 ) = (774 __mod__775 ) = (776 __rmod__777 ) = (778 __pos__779 ) = (780 __neg__781 ) = (782 __call__783 ) = (784 __getitem__785 ) = (786 __lt__787 ) = (788 __le__789 ) = (790 __gt__791 ) = (792 __ge__793 ) = (794 __int__795 ) = (796 __float__797 ) = (798 __complex__799 ) = __pow__ = __rpow__ = __sub__ = __rsub__ = _fail_with_undefined_error800801 def __eq__(self, other):802 return type(self) is type(other)803804 def __ne__(self, other):805 return not self.__eq__(other)806807 def __hash__(self):808 return id(type(self))809810 def __str__(self):811 return u""812813 def __len__(self):814 return 0815816 def __iter__(self):817 if 0:818 yield None819820 def __nonzero__(self):821 return False822823 __bool__ = __nonzero__824825 def __repr__(self):826 return "Undefined"827828829def make_logging_undefined(logger=None, base=None):830 """Given a logger object this returns a new undefined class that will831 log certain failures. It will log iterations and printing. If no832 logger is given a default logger is created.833834 Example::835836 logger = logging.getLogger(__name__)837 LoggingUndefined = make_logging_undefined(838 logger=logger,839 base=Undefined840 )841842 .. versionadded:: 2.8843844 :param logger: the logger to use. If not provided, a default logger845 is created.846 :param base: the base class to add logging functionality to. This847 defaults to :class:`Undefined`.848 """849 if logger is None:850 import logging851852 logger = logging.getLogger(__name__)853 logger.addHandler(logging.StreamHandler(sys.stderr))854 if base is None:855 base = Undefined856857 def _log_message(undef):858 if undef._undefined_hint is None:859 if undef._undefined_obj is missing:860 hint = "%s is undefined" % undef._undefined_name861 elif not isinstance(undef._undefined_name, string_types):862 hint = "%s has no element %s" % (863 object_type_repr(undef._undefined_obj),864 undef._undefined_name,865 )866 else:867 hint = "%s has no attribute %s" % (868 object_type_repr(undef._undefined_obj),869 undef._undefined_name,870 )871 else:872 hint = undef._undefined_hint873 logger.warning("Template variable warning: %s", hint)874875 class LoggingUndefined(base):876 def _fail_with_undefined_error(self, *args, **kwargs):877 try:878 return base._fail_with_undefined_error(self, *args, **kwargs)879 except self._undefined_exception as e:880 logger.error("Template variable error: %s", str(e))881 raise e882883 def __str__(self):884 rv = base.__str__(self)885 _log_message(self)886 return rv887888 def __iter__(self):889 rv = base.__iter__(self)890 _log_message(self)891 return rv892893 if PY2:894895 def __nonzero__(self):896 rv = base.__nonzero__(self)897 _log_message(self)898 return rv899900 def __unicode__(self):901 rv = base.__unicode__(self)902 _log_message(self)903 return rv904905 else:906907 def __bool__(self):908 rv = base.__bool__(self)909 _log_message(self)910 return rv911912 return LoggingUndefined913914915# No @implements_to_string decorator here because __str__916# is not overwritten from Undefined in this class.917# This would cause a recursion error in Python 2.918class ChainableUndefined(Undefined):919 """An undefined that is chainable, where both ``__getattr__`` and920 ``__getitem__`` return itself rather than raising an921 :exc:`UndefinedError`.922923 >>> foo = ChainableUndefined(name='foo')924 >>> str(foo.bar['baz'])925 ''926 >>> foo.bar['baz'] + 42927 Traceback (most recent call last):928 ...929 jinja.exceptions.UndefinedError: 'foo' is undefined930931 .. versionadded:: 2.11.0932 """933934 __slots__ = ()935936 def __html__(self):937 return self.__str__()938939 def __getattr__(self, _):940 return self941942 __getitem__ = __getattr__943944945@implements_to_string946class DebugUndefined(Undefined):947 """An undefined that returns the debug info when printed.948949 >>> foo = DebugUndefined(name='foo')950 >>> str(foo)951 '{{ foo }}'952 >>> not foo953 True954 >>> foo + 42955 Traceback (most recent call last):956 ...957 jinja.exceptions.UndefinedError: 'foo' is undefined958 """959960 __slots__ = ()961962 def __str__(self):963 if self._undefined_hint is None:964 if self._undefined_obj is missing:965 return u"{{ %s }}" % self._undefined_name966 return "{{ no such element: %s[%r] }}" % (967 object_type_repr(self._undefined_obj),968 self._undefined_name,969 )970 return u"{{ undefined value printed: %s }}" % self._undefined_hint971972973@implements_to_string974class StrictUndefined(Undefined):975 """An undefined that barks on print and iteration as well as boolean976 tests and all kinds of comparisons. In other words: you can do nothing977 with it except checking if it's defined using the `defined` test.978979 >>> foo = StrictUndefined(name='foo')980 >>> str(foo)981 Traceback (most recent call last):982 ...983 jinja.exceptions.UndefinedError: 'foo' is undefined984 >>> not foo985 Traceback (most recent call last):986 ...987 jinja.exceptions.UndefinedError: 'foo' is undefined988 >>> foo + 42989 Traceback (most recent call last):990 ...991 jinja.exceptions.UndefinedError: 'foo' is undefined992 """993994 __slots__ = ()995 __iter__ = (996 __str__997 ) = (998 __len__999 ) = (1000 __nonzero__1001 ) = __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error100210031004# remove remaining slots attributes, after the metaclass did the magic they1005# are unneeded and irritating as they contain wrong data for the subclasses.1006del (1007 Undefined.__slots__,1008 ChainableUndefined.__slots__,1009 DebugUndefined.__slots__,1010 StrictUndefined.__slots__,1011)
added:src/jinja/sandbox.py+510 added
1# -*- coding: utf-8 -*-2"""A sandbox layer that ensures unsafe operations cannot be performed.3Useful when the template itself comes from an untrusted source.4"""5import operator6import types7import warnings8from collections import deque9from string import Formatter1011from markupsafe import EscapeFormatter1213from ._compat import abc14from ._compat import PY215from ._compat import range_type16from ._compat import string_types17from .environment import Environment18from .exceptions import SecurityError19from .utils import Markup2021#: maximum number of items a range may produce22MAX_RANGE = 1000002324#: attributes of function objects that are considered unsafe.25if PY2:26 UNSAFE_FUNCTION_ATTRIBUTES = {27 "func_closure",28 "func_code",29 "func_dict",30 "func_defaults",31 "func_globals",32 }33else:34 # On versions > python 2 the special attributes on functions are gone,35 # but they remain on methods and generators for whatever reason.36 UNSAFE_FUNCTION_ATTRIBUTES = set()3738#: unsafe method attributes. function attributes are unsafe for methods too39UNSAFE_METHOD_ATTRIBUTES = {"im_class", "im_func", "im_self"}4041#: unsafe generator attributes.42UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}4344#: unsafe attributes on coroutines45UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}4647#: unsafe attributes on async generators48UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}4950# make sure we don't warn in python 2.6 about stuff we don't care about51warnings.filterwarnings(52 "ignore", "the sets module", DeprecationWarning, module=__name__53)5455_mutable_set_types = (set,)56_mutable_mapping_types = (dict,)57_mutable_sequence_types = (list,)5859# on python 2.x we can register the user collection types60try:61 from UserDict import UserDict, DictMixin62 from UserList import UserList6364 _mutable_mapping_types += (UserDict, DictMixin)65 _mutable_set_types += (UserList,)66except ImportError:67 pass6869# if sets is still available, register the mutable set from there as well70try:71 from sets import Set7273 _mutable_set_types += (Set,)74except ImportError:75 pass7677#: register Python 2.6 abstract base classes78_mutable_set_types += (abc.MutableSet,)79_mutable_mapping_types += (abc.MutableMapping,)80_mutable_sequence_types += (abc.MutableSequence,)8182_mutable_spec = (83 (84 _mutable_set_types,85 frozenset(86 [87 "add",88 "clear",89 "difference_update",90 "discard",91 "pop",92 "remove",93 "symmetric_difference_update",94 "update",95 ]96 ),97 ),98 (99 _mutable_mapping_types,100 frozenset(["clear", "pop", "popitem", "setdefault", "update"]),101 ),102 (103 _mutable_sequence_types,104 frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),105 ),106 (107 deque,108 frozenset(109 [110 "append",111 "appendleft",112 "clear",113 "extend",114 "extendleft",115 "pop",116 "popleft",117 "remove",118 "rotate",119 ]120 ),121 ),122)123124125class _MagicFormatMapping(abc.Mapping):126 """This class implements a dummy wrapper to fix a bug in the Python127 standard library for string formatting.128129 See https://bugs.python.org/issue13598 for information about why130 this is necessary.131 """132133 def __init__(self, args, kwargs):134 self._args = args135 self._kwargs = kwargs136 self._last_index = 0137138 def __getitem__(self, key):139 if key == "":140 idx = self._last_index141 self._last_index += 1142 try:143 return self._args[idx]144 except LookupError:145 pass146 key = str(idx)147 return self._kwargs[key]148149 def __iter__(self):150 return iter(self._kwargs)151152 def __len__(self):153 return len(self._kwargs)154155156def inspect_format_method(callable):157 if not isinstance(158 callable, (types.MethodType, types.BuiltinMethodType)159 ) or callable.__name__ not in ("format", "format_map"):160 return None161 obj = callable.__self__162 if isinstance(obj, string_types):163 return obj164165166def safe_range(*args):167 """A range that can't generate ranges with a length of more than168 MAX_RANGE items.169 """170 rng = range_type(*args)171172 if len(rng) > MAX_RANGE:173 raise OverflowError(174 "Range too big. The sandbox blocks ranges larger than"175 " MAX_RANGE (%d)." % MAX_RANGE176 )177178 return rng179180181def unsafe(f):182 """Marks a function or method as unsafe.183184 ::185186 @unsafe187 def delete(self):188 pass189 """190 f.unsafe_callable = True191 return f192193194def is_internal_attribute(obj, attr):195 """Test if the attribute given is an internal python attribute. For196 example this function returns `True` for the `func_code` attribute of197 python objects. This is useful if the environment method198 :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.199200 >>> from jinja.sandbox import is_internal_attribute201 >>> is_internal_attribute(str, "mro")202 True203 >>> is_internal_attribute(str, "upper")204 False205 """206 if isinstance(obj, types.FunctionType):207 if attr in UNSAFE_FUNCTION_ATTRIBUTES:208 return True209 elif isinstance(obj, types.MethodType):210 if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:211 return True212 elif isinstance(obj, type):213 if attr == "mro":214 return True215 elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):216 return True217 elif isinstance(obj, types.GeneratorType):218 if attr in UNSAFE_GENERATOR_ATTRIBUTES:219 return True220 elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):221 if attr in UNSAFE_COROUTINE_ATTRIBUTES:222 return True223 elif hasattr(types, "AsyncGeneratorType") and isinstance(224 obj, types.AsyncGeneratorType225 ):226 if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:227 return True228 return attr.startswith("__")229230231def modifies_known_mutable(obj, attr):232 """This function checks if an attribute on a builtin mutable object233 (list, dict, set or deque) would modify it if called. It also supports234 the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and235 with Python 2.6 onwards the abstract base classes `MutableSet`,236 `MutableMapping`, and `MutableSequence`.237238 >>> modifies_known_mutable({}, "clear")239 True240 >>> modifies_known_mutable({}, "keys")241 False242 >>> modifies_known_mutable([], "append")243 True244 >>> modifies_known_mutable([], "index")245 False246247 If called with an unsupported object (such as unicode) `False` is248 returned.249250 >>> modifies_known_mutable("foo", "upper")251 False252 """253 for typespec, unsafe in _mutable_spec:254 if isinstance(obj, typespec):255 return attr in unsafe256 return False257258259class SandboxedEnvironment(Environment):260 """The sandboxed environment. It works like the regular environment but261 tells the compiler to generate sandboxed code. Additionally subclasses of262 this environment may override the methods that tell the runtime what263 attributes or functions are safe to access.264265 If the template tries to access insecure code a :exc:`SecurityError` is266 raised. However also other exceptions may occur during the rendering so267 the caller has to ensure that all exceptions are caught.268 """269270 sandboxed = True271272 #: default callback table for the binary operators. A copy of this is273 #: available on each instance of a sandboxed environment as274 #: :attr:`binop_table`275 default_binop_table = {276 "+": operator.add,277 "-": operator.sub,278 "*": operator.mul,279 "/": operator.truediv,280 "//": operator.floordiv,281 "**": operator.pow,282 "%": operator.mod,283 }284285 #: default callback table for the unary operators. A copy of this is286 #: available on each instance of a sandboxed environment as287 #: :attr:`unop_table`288 default_unop_table = {"+": operator.pos, "-": operator.neg}289290 #: a set of binary operators that should be intercepted. Each operator291 #: that is added to this set (empty by default) is delegated to the292 #: :meth:`call_binop` method that will perform the operator. The default293 #: operator callback is specified by :attr:`binop_table`.294 #:295 #: The following binary operators are interceptable:296 #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``297 #:298 #: The default operation form the operator table corresponds to the299 #: builtin function. Intercepted calls are always slower than the native300 #: operator call, so make sure only to intercept the ones you are301 #: interested in.302 #:303 #: .. versionadded:: 2.6304 intercepted_binops = frozenset()305306 #: a set of unary operators that should be intercepted. Each operator307 #: that is added to this set (empty by default) is delegated to the308 #: :meth:`call_unop` method that will perform the operator. The default309 #: operator callback is specified by :attr:`unop_table`.310 #:311 #: The following unary operators are interceptable: ``+``, ``-``312 #:313 #: The default operation form the operator table corresponds to the314 #: builtin function. Intercepted calls are always slower than the native315 #: operator call, so make sure only to intercept the ones you are316 #: interested in.317 #:318 #: .. versionadded:: 2.6319 intercepted_unops = frozenset()320321 def intercept_unop(self, operator):322 """Called during template compilation with the name of a unary323 operator to check if it should be intercepted at runtime. If this324 method returns `True`, :meth:`call_unop` is executed for this unary325 operator. The default implementation of :meth:`call_unop` will use326 the :attr:`unop_table` dictionary to perform the operator with the327 same logic as the builtin one.328329 The following unary operators are interceptable: ``+`` and ``-``330331 Intercepted calls are always slower than the native operator call,332 so make sure only to intercept the ones you are interested in.333334 .. versionadded:: 2.6335 """336 return False337338 def __init__(self, *args, **kwargs):339 Environment.__init__(self, *args, **kwargs)340 self.globals["range"] = safe_range341 self.binop_table = self.default_binop_table.copy()342 self.unop_table = self.default_unop_table.copy()343344 def is_safe_attribute(self, obj, attr, value):345 """The sandboxed environment will call this method to check if the346 attribute of an object is safe to access. Per default all attributes347 starting with an underscore are considered private as well as the348 special attributes of internal python objects as returned by the349 :func:`is_internal_attribute` function.350 """351 return not (attr.startswith("_") or is_internal_attribute(obj, attr))352353 def is_safe_callable(self, obj):354 """Check if an object is safely callable. Per default a function is355 considered safe unless the `unsafe_callable` attribute exists and is356 True. Override this method to alter the behavior, but this won't357 affect the `unsafe` decorator from this module.358 """359 return not (360 getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)361 )362363 def call_binop(self, context, operator, left, right):364 """For intercepted binary operator calls (:meth:`intercepted_binops`)365 this function is executed instead of the builtin operator. This can366 be used to fine tune the behavior of certain operators.367368 .. versionadded:: 2.6369 """370 return self.binop_table[operator](left, right)371372 def call_unop(self, context, operator, arg):373 """For intercepted unary operator calls (:meth:`intercepted_unops`)374 this function is executed instead of the builtin operator. This can375 be used to fine tune the behavior of certain operators.376377 .. versionadded:: 2.6378 """379 return self.unop_table[operator](arg)380381 def getitem(self, obj, argument):382 """Subscribe an object from sandboxed code."""383 try:384 return obj[argument]385 except (TypeError, LookupError):386 if isinstance(argument, string_types):387 try:388 attr = str(argument)389 except Exception:390 pass391 else:392 try:393 value = getattr(obj, attr)394 except AttributeError:395 pass396 else:397 if self.is_safe_attribute(obj, argument, value):398 return value399 return self.unsafe_undefined(obj, argument)400 return self.undefined(obj=obj, name=argument)401402 def getattr(self, obj, attribute):403 """Subscribe an object from sandboxed code and prefer the404 attribute. The attribute passed *must* be a bytestring.405 """406 try:407 value = getattr(obj, attribute)408 except AttributeError:409 try:410 return obj[attribute]411 except (TypeError, LookupError):412 pass413 else:414 if self.is_safe_attribute(obj, attribute, value):415 return value416 return self.unsafe_undefined(obj, attribute)417 return self.undefined(obj=obj, name=attribute)418419 def unsafe_undefined(self, obj, attribute):420 """Return an undefined object for unsafe attributes."""421 return self.undefined(422 "access to attribute %r of %r "423 "object is unsafe." % (attribute, obj.__class__.__name__),424 name=attribute,425 obj=obj,426 exc=SecurityError,427 )428429 def format_string(self, s, args, kwargs, format_func=None):430 """If a format call is detected, then this is routed through this431 method so that our safety sandbox can be used for it.432 """433 if isinstance(s, Markup):434 formatter = SandboxedEscapeFormatter(self, s.escape)435 else:436 formatter = SandboxedFormatter(self)437438 if format_func is not None and format_func.__name__ == "format_map":439 if len(args) != 1 or kwargs:440 raise TypeError(441 "format_map() takes exactly one argument %d given"442 % (len(args) + (kwargs is not None))443 )444445 kwargs = args[0]446 args = None447448 kwargs = _MagicFormatMapping(args, kwargs)449 rv = formatter.vformat(s, args, kwargs)450 return type(s)(rv)451452 def call(__self, __context, __obj, *args, **kwargs): # noqa: B902453 """Call an object from sandboxed code."""454 fmt = inspect_format_method(__obj)455 if fmt is not None:456 return __self.format_string(fmt, args, kwargs, __obj)457458 # the double prefixes are to avoid double keyword argument459 # errors when proxying the call.460 if not __self.is_safe_callable(__obj):461 raise SecurityError("%r is not safely callable" % (__obj,))462 return __context.call(__obj, *args, **kwargs)463464465class ImmutableSandboxedEnvironment(SandboxedEnvironment):466 """Works exactly like the regular `SandboxedEnvironment` but does not467 permit modifications on the builtin mutable objects `list`, `set`, and468 `dict` by using the :func:`modifies_known_mutable` function.469 """470471 def is_safe_attribute(self, obj, attr, value):472 if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):473 return False474 return not modifies_known_mutable(obj, attr)475476477# This really is not a public API apparently.478try:479 from _string import formatter_field_name_split480except ImportError:481482 def formatter_field_name_split(field_name):483 return field_name._formatter_field_name_split()484485486class SandboxedFormatterMixin(object):487 def __init__(self, env):488 self._env = env489490 def get_field(self, field_name, args, kwargs):491 first, rest = formatter_field_name_split(field_name)492 obj = self.get_value(first, args, kwargs)493 for is_attr, i in rest:494 if is_attr:495 obj = self._env.getattr(obj, i)496 else:497 obj = self._env.getitem(obj, i)498 return obj, first499500501class SandboxedFormatter(SandboxedFormatterMixin, Formatter):502 def __init__(self, env):503 SandboxedFormatterMixin.__init__(self, env)504 Formatter.__init__(self)505506507class SandboxedEscapeFormatter(SandboxedFormatterMixin, EscapeFormatter):508 def __init__(self, env, escape):509 SandboxedFormatterMixin.__init__(self, env)510 EscapeFormatter.__init__(self, escape)
added:src/jinja/tests.py+215 added
1# -*- coding: utf-8 -*-2"""Built-in template tests used with the ``is`` operator."""3import decimal4import operator5import re67from ._compat import abc8from ._compat import integer_types9from ._compat import string_types10from ._compat import text_type11from .runtime import Undefined1213number_re = re.compile(r"^-?\d+(\.\d+)?$")14regex_type = type(number_re)15test_callable = callable161718def test_odd(value):19 """Return true if the variable is odd."""20 return value % 2 == 1212223def test_even(value):24 """Return true if the variable is even."""25 return value % 2 == 0262728def test_divisibleby(value, num):29 """Check if a variable is divisible by a number."""30 return value % num == 0313233def test_defined(value):34 """Return true if the variable is defined:3536 .. sourcecode:: jinja3738 {% if variable is defined %}39 value of variable: {{ variable }}40 {% else %}41 variable is not defined42 {% endif %}4344 See the :func:`default` filter for a simple way to set undefined45 variables.46 """47 return not isinstance(value, Undefined)484950def test_undefined(value):51 """Like :func:`defined` but the other way round."""52 return isinstance(value, Undefined)535455def test_none(value):56 """Return true if the variable is none."""57 return value is None585960def test_boolean(value):61 """Return true if the object is a boolean value.6263 .. versionadded:: 2.1164 """65 return value is True or value is False666768def test_false(value):69 """Return true if the object is False.7071 .. versionadded:: 2.1172 """73 return value is False747576def test_true(value):77 """Return true if the object is True.7879 .. versionadded:: 2.1180 """81 return value is True828384# NOTE: The existing 'number' test matches booleans and floats85def test_integer(value):86 """Return true if the object is an integer.8788 .. versionadded:: 2.1189 """90 return isinstance(value, integer_types) and value is not True and value is not False919293# NOTE: The existing 'number' test matches booleans and integers94def test_float(value):95 """Return true if the object is a float.9697 .. versionadded:: 2.1198 """99 return isinstance(value, float)100101102def test_lower(value):103 """Return true if the variable is lowercased."""104 return text_type(value).islower()105106107def test_upper(value):108 """Return true if the variable is uppercased."""109 return text_type(value).isupper()110111112def test_string(value):113 """Return true if the object is a string."""114 return isinstance(value, string_types)115116117def test_mapping(value):118 """Return true if the object is a mapping (dict etc.).119120 .. versionadded:: 2.6121 """122 return isinstance(value, abc.Mapping)123124125def test_number(value):126 """Return true if the variable is a number."""127 return isinstance(value, integer_types + (float, complex, decimal.Decimal))128129130def test_sequence(value):131 """Return true if the variable is a sequence. Sequences are variables132 that are iterable.133 """134 try:135 len(value)136 value.__getitem__137 except Exception:138 return False139 return True140141142def test_sameas(value, other):143 """Check if an object points to the same memory address than another144 object:145146 .. sourcecode:: jinja147148 {% if foo.attribute is sameas false %}149 the foo attribute really is the `False` singleton150 {% endif %}151 """152 return value is other153154155def test_iterable(value):156 """Check if it's possible to iterate over an object."""157 try:158 iter(value)159 except TypeError:160 return False161 return True162163164def test_escaped(value):165 """Check if the value is escaped."""166 return hasattr(value, "__html__")167168169def test_in(value, seq):170 """Check if value is in seq.171172 .. versionadded:: 2.10173 """174 return value in seq175176177TESTS = {178 "odd": test_odd,179 "even": test_even,180 "divisibleby": test_divisibleby,181 "defined": test_defined,182 "undefined": test_undefined,183 "none": test_none,184 "boolean": test_boolean,185 "false": test_false,186 "true": test_true,187 "integer": test_integer,188 "float": test_float,189 "lower": test_lower,190 "upper": test_upper,191 "string": test_string,192 "mapping": test_mapping,193 "number": test_number,194 "sequence": test_sequence,195 "iterable": test_iterable,196 "callable": test_callable,197 "sameas": test_sameas,198 "escaped": test_escaped,199 "in": test_in,200 "==": operator.eq,201 "eq": operator.eq,202 "equalto": operator.eq,203 "!=": operator.ne,204 "ne": operator.ne,205 ">": operator.gt,206 "gt": operator.gt,207 "greaterthan": operator.gt,208 "ge": operator.ge,209 ">=": operator.ge,210 "<": operator.lt,211 "lt": operator.lt,212 "lessthan": operator.lt,213 "<=": operator.le,214 "le": operator.le,215}
added:src/jinja/utils.py+727 added
1# -*- coding: utf-8 -*-2import json3import os4import re5import warnings6from collections import deque7from random import choice8from random import randrange9from threading import Lock1011from markupsafe import escape12from markupsafe import Markup1314from ._compat import abc15from ._compat import string_types16from ._compat import text_type17from ._compat import url_quote1819_word_split_re = re.compile(r"(\s+)")20_punctuation_re = re.compile(21 "^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$"22 % (23 "|".join(map(re.escape, ("(", "<", "&lt;"))),24 "|".join(map(re.escape, (".", ",", ")", ">", "\n", "&gt;"))),25 )26)27_simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")28_striptags_re = re.compile(r"(<!--.*?-->|<[^>]*>)")29_entity_re = re.compile(r"&([^;]+);")30_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"31_digits = "0123456789"3233# special singleton representing missing values for the runtime34missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()3536# internal code37internal_code = set()3839concat = u"".join4041_slash_escape = "\\/" not in json.dumps("/")424344def contextfunction(f):45 """This decorator can be used to mark a function or method context callable.46 A context callable is passed the active :class:`Context` as first argument when47 called from the template. This is useful if a function wants to get access48 to the context or functions provided on the context object. For example49 a function that returns a sorted list of template variables the current50 template exports could look like this::5152 @contextfunction53 def get_exported_names(context):54 return sorted(context.exported_vars)55 """56 f.contextfunction = True57 return f585960def evalcontextfunction(f):61 """This decorator can be used to mark a function or method as an eval62 context callable. This is similar to the :func:`contextfunction`63 but instead of passing the context, an evaluation context object is64 passed. For more information about the eval context, see65 :ref:`eval-context`.6667 .. versionadded:: 2.468 """69 f.evalcontextfunction = True70 return f717273def environmentfunction(f):74 """This decorator can be used to mark a function or method as environment75 callable. This decorator works exactly like the :func:`contextfunction`76 decorator just that the first argument is the active :class:`Environment`77 and not context.78 """79 f.environmentfunction = True80 return f818283def internalcode(f):84 """Marks the function as internally used"""85 internal_code.add(f.__code__)86 return f878889def is_undefined(obj):90 """Check if the object passed is undefined. This does nothing more than91 performing an instance check against :class:`Undefined` but looks nicer.92 This can be used for custom filters or tests that want to react to93 undefined variables. For example a custom default filter can look like94 this::9596 def default(var, default=''):97 if is_undefined(var):98 return default99 return var100 """101 from .runtime import Undefined102103 return isinstance(obj, Undefined)104105106def consume(iterable):107 """Consumes an iterable without doing anything with it."""108 for _ in iterable:109 pass110111112def clear_caches():113 """Jinja keeps internal caches for environments and lexers. These are114 used so that Jinja doesn't have to recreate environments and lexers all115 the time. Normally you don't have to care about that but if you are116 measuring memory consumption you may want to clean the caches.117 """118 from .environment import _spontaneous_environments119 from .lexer import _lexer_cache120121 _spontaneous_environments.clear()122 _lexer_cache.clear()123124125def import_string(import_name, silent=False):126 """Imports an object based on a string. This is useful if you want to127 use import paths as endpoints or something similar. An import path can128 be specified either in dotted notation (``xml.sax.saxutils.escape``)129 or with a colon as object delimiter (``xml.sax.saxutils:escape``).130131 If the `silent` is True the return value will be `None` if the import132 fails.133134 :return: imported object135 """136 try:137 if ":" in import_name:138 module, obj = import_name.split(":", 1)139 elif "." in import_name:140 module, _, obj = import_name.rpartition(".")141 else:142 return __import__(import_name)143 return getattr(__import__(module, None, None, [obj]), obj)144 except (ImportError, AttributeError):145 if not silent:146 raise147148149def open_if_exists(filename, mode="rb"):150 """Returns a file descriptor for the filename if that file exists,151 otherwise ``None``.152 """153 if not os.path.isfile(filename):154 return None155156 return open(filename, mode)157158159def object_type_repr(obj):160 """Returns the name of the object's type. For some recognized161 singletons the name of the object is returned instead. (For162 example for `None` and `Ellipsis`).163 """164 if obj is None:165 return "None"166 elif obj is Ellipsis:167 return "Ellipsis"168 # __builtin__ in 2.x, builtins in 3.x169 if obj.__class__.__module__ in ("__builtin__", "builtins"):170 name = obj.__class__.__name__171 else:172 name = obj.__class__.__module__ + "." + obj.__class__.__name__173 return "%s object" % name174175176def pformat(obj, verbose=False):177 """Prettyprint an object. Either use the `pretty` library or the178 builtin `pprint`.179 """180 try:181 from pretty import pretty182183 return pretty(obj, verbose=verbose)184 except ImportError:185 from pprint import pformat186187 return pformat(obj)188189190def urlize(text, trim_url_limit=None, rel=None, target=None):191 """Converts any URLs in text into clickable links. Works on http://,192 https:// and www. links. Links can have trailing punctuation (periods,193 commas, close-parens) and leading punctuation (opening parens) and194 it'll still do the right thing.195196 If trim_url_limit is not None, the URLs in link text will be limited197 to trim_url_limit characters.198199 If nofollow is True, the URLs in link text will get a rel="nofollow"200 attribute.201202 If target is not None, a target attribute will be added to the link.203 """204 trim_url = (205 lambda x, limit=trim_url_limit: limit is not None206 and (x[:limit] + (len(x) >= limit and "..." or ""))207 or x208 )209 words = _word_split_re.split(text_type(escape(text)))210 rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ""211 target_attr = target and ' target="%s"' % escape(target) or ""212213 for i, word in enumerate(words):214 match = _punctuation_re.match(word)215 if match:216 lead, middle, trail = match.groups()217 if middle.startswith("www.") or (218 "@" not in middle219 and not middle.startswith("http://")220 and not middle.startswith("https://")221 and len(middle) > 0222 and middle[0] in _letters + _digits223 and (224 middle.endswith(".org")225 or middle.endswith(".net")226 or middle.endswith(".com")227 )228 ):229 middle = '<a href="http://%s"%s%s>%s</a>' % (230 middle,231 rel_attr,232 target_attr,233 trim_url(middle),234 )235 if middle.startswith("http://") or middle.startswith("https://"):236 middle = '<a href="%s"%s%s>%s</a>' % (237 middle,238 rel_attr,239 target_attr,240 trim_url(middle),241 )242 if (243 "@" in middle244 and not middle.startswith("www.")245 and ":" not in middle246 and _simple_email_re.match(middle)247 ):248 middle = '<a href="mailto:%s">%s</a>' % (middle, middle)249 if lead + middle + trail != word:250 words[i] = lead + middle + trail251 return u"".join(words)252253254def generate_lorem_ipsum(n=5, html=True, min=20, max=100):255 """Generate some lorem ipsum for the template."""256 from .constants import LOREM_IPSUM_WORDS257258 words = LOREM_IPSUM_WORDS.split()259 result = []260261 for _ in range(n):262 next_capitalized = True263 last_comma = last_fullstop = 0264 word = None265 last = None266 p = []267268 # each paragraph contains out of 20 to 100 words.269 for idx, _ in enumerate(range(randrange(min, max))):270 while True:271 word = choice(words)272 if word != last:273 last = word274 break275 if next_capitalized:276 word = word.capitalize()277 next_capitalized = False278 # add commas279 if idx - randrange(3, 8) > last_comma:280 last_comma = idx281 last_fullstop += 2282 word += ","283 # add end of sentences284 if idx - randrange(10, 20) > last_fullstop:285 last_comma = last_fullstop = idx286 word += "."287 next_capitalized = True288 p.append(word)289290 # ensure that the paragraph ends with a dot.291 p = u" ".join(p)292 if p.endswith(","):293 p = p[:-1] + "."294 elif not p.endswith("."):295 p += "."296 result.append(p)297298 if not html:299 return u"\n\n".join(result)300 return Markup(u"\n".join(u"<p>%s</p>" % escape(x) for x in result))301302303def unicode_urlencode(obj, charset="utf-8", for_qs=False):304 """Quote a string for use in a URL using the given charset.305306 This function is misnamed, it is a wrapper around307 :func:`urllib.parse.quote`.308309 :param obj: String or bytes to quote. Other types are converted to310 string then encoded to bytes using the given charset.311 :param charset: Encode text to bytes using this charset.312 :param for_qs: Quote "/" and use "+" for spaces.313 """314 if not isinstance(obj, string_types):315 obj = text_type(obj)316317 if isinstance(obj, text_type):318 obj = obj.encode(charset)319320 safe = b"" if for_qs else b"/"321 rv = url_quote(obj, safe)322323 if not isinstance(rv, text_type):324 rv = rv.decode("utf-8")325326 if for_qs:327 rv = rv.replace("%20", "+")328329 return rv330331332class LRUCache(object):333 """A simple LRU Cache implementation."""334335 # this is fast for small capacities (something below 1000) but doesn't336 # scale. But as long as it's only used as storage for templates this337 # won't do any harm.338339 def __init__(self, capacity):340 self.capacity = capacity341 self._mapping = {}342 self._queue = deque()343 self._postinit()344345 def _postinit(self):346 # alias all queue methods for faster lookup347 self._popleft = self._queue.popleft348 self._pop = self._queue.pop349 self._remove = self._queue.remove350 self._wlock = Lock()351 self._append = self._queue.append352353 def __getstate__(self):354 return {355 "capacity": self.capacity,356 "_mapping": self._mapping,357 "_queue": self._queue,358 }359360 def __setstate__(self, d):361 self.__dict__.update(d)362 self._postinit()363364 def __getnewargs__(self):365 return (self.capacity,)366367 def copy(self):368 """Return a shallow copy of the instance."""369 rv = self.__class__(self.capacity)370 rv._mapping.update(self._mapping)371 rv._queue.extend(self._queue)372 return rv373374 def get(self, key, default=None):375 """Return an item from the cache dict or `default`"""376 try:377 return self[key]378 except KeyError:379 return default380381 def setdefault(self, key, default=None):382 """Set `default` if the key is not in the cache otherwise383 leave unchanged. Return the value of this key.384 """385 try:386 return self[key]387 except KeyError:388 self[key] = default389 return default390391 def clear(self):392 """Clear the cache."""393 self._wlock.acquire()394 try:395 self._mapping.clear()396 self._queue.clear()397 finally:398 self._wlock.release()399400 def __contains__(self, key):401 """Check if a key exists in this cache."""402 return key in self._mapping403404 def __len__(self):405 """Return the current size of the cache."""406 return len(self._mapping)407408 def __repr__(self):409 return "<%s %r>" % (self.__class__.__name__, self._mapping)410411 def __getitem__(self, key):412 """Get an item from the cache. Moves the item up so that it has the413 highest priority then.414415 Raise a `KeyError` if it does not exist.416 """417 self._wlock.acquire()418 try:419 rv = self._mapping[key]420 if self._queue[-1] != key:421 try:422 self._remove(key)423 except ValueError:424 # if something removed the key from the container425 # when we read, ignore the ValueError that we would426 # get otherwise.427 pass428 self._append(key)429 return rv430 finally:431 self._wlock.release()432433 def __setitem__(self, key, value):434 """Sets the value for an item. Moves the item up so that it435 has the highest priority then.436 """437 self._wlock.acquire()438 try:439 if key in self._mapping:440 self._remove(key)441 elif len(self._mapping) == self.capacity:442 del self._mapping[self._popleft()]443 self._append(key)444 self._mapping[key] = value445 finally:446 self._wlock.release()447448 def __delitem__(self, key):449 """Remove an item from the cache dict.450 Raise a `KeyError` if it does not exist.451 """452 self._wlock.acquire()453 try:454 del self._mapping[key]455 try:456 self._remove(key)457 except ValueError:458 pass459 finally:460 self._wlock.release()461462 def items(self):463 """Return a list of items."""464 result = [(key, self._mapping[key]) for key in list(self._queue)]465 result.reverse()466 return result467468 def iteritems(self):469 """Iterate over all items."""470 warnings.warn(471 "'iteritems()' will be removed in version 3.0. Use"472 " 'iter(cache.items())' instead.",473 DeprecationWarning,474 stacklevel=2,475 )476 return iter(self.items())477478 def values(self):479 """Return a list of all values."""480 return [x[1] for x in self.items()]481482 def itervalue(self):483 """Iterate over all values."""484 warnings.warn(485 "'itervalue()' will be removed in version 3.0. Use"486 " 'iter(cache.values())' instead.",487 DeprecationWarning,488 stacklevel=2,489 )490 return iter(self.values())491492 def itervalues(self):493 """Iterate over all values."""494 warnings.warn(495 "'itervalues()' will be removed in version 3.0. Use"496 " 'iter(cache.values())' instead.",497 DeprecationWarning,498 stacklevel=2,499 )500 return iter(self.values())501502 def keys(self):503 """Return a list of all keys ordered by most recent usage."""504 return list(self)505506 def iterkeys(self):507 """Iterate over all keys in the cache dict, ordered by508 the most recent usage.509 """510 warnings.warn(511 "'iterkeys()' will be removed in version 3.0. Use"512 " 'iter(cache.keys())' instead.",513 DeprecationWarning,514 stacklevel=2,515 )516 return iter(self)517518 def __iter__(self):519 return reversed(tuple(self._queue))520521 def __reversed__(self):522 """Iterate over the keys in the cache dict, oldest items523 coming first.524 """525 return iter(tuple(self._queue))526527 __copy__ = copy528529530abc.MutableMapping.register(LRUCache)531532533def select_autoescape(534 enabled_extensions=("html", "htm", "xml"),535 disabled_extensions=(),536 default_for_string=True,537 default=False,538):539 """Intelligently sets the initial value of autoescaping based on the540 filename of the template. This is the recommended way to configure541 autoescaping if you do not want to write a custom function yourself.542543 If you want to enable it for all templates created from strings or544 for all templates with `.html` and `.xml` extensions::545546 from jinja import Environment, select_autoescape547 env = Environment(autoescape=select_autoescape(548 enabled_extensions=('html', 'xml'),549 default_for_string=True,550 ))551552 Example configuration to turn it on at all times except if the template553 ends with `.txt`::554555 from jinja import Environment, select_autoescape556 env = Environment(autoescape=select_autoescape(557 disabled_extensions=('txt',),558 default_for_string=True,559 default=True,560 ))561562 The `enabled_extensions` is an iterable of all the extensions that563 autoescaping should be enabled for. Likewise `disabled_extensions` is564 a list of all templates it should be disabled for. If a template is565 loaded from a string then the default from `default_for_string` is used.566 If nothing matches then the initial value of autoescaping is set to the567 value of `default`.568569 For security reasons this function operates case insensitive.570571 .. versionadded:: 2.9572 """573 enabled_patterns = tuple("." + x.lstrip(".").lower() for x in enabled_extensions)574 disabled_patterns = tuple("." + x.lstrip(".").lower() for x in disabled_extensions)575576 def autoescape(template_name):577 if template_name is None:578 return default_for_string579 template_name = template_name.lower()580 if template_name.endswith(enabled_patterns):581 return True582 if template_name.endswith(disabled_patterns):583 return False584 return default585586 return autoescape587588589def htmlsafe_json_dumps(obj, dumper=None, **kwargs):590 """Works exactly like :func:`dumps` but is safe for use in ``<script>``591 tags. It accepts the same arguments and returns a JSON string. Note that592 this is available in templates through the ``|tojson`` filter which will593 also mark the result as safe. Due to how this function escapes certain594 characters this is safe even if used outside of ``<script>`` tags.595596 The following characters are escaped in strings:597598 - ``<``599 - ``>``600 - ``&``601 - ``'``602603 This makes it safe to embed such strings in any place in HTML with the604 notable exception of double quoted attributes. In that case single605 quote your attributes or HTML escape it in addition.606 """607 if dumper is None:608 dumper = json.dumps609 rv = (610 dumper(obj, **kwargs)611 .replace(u"<", u"\\u003c")612 .replace(u">", u"\\u003e")613 .replace(u"&", u"\\u0026")614 .replace(u"'", u"\\u0027")615 )616 return Markup(rv)617618619class Cycler(object):620 """Cycle through values by yield them one at a time, then restarting621 once the end is reached. Available as ``cycler`` in templates.622623 Similar to ``loop.cycle``, but can be used outside loops or across624 multiple loops. For example, render a list of folders and files in a625 list, alternating giving them "odd" and "even" classes.626627 .. code-block:: html+jinja628629 {% set row_class = cycler("odd", "even") %}630 <ul class="browser">631 {% for folder in folders %}632 <li class="folder {{ row_class.next() }}">{{ folder }}633 {% endfor %}634 {% for file in files %}635 <li class="file {{ row_class.next() }}">{{ file }}636 {% endfor %}637 </ul>638639 :param items: Each positional argument will be yielded in the order640 given for each cycle.641642 .. versionadded:: 2.1643 """644645 def __init__(self, *items):646 if not items:647 raise RuntimeError("at least one item has to be provided")648 self.items = items649 self.pos = 0650651 def reset(self):652 """Resets the current item to the first item."""653 self.pos = 0654655 @property656 def current(self):657 """Return the current item. Equivalent to the item that will be658 returned next time :meth:`next` is called.659 """660 return self.items[self.pos]661662 def next(self):663 """Return the current item, then advance :attr:`current` to the664 next item.665 """666 rv = self.current667 self.pos = (self.pos + 1) % len(self.items)668 return rv669670 __next__ = next671672673class Joiner(object):674 """A joining helper for templates."""675676 def __init__(self, sep=u", "):677 self.sep = sep678 self.used = False679680 def __call__(self):681 if not self.used:682 self.used = True683 return u""684 return self.sep685686687class Namespace(object):688 """A namespace object that can hold arbitrary attributes. It may be689 initialized from a dictionary or with keyword arguments."""690691 def __init__(*args, **kwargs): # noqa: B902692 self, args = args[0], args[1:]693 self.__attrs = dict(*args, **kwargs)694695 def __getattribute__(self, name):696 if name == "_Namespace__attrs":697 return object.__getattribute__(self, name)698 try:699 return self.__attrs[name]700 except KeyError:701 raise AttributeError(name)702703 def __setitem__(self, name, value):704 self.__attrs[name] = value705706 def __repr__(self):707 return "<Namespace %r>" % self.__attrs708709710# does this python version support async for in and async generators?711try:712 exec("async def _():\n async for _ in ():\n yield _")713 have_async_gen = True714except SyntaxError:715 have_async_gen = False716717718def soft_unicode(s):719 from markupsafe import soft_unicode720721 warnings.warn(722 "'jinja.utils.soft_unicode' will be removed in version 3.0."723 " Use 'markupsafe.soft_unicode' instead.",724 DeprecationWarning,725 stacklevel=2,726 )727 return soft_unicode(s)
added:src/jinja/visitor.py+81 added
1# -*- coding: utf-8 -*-2"""API for traversing the AST nodes. Implemented by the compiler and3meta introspection.4"""5from .nodes import Node678class NodeVisitor(object):9 """Walks the abstract syntax tree and call visitor functions for every10 node found. The visitor functions may return values which will be11 forwarded by the `visit` method.1213 Per default the visitor functions for the nodes are ``'visit_'`` +14 class name of the node. So a `TryFinally` node visit function would15 be `visit_TryFinally`. This behavior can be changed by overriding16 the `get_visitor` function. If no visitor function exists for a node17 (return value `None`) the `generic_visit` visitor is used instead.18 """1920 def get_visitor(self, node):21 """Return the visitor function for this node or `None` if no visitor22 exists for this node. In that case the generic visit function is23 used instead.24 """25 method = "visit_" + node.__class__.__name__26 return getattr(self, method, None)2728 def visit(self, node, *args, **kwargs):29 """Visit a node."""30 f = self.get_visitor(node)31 if f is not None:32 return f(node, *args, **kwargs)33 return self.generic_visit(node, *args, **kwargs)3435 def generic_visit(self, node, *args, **kwargs):36 """Called if no explicit visitor function exists for a node."""37 for node in node.iter_child_nodes():38 self.visit(node, *args, **kwargs)394041class NodeTransformer(NodeVisitor):42 """Walks the abstract syntax tree and allows modifications of nodes.4344 The `NodeTransformer` will walk the AST and use the return value of the45 visitor functions to replace or remove the old node. If the return46 value of the visitor function is `None` the node will be removed47 from the previous location otherwise it's replaced with the return48 value. The return value may be the original node in which case no49 replacement takes place.50 """5152 def generic_visit(self, node, *args, **kwargs):53 for field, old_value in node.iter_fields():54 if isinstance(old_value, list):55 new_values = []56 for value in old_value:57 if isinstance(value, Node):58 value = self.visit(value, *args, **kwargs)59 if value is None:60 continue61 elif not isinstance(value, Node):62 new_values.extend(value)63 continue64 new_values.append(value)65 old_value[:] = new_values66 elif isinstance(old_value, Node):67 new_node = self.visit(old_value, *args, **kwargs)68 if new_node is None:69 delattr(node, field)70 else:71 setattr(node, field, new_node)72 return node7374 def visit_list(self, node, *args, **kwargs):75 """As transformers may return lists in some places this method76 can be used to enforce a list as return value.77 """78 rv = self.visit(node, *args, **kwargs)79 if not isinstance(rv, list):80 rv = [rv]81 return rv
deleted:src/jinja2/__init__.py-43 removed
1# -*- coding: utf-8 -*-2"""Jinja is a template engine written in pure Python. It provides a3non-XML syntax that supports inline expressions and an optional4sandboxed environment.5"""6from .bccache import BytecodeCache7from .bccache import FileSystemBytecodeCache8from .bccache import MemcachedBytecodeCache9from .environment import Environment10from .environment import Template11from .exceptions import TemplateAssertionError12from .exceptions import TemplateError13from .exceptions import TemplateNotFound14from .exceptions import TemplateRuntimeError15from .exceptions import TemplatesNotFound16from .exceptions import TemplateSyntaxError17from .exceptions import UndefinedError18from .filters import contextfilter19from .filters import environmentfilter20from .filters import evalcontextfilter21from .loaders import BaseLoader22from .loaders import ChoiceLoader23from .loaders import DictLoader24from .loaders import FileSystemLoader25from .loaders import FunctionLoader26from .loaders import ModuleLoader27from .loaders import PackageLoader28from .loaders import PrefixLoader29from .runtime import ChainableUndefined30from .runtime import DebugUndefined31from .runtime import make_logging_undefined32from .runtime import StrictUndefined33from .runtime import Undefined34from .utils import clear_caches35from .utils import contextfunction36from .utils import environmentfunction37from .utils import escape38from .utils import evalcontextfunction39from .utils import is_undefined40from .utils import Markup41from .utils import select_autoescape4243__version__ = "2.11.0.dev0"
deleted:src/jinja2/_compat.py-132 removed
1# -*- coding: utf-8 -*-2# flake8: noqa3import marshal4import sys56PY2 = sys.version_info[0] == 27PYPY = hasattr(sys, "pypy_translation_info")8_identity = lambda x: x910if not PY2:11 unichr = chr12 range_type = range13 text_type = str14 string_types = (str,)15 integer_types = (int,)1617 iterkeys = lambda d: iter(d.keys())18 itervalues = lambda d: iter(d.values())19 iteritems = lambda d: iter(d.items())2021 import pickle22 from io import BytesIO, StringIO2324 NativeStringIO = StringIO2526 def reraise(tp, value, tb=None):27 if value.__traceback__ is not tb:28 raise value.with_traceback(tb)29 raise value3031 ifilter = filter32 imap = map33 izip = zip34 intern = sys.intern3536 implements_iterator = _identity37 implements_to_string = _identity38 encode_filename = _identity3940 marshal_dump = marshal.dump41 marshal_load = marshal.load4243else:44 unichr = unichr45 text_type = unicode46 range_type = xrange47 string_types = (str, unicode)48 integer_types = (int, long)4950 iterkeys = lambda d: d.iterkeys()51 itervalues = lambda d: d.itervalues()52 iteritems = lambda d: d.iteritems()5354 import cPickle as pickle55 from cStringIO import StringIO as BytesIO, StringIO5657 NativeStringIO = BytesIO5859 exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")6061 from itertools import imap, izip, ifilter6263 intern = intern6465 def implements_iterator(cls):66 cls.next = cls.__next__67 del cls.__next__68 return cls6970 def implements_to_string(cls):71 cls.__unicode__ = cls.__str__72 cls.__str__ = lambda x: x.__unicode__().encode("utf-8")73 return cls7475 def encode_filename(filename):76 if isinstance(filename, unicode):77 return filename.encode("utf-8")78 return filename7980 def marshal_dump(code, f):81 if isinstance(f, file):82 marshal.dump(code, f)83 else:84 f.write(marshal.dumps(code))8586 def marshal_load(f):87 if isinstance(f, file):88 return marshal.load(f)89 return marshal.loads(f.read())909192def with_metaclass(meta, *bases):93 """Create a base class with a metaclass."""94 # This requires a bit of explanation: the basic idea is to make a95 # dummy metaclass for one level of class instantiation that replaces96 # itself with the actual metaclass.97 class metaclass(type):98 def __new__(cls, name, this_bases, d):99 return meta(name, bases, d)100101 return type.__new__(metaclass, "temporary_class", (), {})102103104try:105 from urllib.parse import quote_from_bytes as url_quote106except ImportError:107 from urllib import quote as url_quote108109110try:111 from collections import abc112except ImportError:113 import collections as abc114115116try:117 from os import fspath118except ImportError:119 try:120 from pathlib import PurePath121 except ImportError:122 PurePath = None123124 def fspath(path):125 if hasattr(path, "__fspath__"):126 return path.__fspath__()127128 # Python 3.5 doesn't have __fspath__ yet, use str.129 if PurePath is not None and isinstance(path, PurePath):130 return str(path)131132 return path
deleted:src/jinja2/_identifier.py-6 removed
1import re23# generated by scripts/generate_identifier_pattern.py4pattern = re.compile(5 r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఃా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑅳𑄴𑆀-𑆂𑆳-𑇊𑇀-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B9506)
deleted:src/jinja2/asyncfilters.py-159 removed
1from functools import wraps23from . import filters4from .asyncsupport import auto_aiter5from .asyncsupport import auto_await678async def auto_to_seq(value):9 seq = []10 if hasattr(value, "__aiter__"):11 async for item in value:12 seq.append(item)13 else:14 for item in value:15 seq.append(item)16 return seq171819async def async_select_or_reject(args, kwargs, modfunc, lookup_attr):20 seq, func = filters.prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)21 if seq:22 async for item in auto_aiter(seq):23 if func(item):24 yield item252627def dualfilter(normal_filter, async_filter):28 wrap_evalctx = False29 if getattr(normal_filter, "environmentfilter", False):3031 def is_async(args):32 return args[0].is_async3334 wrap_evalctx = False35 else:36 if not getattr(normal_filter, "evalcontextfilter", False) and not getattr(37 normal_filter, "contextfilter", False38 ):39 wrap_evalctx = True4041 def is_async(args):42 return args[0].environment.is_async4344 @wraps(normal_filter)45 def wrapper(*args, **kwargs):46 b = is_async(args)47 if wrap_evalctx:48 args = args[1:]49 if b:50 return async_filter(*args, **kwargs)51 return normal_filter(*args, **kwargs)5253 if wrap_evalctx:54 wrapper.evalcontextfilter = True5556 wrapper.asyncfiltervariant = True5758 return wrapper596061def asyncfiltervariant(original):62 def decorator(f):63 return dualfilter(original, f)6465 return decorator666768@asyncfiltervariant(filters.do_first)69async def do_first(environment, seq):70 try:71 return await auto_aiter(seq).__anext__()72 except StopAsyncIteration:73 return environment.undefined("No first item, sequence was empty.")747576@asyncfiltervariant(filters.do_groupby)77async def do_groupby(environment, value, attribute):78 expr = filters.make_attrgetter(environment, attribute)79 return [80 filters._GroupTuple(key, await auto_to_seq(values))81 for key, values in filters.groupby(82 sorted(await auto_to_seq(value), key=expr), expr83 )84 ]858687@asyncfiltervariant(filters.do_join)88async def do_join(eval_ctx, value, d=u"", attribute=None):89 return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)909192@asyncfiltervariant(filters.do_list)93async def do_list(value):94 return await auto_to_seq(value)959697@asyncfiltervariant(filters.do_reject)98async def do_reject(*args, **kwargs):99 return async_select_or_reject(args, kwargs, lambda x: not x, False)100101102@asyncfiltervariant(filters.do_rejectattr)103async def do_rejectattr(*args, **kwargs):104 return async_select_or_reject(args, kwargs, lambda x: not x, True)105106107@asyncfiltervariant(filters.do_select)108async def do_select(*args, **kwargs):109 return async_select_or_reject(args, kwargs, lambda x: x, False)110111112@asyncfiltervariant(filters.do_selectattr)113async def do_selectattr(*args, **kwargs):114 return async_select_or_reject(args, kwargs, lambda x: x, True)115116117@asyncfiltervariant(filters.do_map)118async def do_map(*args, **kwargs):119 seq, func = filters.prepare_map(args, kwargs)120 if seq:121 async for item in auto_aiter(seq):122 yield await auto_await(func(item))123124125@asyncfiltervariant(filters.do_sum)126async def do_sum(environment, iterable, attribute=None, start=0):127 rv = start128 if attribute is not None:129 func = filters.make_attrgetter(environment, attribute)130 else:131132 def func(x):133 return x134135 async for item in auto_aiter(iterable):136 rv += func(item)137 return rv138139140@asyncfiltervariant(filters.do_slice)141async def do_slice(value, slices, fill_with=None):142 return filters.do_slice(await auto_to_seq(value), slices, fill_with)143144145ASYNC_FILTERS = {146 "first": do_first,147 "groupby": do_groupby,148 "join": do_join,149 "list": do_list,150 # we intentionally do not support do_last because that would be151 # ridiculous152 "reject": do_reject,153 "rejectattr": do_rejectattr,154 "map": do_map,155 "select": do_select,156 "selectattr": do_selectattr,157 "sum": do_sum,158 "slice": do_slice,159}
deleted:src/jinja2/asyncsupport.py-263 removed
1# -*- coding: utf-8 -*-2"""The code for async support. Importing this patches Jinja on supported3Python versions.4"""5import asyncio6import inspect7from functools import update_wrapper89from .environment import TemplateModule10from .runtime import LoopContext11from .utils import concat12from .utils import internalcode13from .utils import Markup14from .utils import missing151617async def concat_async(async_gen):18 rv = []1920 async def collect():21 async for event in async_gen:22 rv.append(event)2324 await collect()25 return concat(rv)262728async def generate_async(self, *args, **kwargs):29 vars = dict(*args, **kwargs)30 try:31 async for event in self.root_render_func(self.new_context(vars)):32 yield event33 except Exception:34 yield self.environment.handle_exception()353637def wrap_generate_func(original_generate):38 def _convert_generator(self, loop, args, kwargs):39 async_gen = self.generate_async(*args, **kwargs)40 try:41 while 1:42 yield loop.run_until_complete(async_gen.__anext__())43 except StopAsyncIteration:44 pass4546 def generate(self, *args, **kwargs):47 if not self.environment.is_async:48 return original_generate(self, *args, **kwargs)49 return _convert_generator(self, asyncio.get_event_loop(), args, kwargs)5051 return update_wrapper(generate, original_generate)525354async def render_async(self, *args, **kwargs):55 if not self.environment.is_async:56 raise RuntimeError("The environment was not created with async mode enabled.")5758 vars = dict(*args, **kwargs)59 ctx = self.new_context(vars)6061 try:62 return await concat_async(self.root_render_func(ctx))63 except Exception:64 return self.environment.handle_exception()656667def wrap_render_func(original_render):68 def render(self, *args, **kwargs):69 if not self.environment.is_async:70 return original_render(self, *args, **kwargs)71 loop = asyncio.get_event_loop()72 return loop.run_until_complete(self.render_async(*args, **kwargs))7374 return update_wrapper(render, original_render)757677def wrap_block_reference_call(original_call):78 @internalcode79 async def async_call(self):80 rv = await concat_async(self._stack[self._depth](self._context))81 if self._context.eval_ctx.autoescape:82 rv = Markup(rv)83 return rv8485 @internalcode86 def __call__(self):87 if not self._context.environment.is_async:88 return original_call(self)89 return async_call(self)9091 return update_wrapper(__call__, original_call)929394def wrap_macro_invoke(original_invoke):95 @internalcode96 async def async_invoke(self, arguments, autoescape):97 rv = await self._func(*arguments)98 if autoescape:99 rv = Markup(rv)100 return rv101102 @internalcode103 def _invoke(self, arguments, autoescape):104 if not self._environment.is_async:105 return original_invoke(self, arguments, autoescape)106 return async_invoke(self, arguments, autoescape)107108 return update_wrapper(_invoke, original_invoke)109110111@internalcode112async def get_default_module_async(self):113 if self._module is not None:114 return self._module115 self._module = rv = await self.make_module_async()116 return rv117118119def wrap_default_module(original_default_module):120 @internalcode121 def _get_default_module(self):122 if self.environment.is_async:123 raise RuntimeError("Template module attribute is unavailable in async mode")124 return original_default_module(self)125126 return _get_default_module127128129async def make_module_async(self, vars=None, shared=False, locals=None):130 context = self.new_context(vars, shared, locals)131 body_stream = []132 async for item in self.root_render_func(context):133 body_stream.append(item)134 return TemplateModule(self, context, body_stream)135136137def patch_template():138 from . import Template139140 Template.generate = wrap_generate_func(Template.generate)141 Template.generate_async = update_wrapper(generate_async, Template.generate_async)142 Template.render_async = update_wrapper(render_async, Template.render_async)143 Template.render = wrap_render_func(Template.render)144 Template._get_default_module = wrap_default_module(Template._get_default_module)145 Template._get_default_module_async = get_default_module_async146 Template.make_module_async = update_wrapper(147 make_module_async, Template.make_module_async148 )149150151def patch_runtime():152 from .runtime import BlockReference, Macro153154 BlockReference.__call__ = wrap_block_reference_call(BlockReference.__call__)155 Macro._invoke = wrap_macro_invoke(Macro._invoke)156157158def patch_filters():159 from .filters import FILTERS160 from .asyncfilters import ASYNC_FILTERS161162 FILTERS.update(ASYNC_FILTERS)163164165def patch_all():166 patch_template()167 patch_runtime()168 patch_filters()169170171async def auto_await(value):172 if inspect.isawaitable(value):173 return await value174 return value175176177async def auto_aiter(iterable):178 if hasattr(iterable, "__aiter__"):179 async for item in iterable:180 yield item181 return182 for item in iterable:183 yield item184185186class AsyncLoopContext(LoopContext):187 _to_iterator = staticmethod(auto_aiter)188189 @property190 async def length(self):191 if self._length is not None:192 return self._length193194 try:195 self._length = len(self._iterable)196 except TypeError:197 iterable = [x async for x in self._iterator]198 self._iterator = self._to_iterator(iterable)199 self._length = len(iterable) + self.index + (self._after is not missing)200201 return self._length202203 @property204 async def revindex0(self):205 return await self.length - self.index206207 @property208 async def revindex(self):209 return await self.length - self.index0210211 async def _peek_next(self):212 if self._after is not missing:213 return self._after214215 try:216 self._after = await self._iterator.__anext__()217 except StopAsyncIteration:218 self._after = missing219220 return self._after221222 @property223 async def last(self):224 return await self._peek_next() is missing225226 @property227 async def nextitem(self):228 rv = await self._peek_next()229230 if rv is missing:231 return self._undefined("there is no next item")232233 return rv234235 def __aiter__(self):236 return self237238 async def __anext__(self):239 if self._after is not missing:240 rv = self._after241 self._after = missing242 else:243 rv = await self._iterator.__anext__()244245 self.index0 += 1246 self._before = self._current247 self._current = rv248 return rv, self249250251async def make_async_loop_context(iterable, undefined, recurse=None, depth0=0):252 import warnings253254 warnings.warn(255 "This template must be recompiled with at least Jinja 2.11, or"256 " it will fail in 3.0.",257 DeprecationWarning,258 stacklevel=2,259 )260 return AsyncLoopContext(iterable, undefined, recurse, depth0)261262263patch_all()
deleted:src/jinja2/bccache.py-353 removed
1# -*- coding: utf-8 -*-2"""The optional bytecode cache system. This is useful if you have very3complex template situations and the compilation of all those templates4slows down your application too much.56Situations where this is useful are often forking web applications that7are initialized on the first request.8"""9import errno10import fnmatch11import os12import stat13import sys14import tempfile15from hashlib import sha116from os import listdir17from os import path1819from ._compat import BytesIO20from ._compat import marshal_dump21from ._compat import marshal_load22from ._compat import pickle23from ._compat import text_type24from .utils import open_if_exists2526bc_version = 32728# magic version used to only change with new jinja versions. With 2.629# we change this to also take Python version changes into account. The30# reason for this is that Python tends to segfault if fed earlier bytecode31# versions because someone thought it would be a good idea to reuse opcodes32# or make Python incompatible with earlier versions.33bc_magic = (34 "j2".encode("ascii")35 + pickle.dumps(bc_version, 2)36 + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1])37)383940class Bucket(object):41 """Buckets are used to store the bytecode for one template. It's created42 and initialized by the bytecode cache and passed to the loading functions.4344 The buckets get an internal checksum from the cache assigned and use this45 to automatically reject outdated cache material. Individual bytecode46 cache subclasses don't have to care about cache invalidation.47 """4849 def __init__(self, environment, key, checksum):50 self.environment = environment51 self.key = key52 self.checksum = checksum53 self.reset()5455 def reset(self):56 """Resets the bucket (unloads the bytecode)."""57 self.code = None5859 def load_bytecode(self, f):60 """Loads bytecode from a file or file like object."""61 # make sure the magic header is correct62 magic = f.read(len(bc_magic))63 if magic != bc_magic:64 self.reset()65 return66 # the source code of the file changed, we need to reload67 checksum = pickle.load(f)68 if self.checksum != checksum:69 self.reset()70 return71 # if marshal_load fails then we need to reload72 try:73 self.code = marshal_load(f)74 except (EOFError, ValueError, TypeError):75 self.reset()76 return7778 def write_bytecode(self, f):79 """Dump the bytecode into the file or file like object passed."""80 if self.code is None:81 raise TypeError("can't write empty bucket")82 f.write(bc_magic)83 pickle.dump(self.checksum, f, 2)84 marshal_dump(self.code, f)8586 def bytecode_from_string(self, string):87 """Load bytecode from a string."""88 self.load_bytecode(BytesIO(string))8990 def bytecode_to_string(self):91 """Return the bytecode as string."""92 out = BytesIO()93 self.write_bytecode(out)94 return out.getvalue()959697class BytecodeCache(object):98 """To implement your own bytecode cache you have to subclass this class99 and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of100 these methods are passed a :class:`~jinja2.bccache.Bucket`.101102 A very basic bytecode cache that saves the bytecode on the file system::103104 from os import path105106 class MyCache(BytecodeCache):107108 def __init__(self, directory):109 self.directory = directory110111 def load_bytecode(self, bucket):112 filename = path.join(self.directory, bucket.key)113 if path.exists(filename):114 with open(filename, 'rb') as f:115 bucket.load_bytecode(f)116117 def dump_bytecode(self, bucket):118 filename = path.join(self.directory, bucket.key)119 with open(filename, 'wb') as f:120 bucket.write_bytecode(f)121122 A more advanced version of a filesystem based bytecode cache is part of123 Jinja.124 """125126 def load_bytecode(self, bucket):127 """Subclasses have to override this method to load bytecode into a128 bucket. If they are not able to find code in the cache for the129 bucket, it must not do anything.130 """131 raise NotImplementedError()132133 def dump_bytecode(self, bucket):134 """Subclasses have to override this method to write the bytecode135 from a bucket back to the cache. If it unable to do so it must not136 fail silently but raise an exception.137 """138 raise NotImplementedError()139140 def clear(self):141 """Clears the cache. This method is not used by Jinja but should be142 implemented to allow applications to clear the bytecode cache used143 by a particular environment.144 """145146 def get_cache_key(self, name, filename=None):147 """Returns the unique hash key for this template name."""148 hash = sha1(name.encode("utf-8"))149 if filename is not None:150 filename = "|" + filename151 if isinstance(filename, text_type):152 filename = filename.encode("utf-8")153 hash.update(filename)154 return hash.hexdigest()155156 def get_source_checksum(self, source):157 """Returns a checksum for the source."""158 return sha1(source.encode("utf-8")).hexdigest()159160 def get_bucket(self, environment, name, filename, source):161 """Return a cache bucket for the given template. All arguments are162 mandatory but filename may be `None`.163 """164 key = self.get_cache_key(name, filename)165 checksum = self.get_source_checksum(source)166 bucket = Bucket(environment, key, checksum)167 self.load_bytecode(bucket)168 return bucket169170 def set_bucket(self, bucket):171 """Put the bucket into the cache."""172 self.dump_bytecode(bucket)173174175class FileSystemBytecodeCache(BytecodeCache):176 """A bytecode cache that stores bytecode on the filesystem. It accepts177 two arguments: The directory where the cache items are stored and a178 pattern string that is used to build the filename.179180 If no directory is specified a default cache directory is selected. On181 Windows the user's temp directory is used, on UNIX systems a directory182 is created for the user in the system temp directory.183184 The pattern can be used to have multiple separate caches operate on the185 same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``186 is replaced with the cache key.187188 >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')189190 This bytecode cache supports clearing of the cache using the clear method.191 """192193 def __init__(self, directory=None, pattern="__jinja2_%s.cache"):194 if directory is None:195 directory = self._get_default_cache_dir()196 self.directory = directory197 self.pattern = pattern198199 def _get_default_cache_dir(self):200 def _unsafe_dir():201 raise RuntimeError(202 "Cannot determine safe temp directory. You "203 "need to explicitly provide one."204 )205206 tmpdir = tempfile.gettempdir()207208 # On windows the temporary directory is used specific unless209 # explicitly forced otherwise. We can just use that.210 if os.name == "nt":211 return tmpdir212 if not hasattr(os, "getuid"):213 _unsafe_dir()214215 dirname = "_jinja2-cache-%d" % os.getuid()216 actual_dir = os.path.join(tmpdir, dirname)217218 try:219 os.mkdir(actual_dir, stat.S_IRWXU)220 except OSError as e:221 if e.errno != errno.EEXIST:222 raise223 try:224 os.chmod(actual_dir, stat.S_IRWXU)225 actual_dir_stat = os.lstat(actual_dir)226 if (227 actual_dir_stat.st_uid != os.getuid()228 or not stat.S_ISDIR(actual_dir_stat.st_mode)229 or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU230 ):231 _unsafe_dir()232 except OSError as e:233 if e.errno != errno.EEXIST:234 raise235236 actual_dir_stat = os.lstat(actual_dir)237 if (238 actual_dir_stat.st_uid != os.getuid()239 or not stat.S_ISDIR(actual_dir_stat.st_mode)240 or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU241 ):242 _unsafe_dir()243244 return actual_dir245246 def _get_cache_filename(self, bucket):247 return path.join(self.directory, self.pattern % bucket.key)248249 def load_bytecode(self, bucket):250 f = open_if_exists(self._get_cache_filename(bucket), "rb")251 if f is not None:252 try:253 bucket.load_bytecode(f)254 finally:255 f.close()256257 def dump_bytecode(self, bucket):258 f = open(self._get_cache_filename(bucket), "wb")259 try:260 bucket.write_bytecode(f)261 finally:262 f.close()263264 def clear(self):265 # imported lazily here because google app-engine doesn't support266 # write access on the file system and the function does not exist267 # normally.268 from os import remove269270 files = fnmatch.filter(listdir(self.directory), self.pattern % "*")271 for filename in files:272 try:273 remove(path.join(self.directory, filename))274 except OSError:275 pass276277278class MemcachedBytecodeCache(BytecodeCache):279 """This class implements a bytecode cache that uses a memcache cache for280 storing the information. It does not enforce a specific memcache library281 (tummy's memcache or cmemcache) but will accept any class that provides282 the minimal interface required.283284 Libraries compatible with this class:285286 - `cachelib <https://github.com/pallets/cachelib>`_287 - `python-memcached <https://pypi.org/project/python-memcached/>`_288289 (Unfortunately the django cache interface is not compatible because it290 does not support storing binary data, only unicode. You can however pass291 the underlying cache client to the bytecode cache which is available292 as `django.core.cache.cache._client`.)293294 The minimal interface for the client passed to the constructor is this:295296 .. class:: MinimalClientInterface297298 .. method:: set(key, value[, timeout])299300 Stores the bytecode in the cache. `value` is a string and301 `timeout` the timeout of the key. If timeout is not provided302 a default timeout or no timeout should be assumed, if it's303 provided it's an integer with the number of seconds the cache304 item should exist.305306 .. method:: get(key)307308 Returns the value for the cache key. If the item does not309 exist in the cache the return value must be `None`.310311 The other arguments to the constructor are the prefix for all keys that312 is added before the actual cache key and the timeout for the bytecode in313 the cache system. We recommend a high (or no) timeout.314315 This bytecode cache does not support clearing of used items in the cache.316 The clear method is a no-operation function.317318 .. versionadded:: 2.7319 Added support for ignoring memcache errors through the320 `ignore_memcache_errors` parameter.321 """322323 def __init__(324 self,325 client,326 prefix="jinja2/bytecode/",327 timeout=None,328 ignore_memcache_errors=True,329 ):330 self.client = client331 self.prefix = prefix332 self.timeout = timeout333 self.ignore_memcache_errors = ignore_memcache_errors334335 def load_bytecode(self, bucket):336 try:337 code = self.client.get(self.prefix + bucket.key)338 except Exception:339 if not self.ignore_memcache_errors:340 raise341 code = None342 if code is not None:343 bucket.bytecode_from_string(code)344345 def dump_bytecode(self, bucket):346 args = (self.prefix + bucket.key, bucket.bytecode_to_string())347 if self.timeout is not None:348 args += (self.timeout,)349 try:350 self.client.set(*args)351 except Exception:352 if not self.ignore_memcache_errors:353 raise
deleted:src/jinja2/compiler.py-1842 removed
1# -*- coding: utf-8 -*-2"""Compiles nodes from the parser into Python code."""3from collections import namedtuple4from functools import update_wrapper5from itertools import chain6from keyword import iskeyword as is_python_keyword78from . import nodes9from ._compat import imap10from ._compat import iteritems11from ._compat import izip12from ._compat import NativeStringIO13from ._compat import range_type14from ._compat import string_types15from ._compat import text_type16from .exceptions import TemplateAssertionError17from .idtracking import Symbols18from .idtracking import VAR_LOAD_ALIAS19from .idtracking import VAR_LOAD_PARAMETER20from .idtracking import VAR_LOAD_RESOLVE21from .idtracking import VAR_LOAD_UNDEFINED22from .nodes import EvalContext23from .optimizer import Optimizer24from .utils import concat25from .utils import escape26from .utils import Markup27from .visitor import NodeVisitor2829operators = {30 "eq": "==",31 "ne": "!=",32 "gt": ">",33 "gteq": ">=",34 "lt": "<",35 "lteq": "<=",36 "in": "in",37 "notin": "not in",38}3940# what method to iterate over items do we want to use for dict iteration41# in generated code? on 2.x let's go with iteritems, on 3.x with items42if hasattr(dict, "iteritems"):43 dict_item_iter = "iteritems"44else:45 dict_item_iter = "items"4647code_features = ["division"]4849# does this python version support generator stops? (PEP 0479)50try:51 exec("from __future__ import generator_stop")52 code_features.append("generator_stop")53except SyntaxError:54 pass5556# does this python version support yield from?57try:58 exec("def f(): yield from x()")59except SyntaxError:60 supports_yield_from = False61else:62 supports_yield_from = True636465def optimizeconst(f):66 def new_func(self, node, frame, **kwargs):67 # Only optimize if the frame is not volatile68 if self.optimized and not frame.eval_ctx.volatile:69 new_node = self.optimizer.visit(node, frame.eval_ctx)70 if new_node != node:71 return self.visit(new_node, frame)72 return f(self, node, frame, **kwargs)7374 return update_wrapper(new_func, f)757677def generate(78 node, environment, name, filename, stream=None, defer_init=False, optimized=True79):80 """Generate the python source for a node tree."""81 if not isinstance(node, nodes.Template):82 raise TypeError("Can't compile non template nodes")83 generator = environment.code_generator_class(84 environment, name, filename, stream, defer_init, optimized85 )86 generator.visit(node)87 if stream is None:88 return generator.stream.getvalue()899091def has_safe_repr(value):92 """Does the node have a safe representation?"""93 if value is None or value is NotImplemented or value is Ellipsis:94 return True95 if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:96 return True97 if type(value) in (tuple, list, set, frozenset):98 for item in value:99 if not has_safe_repr(item):100 return False101 return True102 elif type(value) is dict:103 for key, value in iteritems(value):104 if not has_safe_repr(key):105 return False106 if not has_safe_repr(value):107 return False108 return True109 return False110111112def find_undeclared(nodes, names):113 """Check if the names passed are accessed undeclared. The return value114 is a set of all the undeclared names from the sequence of names found.115 """116 visitor = UndeclaredNameVisitor(names)117 try:118 for node in nodes:119 visitor.visit(node)120 except VisitorExit:121 pass122 return visitor.undeclared123124125class MacroRef(object):126 def __init__(self, node):127 self.node = node128 self.accesses_caller = False129 self.accesses_kwargs = False130 self.accesses_varargs = False131132133class Frame(object):134 """Holds compile time information for us."""135136 def __init__(self, eval_ctx, parent=None, level=None):137 self.eval_ctx = eval_ctx138 self.symbols = Symbols(parent and parent.symbols or None, level=level)139140 # a toplevel frame is the root + soft frames such as if conditions.141 self.toplevel = False142143 # the root frame is basically just the outermost frame, so no if144 # conditions. This information is used to optimize inheritance145 # situations.146 self.rootlevel = False147148 # in some dynamic inheritance situations the compiler needs to add149 # write tests around output statements.150 self.require_output_check = parent and parent.require_output_check151152 # inside some tags we are using a buffer rather than yield statements.153 # this for example affects {% filter %} or {% macro %}. If a frame154 # is buffered this variable points to the name of the list used as155 # buffer.156 self.buffer = None157158 # the name of the block we're in, otherwise None.159 self.block = parent and parent.block or None160161 # the parent of this frame162 self.parent = parent163164 if parent is not None:165 self.buffer = parent.buffer166167 def copy(self):168 """Create a copy of the current one."""169 rv = object.__new__(self.__class__)170 rv.__dict__.update(self.__dict__)171 rv.symbols = self.symbols.copy()172 return rv173174 def inner(self, isolated=False):175 """Return an inner frame."""176 if isolated:177 return Frame(self.eval_ctx, level=self.symbols.level + 1)178 return Frame(self.eval_ctx, self)179180 def soft(self):181 """Return a soft frame. A soft frame may not be modified as182 standalone thing as it shares the resources with the frame it183 was created of, but it's not a rootlevel frame any longer.184185 This is only used to implement if-statements.186 """187 rv = self.copy()188 rv.rootlevel = False189 return rv190191 __copy__ = copy192193194class VisitorExit(RuntimeError):195 """Exception used by the `UndeclaredNameVisitor` to signal a stop."""196197198class DependencyFinderVisitor(NodeVisitor):199 """A visitor that collects filter and test calls."""200201 def __init__(self):202 self.filters = set()203 self.tests = set()204205 def visit_Filter(self, node):206 self.generic_visit(node)207 self.filters.add(node.name)208209 def visit_Test(self, node):210 self.generic_visit(node)211 self.tests.add(node.name)212213 def visit_Block(self, node):214 """Stop visiting at blocks."""215216217class UndeclaredNameVisitor(NodeVisitor):218 """A visitor that checks if a name is accessed without being219 declared. This is different from the frame visitor as it will220 not stop at closure frames.221 """222223 def __init__(self, names):224 self.names = set(names)225 self.undeclared = set()226227 def visit_Name(self, node):228 if node.ctx == "load" and node.name in self.names:229 self.undeclared.add(node.name)230 if self.undeclared == self.names:231 raise VisitorExit()232 else:233 self.names.discard(node.name)234235 def visit_Block(self, node):236 """Stop visiting a blocks."""237238239class CompilerExit(Exception):240 """Raised if the compiler encountered a situation where it just241 doesn't make sense to further process the code. Any block that242 raises such an exception is not further processed.243 """244245246class CodeGenerator(NodeVisitor):247 def __init__(248 self, environment, name, filename, stream=None, defer_init=False, optimized=True249 ):250 if stream is None:251 stream = NativeStringIO()252 self.environment = environment253 self.name = name254 self.filename = filename255 self.stream = stream256 self.created_block_context = False257 self.defer_init = defer_init258 self.optimized = optimized259 if optimized:260 self.optimizer = Optimizer(environment)261262 # aliases for imports263 self.import_aliases = {}264265 # a registry for all blocks. Because blocks are moved out266 # into the global python scope they are registered here267 self.blocks = {}268269 # the number of extends statements so far270 self.extends_so_far = 0271272 # some templates have a rootlevel extends. In this case we273 # can safely assume that we're a child template and do some274 # more optimizations.275 self.has_known_extends = False276277 # the current line number278 self.code_lineno = 1279280 # registry of all filters and tests (global, not block local)281 self.tests = {}282 self.filters = {}283284 # the debug information285 self.debug_info = []286 self._write_debug_info = None287288 # the number of new lines before the next write()289 self._new_lines = 0290291 # the line number of the last written statement292 self._last_line = 0293294 # true if nothing was written so far.295 self._first_write = True296297 # used by the `temporary_identifier` method to get new298 # unique, temporary identifier299 self._last_identifier = 0300301 # the current indentation302 self._indentation = 0303304 # Tracks toplevel assignments305 self._assign_stack = []306307 # Tracks parameter definition blocks308 self._param_def_block = []309310 # Tracks the current context.311 self._context_reference_stack = ["context"]312313 # -- Various compilation helpers314315 def fail(self, msg, lineno):316 """Fail with a :exc:`TemplateAssertionError`."""317 raise TemplateAssertionError(msg, lineno, self.name, self.filename)318319 def temporary_identifier(self):320 """Get a new unique identifier."""321 self._last_identifier += 1322 return "t_%d" % self._last_identifier323324 def buffer(self, frame):325 """Enable buffering for the frame from that point onwards."""326 frame.buffer = self.temporary_identifier()327 self.writeline("%s = []" % frame.buffer)328329 def return_buffer_contents(self, frame, force_unescaped=False):330 """Return the buffer contents of the frame."""331 if not force_unescaped:332 if frame.eval_ctx.volatile:333 self.writeline("if context.eval_ctx.autoescape:")334 self.indent()335 self.writeline("return Markup(concat(%s))" % frame.buffer)336 self.outdent()337 self.writeline("else:")338 self.indent()339 self.writeline("return concat(%s)" % frame.buffer)340 self.outdent()341 return342 elif frame.eval_ctx.autoescape:343 self.writeline("return Markup(concat(%s))" % frame.buffer)344 return345 self.writeline("return concat(%s)" % frame.buffer)346347 def indent(self):348 """Indent by one."""349 self._indentation += 1350351 def outdent(self, step=1):352 """Outdent by step."""353 self._indentation -= step354355 def start_write(self, frame, node=None):356 """Yield or write into the frame buffer."""357 if frame.buffer is None:358 self.writeline("yield ", node)359 else:360 self.writeline("%s.append(" % frame.buffer, node)361362 def end_write(self, frame):363 """End the writing process started by `start_write`."""364 if frame.buffer is not None:365 self.write(")")366367 def simple_write(self, s, frame, node=None):368 """Simple shortcut for start_write + write + end_write."""369 self.start_write(frame, node)370 self.write(s)371 self.end_write(frame)372373 def blockvisit(self, nodes, frame):374 """Visit a list of nodes as block in a frame. If the current frame375 is no buffer a dummy ``if 0: yield None`` is written automatically.376 """377 try:378 self.writeline("pass")379 for node in nodes:380 self.visit(node, frame)381 except CompilerExit:382 pass383384 def write(self, x):385 """Write a string into the output stream."""386 if self._new_lines:387 if not self._first_write:388 self.stream.write("\n" * self._new_lines)389 self.code_lineno += self._new_lines390 if self._write_debug_info is not None:391 self.debug_info.append((self._write_debug_info, self.code_lineno))392 self._write_debug_info = None393 self._first_write = False394 self.stream.write(" " * self._indentation)395 self._new_lines = 0396 self.stream.write(x)397398 def writeline(self, x, node=None, extra=0):399 """Combination of newline and write."""400 self.newline(node, extra)401 self.write(x)402403 def newline(self, node=None, extra=0):404 """Add one or more newlines before the next write."""405 self._new_lines = max(self._new_lines, 1 + extra)406 if node is not None and node.lineno != self._last_line:407 self._write_debug_info = node.lineno408 self._last_line = node.lineno409410 def signature(self, node, frame, extra_kwargs=None):411 """Writes a function call to the stream for the current node.412 A leading comma is added automatically. The extra keyword413 arguments may not include python keywords otherwise a syntax414 error could occur. The extra keyword arguments should be given415 as python dict.416 """417 # if any of the given keyword arguments is a python keyword418 # we have to make sure that no invalid call is created.419 kwarg_workaround = False420 for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):421 if is_python_keyword(kwarg):422 kwarg_workaround = True423 break424425 for arg in node.args:426 self.write(", ")427 self.visit(arg, frame)428429 if not kwarg_workaround:430 for kwarg in node.kwargs:431 self.write(", ")432 self.visit(kwarg, frame)433 if extra_kwargs is not None:434 for key, value in iteritems(extra_kwargs):435 self.write(", %s=%s" % (key, value))436 if node.dyn_args:437 self.write(", *")438 self.visit(node.dyn_args, frame)439440 if kwarg_workaround:441 if node.dyn_kwargs is not None:442 self.write(", **dict({")443 else:444 self.write(", **{")445 for kwarg in node.kwargs:446 self.write("%r: " % kwarg.key)447 self.visit(kwarg.value, frame)448 self.write(", ")449 if extra_kwargs is not None:450 for key, value in iteritems(extra_kwargs):451 self.write("%r: %s, " % (key, value))452 if node.dyn_kwargs is not None:453 self.write("}, **")454 self.visit(node.dyn_kwargs, frame)455 self.write(")")456 else:457 self.write("}")458459 elif node.dyn_kwargs is not None:460 self.write(", **")461 self.visit(node.dyn_kwargs, frame)462463 def pull_dependencies(self, nodes):464 """Pull all the dependencies."""465 visitor = DependencyFinderVisitor()466 for node in nodes:467 visitor.visit(node)468 for dependency in "filters", "tests":469 mapping = getattr(self, dependency)470 for name in getattr(visitor, dependency):471 if name not in mapping:472 mapping[name] = self.temporary_identifier()473 self.writeline(474 "%s = environment.%s[%r]" % (mapping[name], dependency, name)475 )476477 def enter_frame(self, frame):478 undefs = []479 for target, (action, param) in iteritems(frame.symbols.loads):480 if action == VAR_LOAD_PARAMETER:481 pass482 elif action == VAR_LOAD_RESOLVE:483 self.writeline("%s = %s(%r)" % (target, self.get_resolve_func(), param))484 elif action == VAR_LOAD_ALIAS:485 self.writeline("%s = %s" % (target, param))486 elif action == VAR_LOAD_UNDEFINED:487 undefs.append(target)488 else:489 raise NotImplementedError("unknown load instruction")490 if undefs:491 self.writeline("%s = missing" % " = ".join(undefs))492493 def leave_frame(self, frame, with_python_scope=False):494 if not with_python_scope:495 undefs = []496 for target, _ in iteritems(frame.symbols.loads):497 undefs.append(target)498 if undefs:499 self.writeline("%s = missing" % " = ".join(undefs))500501 def func(self, name):502 if self.environment.is_async:503 return "async def %s" % name504 return "def %s" % name505506 def macro_body(self, node, frame):507 """Dump the function def of a macro or call block."""508 frame = frame.inner()509 frame.symbols.analyze_node(node)510 macro_ref = MacroRef(node)511512 explicit_caller = None513 skip_special_params = set()514 args = []515 for idx, arg in enumerate(node.args):516 if arg.name == "caller":517 explicit_caller = idx518 if arg.name in ("kwargs", "varargs"):519 skip_special_params.add(arg.name)520 args.append(frame.symbols.ref(arg.name))521522 undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs"))523524 if "caller" in undeclared:525 # In older Jinja versions there was a bug that allowed caller526 # to retain the special behavior even if it was mentioned in527 # the argument list. However thankfully this was only really528 # working if it was the last argument. So we are explicitly529 # checking this now and error out if it is anywhere else in530 # the argument list.531 if explicit_caller is not None:532 try:533 node.defaults[explicit_caller - len(node.args)]534 except IndexError:535 self.fail(536 "When defining macros or call blocks the "537 'special "caller" argument must be omitted '538 "or be given a default.",539 node.lineno,540 )541 else:542 args.append(frame.symbols.declare_parameter("caller"))543 macro_ref.accesses_caller = True544 if "kwargs" in undeclared and "kwargs" not in skip_special_params:545 args.append(frame.symbols.declare_parameter("kwargs"))546 macro_ref.accesses_kwargs = True547 if "varargs" in undeclared and "varargs" not in skip_special_params:548 args.append(frame.symbols.declare_parameter("varargs"))549 macro_ref.accesses_varargs = True550551 # macros are delayed, they never require output checks552 frame.require_output_check = False553 frame.symbols.analyze_node(node)554 self.writeline("%s(%s):" % (self.func("macro"), ", ".join(args)), node)555 self.indent()556557 self.buffer(frame)558 self.enter_frame(frame)559560 self.push_parameter_definitions(frame)561 for idx, arg in enumerate(node.args):562 ref = frame.symbols.ref(arg.name)563 self.writeline("if %s is missing:" % ref)564 self.indent()565 try:566 default = node.defaults[idx - len(node.args)]567 except IndexError:568 self.writeline(569 "%s = undefined(%r, name=%r)"570 % (ref, "parameter %r was not provided" % arg.name, arg.name)571 )572 else:573 self.writeline("%s = " % ref)574 self.visit(default, frame)575 self.mark_parameter_stored(ref)576 self.outdent()577 self.pop_parameter_definitions()578579 self.blockvisit(node.body, frame)580 self.return_buffer_contents(frame, force_unescaped=True)581 self.leave_frame(frame, with_python_scope=True)582 self.outdent()583584 return frame, macro_ref585586 def macro_def(self, macro_ref, frame):587 """Dump the macro definition for the def created by macro_body."""588 arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args)589 name = getattr(macro_ref.node, "name", None)590 if len(macro_ref.node.args) == 1:591 arg_tuple += ","592 self.write(593 "Macro(environment, macro, %r, (%s), %r, %r, %r, "594 "context.eval_ctx.autoescape)"595 % (596 name,597 arg_tuple,598 macro_ref.accesses_kwargs,599 macro_ref.accesses_varargs,600 macro_ref.accesses_caller,601 )602 )603604 def position(self, node):605 """Return a human readable position for the node."""606 rv = "line %d" % node.lineno607 if self.name is not None:608 rv += " in " + repr(self.name)609 return rv610611 def dump_local_context(self, frame):612 return "{%s}" % ", ".join(613 "%r: %s" % (name, target)614 for name, target in iteritems(frame.symbols.dump_stores())615 )616617 def write_commons(self):618 """Writes a common preamble that is used by root and block functions.619 Primarily this sets up common local helpers and enforces a generator620 through a dead branch.621 """622 self.writeline("resolve = context.resolve_or_missing")623 self.writeline("undefined = environment.undefined")624 # always use the standard Undefined class for the implicit else of625 # conditional expressions626 self.writeline("cond_expr_undefined = Undefined")627 self.writeline("if 0: yield None")628629 def push_parameter_definitions(self, frame):630 """Pushes all parameter targets from the given frame into a local631 stack that permits tracking of yet to be assigned parameters. In632 particular this enables the optimization from `visit_Name` to skip633 undefined expressions for parameters in macros as macros can reference634 otherwise unbound parameters.635 """636 self._param_def_block.append(frame.symbols.dump_param_targets())637638 def pop_parameter_definitions(self):639 """Pops the current parameter definitions set."""640 self._param_def_block.pop()641642 def mark_parameter_stored(self, target):643 """Marks a parameter in the current parameter definitions as stored.644 This will skip the enforced undefined checks.645 """646 if self._param_def_block:647 self._param_def_block[-1].discard(target)648649 def push_context_reference(self, target):650 self._context_reference_stack.append(target)651652 def pop_context_reference(self):653 self._context_reference_stack.pop()654655 def get_context_ref(self):656 return self._context_reference_stack[-1]657658 def get_resolve_func(self):659 target = self._context_reference_stack[-1]660 if target == "context":661 return "resolve"662 return "%s.resolve" % target663664 def derive_context(self, frame):665 return "%s.derived(%s)" % (666 self.get_context_ref(),667 self.dump_local_context(frame),668 )669670 def parameter_is_undeclared(self, target):671 """Checks if a given target is an undeclared parameter."""672 if not self._param_def_block:673 return False674 return target in self._param_def_block[-1]675676 def push_assign_tracking(self):677 """Pushes a new layer for assignment tracking."""678 self._assign_stack.append(set())679680 def pop_assign_tracking(self, frame):681 """Pops the topmost level for assignment tracking and updates the682 context variables if necessary.683 """684 vars = self._assign_stack.pop()685 if not frame.toplevel or not vars:686 return687 public_names = [x for x in vars if x[:1] != "_"]688 if len(vars) == 1:689 name = next(iter(vars))690 ref = frame.symbols.ref(name)691 self.writeline("context.vars[%r] = %s" % (name, ref))692 else:693 self.writeline("context.vars.update({")694 for idx, name in enumerate(vars):695 if idx:696 self.write(", ")697 ref = frame.symbols.ref(name)698 self.write("%r: %s" % (name, ref))699 self.write("})")700 if public_names:701 if len(public_names) == 1:702 self.writeline("context.exported_vars.add(%r)" % public_names[0])703 else:704 self.writeline(705 "context.exported_vars.update((%s))"706 % ", ".join(imap(repr, public_names))707 )708709 # -- Statement Visitors710711 def visit_Template(self, node, frame=None):712 assert frame is None, "no root frame allowed"713 eval_ctx = EvalContext(self.environment, self.name)714715 from .runtime import __all__ as exported716717 self.writeline("from __future__ import %s" % ", ".join(code_features))718 self.writeline("from jinja2.runtime import " + ", ".join(exported))719720 if self.environment.is_async:721 self.writeline(722 "from jinja2.asyncsupport import auto_await, "723 "auto_aiter, AsyncLoopContext"724 )725726 # if we want a deferred initialization we cannot move the727 # environment into a local name728 envenv = not self.defer_init and ", environment=environment" or ""729730 # do we have an extends tag at all? If not, we can save some731 # overhead by just not processing any inheritance code.732 have_extends = node.find(nodes.Extends) is not None733734 # find all blocks735 for block in node.find_all(nodes.Block):736 if block.name in self.blocks:737 self.fail("block %r defined twice" % block.name, block.lineno)738 self.blocks[block.name] = block739740 # find all imports and import them741 for import_ in node.find_all(nodes.ImportedName):742 if import_.importname not in self.import_aliases:743 imp = import_.importname744 self.import_aliases[imp] = alias = self.temporary_identifier()745 if "." in imp:746 module, obj = imp.rsplit(".", 1)747 self.writeline("from %s import %s as %s" % (module, obj, alias))748 else:749 self.writeline("import %s as %s" % (imp, alias))750751 # add the load name752 self.writeline("name = %r" % self.name)753754 # generate the root render function.755 self.writeline(756 "%s(context, missing=missing%s):" % (self.func("root"), envenv), extra=1757 )758 self.indent()759 self.write_commons()760761 # process the root762 frame = Frame(eval_ctx)763 if "self" in find_undeclared(node.body, ("self",)):764 ref = frame.symbols.declare_parameter("self")765 self.writeline("%s = TemplateReference(context)" % ref)766 frame.symbols.analyze_node(node)767 frame.toplevel = frame.rootlevel = True768 frame.require_output_check = have_extends and not self.has_known_extends769 if have_extends:770 self.writeline("parent_template = None")771 self.enter_frame(frame)772 self.pull_dependencies(node.body)773 self.blockvisit(node.body, frame)774 self.leave_frame(frame, with_python_scope=True)775 self.outdent()776777 # make sure that the parent root is called.778 if have_extends:779 if not self.has_known_extends:780 self.indent()781 self.writeline("if parent_template is not None:")782 self.indent()783 if supports_yield_from and not self.environment.is_async:784 self.writeline("yield from parent_template.root_render_func(context)")785 else:786 self.writeline(787 "%sfor event in parent_template."788 "root_render_func(context):"789 % (self.environment.is_async and "async " or "")790 )791 self.indent()792 self.writeline("yield event")793 self.outdent()794 self.outdent(1 + (not self.has_known_extends))795796 # at this point we now have the blocks collected and can visit them too.797 for name, block in iteritems(self.blocks):798 self.writeline(799 "%s(context, missing=missing%s):"800 % (self.func("block_" + name), envenv),801 block,802 1,803 )804 self.indent()805 self.write_commons()806 # It's important that we do not make this frame a child of the807 # toplevel template. This would cause a variety of808 # interesting issues with identifier tracking.809 block_frame = Frame(eval_ctx)810 undeclared = find_undeclared(block.body, ("self", "super"))811 if "self" in undeclared:812 ref = block_frame.symbols.declare_parameter("self")813 self.writeline("%s = TemplateReference(context)" % ref)814 if "super" in undeclared:815 ref = block_frame.symbols.declare_parameter("super")816 self.writeline("%s = context.super(%r, block_%s)" % (ref, name, name))817 block_frame.symbols.analyze_node(block)818 block_frame.block = name819 self.enter_frame(block_frame)820 self.pull_dependencies(block.body)821 self.blockvisit(block.body, block_frame)822 self.leave_frame(block_frame, with_python_scope=True)823 self.outdent()824825 self.writeline(826 "blocks = {%s}" % ", ".join("%r: block_%s" % (x, x) for x in self.blocks),827 extra=1,828 )829830 # add a function that returns the debug info831 self.writeline(832 "debug_info = %r" % "&".join("%s=%s" % x for x in self.debug_info)833 )834835 def visit_Block(self, node, frame):836 """Call a block and register it for the template."""837 level = 0838 if frame.toplevel:839 # if we know that we are a child template, there is no need to840 # check if we are one841 if self.has_known_extends:842 return843 if self.extends_so_far > 0:844 self.writeline("if parent_template is None:")845 self.indent()846 level += 1847848 if node.scoped:849 context = self.derive_context(frame)850 else:851 context = self.get_context_ref()852853 if (854 supports_yield_from855 and not self.environment.is_async856 and frame.buffer is None857 ):858 self.writeline(859 "yield from context.blocks[%r][0](%s)" % (node.name, context), node860 )861 else:862 loop = self.environment.is_async and "async for" or "for"863 self.writeline(864 "%s event in context.blocks[%r][0](%s):" % (loop, node.name, context),865 node,866 )867 self.indent()868 self.simple_write("event", frame)869 self.outdent()870871 self.outdent(level)872873 def visit_Extends(self, node, frame):874 """Calls the extender."""875 if not frame.toplevel:876 self.fail("cannot use extend from a non top-level scope", node.lineno)877878 # if the number of extends statements in general is zero so879 # far, we don't have to add a check if something extended880 # the template before this one.881 if self.extends_so_far > 0:882883 # if we have a known extends we just add a template runtime884 # error into the generated code. We could catch that at compile885 # time too, but i welcome it not to confuse users by throwing the886 # same error at different times just "because we can".887 if not self.has_known_extends:888 self.writeline("if parent_template is not None:")889 self.indent()890 self.writeline("raise TemplateRuntimeError(%r)" % "extended multiple times")891892 # if we have a known extends already we don't need that code here893 # as we know that the template execution will end here.894 if self.has_known_extends:895 raise CompilerExit()896 else:897 self.outdent()898899 self.writeline("parent_template = environment.get_template(", node)900 self.visit(node.template, frame)901 self.write(", %r)" % self.name)902 self.writeline(903 "for name, parent_block in parent_template.blocks.%s():" % dict_item_iter904 )905 self.indent()906 self.writeline("context.blocks.setdefault(name, []).append(parent_block)")907 self.outdent()908909 # if this extends statement was in the root level we can take910 # advantage of that information and simplify the generated code911 # in the top level from this point onwards912 if frame.rootlevel:913 self.has_known_extends = True914915 # and now we have one more916 self.extends_so_far += 1917918 def visit_Include(self, node, frame):919 """Handles includes."""920 if node.ignore_missing:921 self.writeline("try:")922 self.indent()923924 func_name = "get_or_select_template"925 if isinstance(node.template, nodes.Const):926 if isinstance(node.template.value, string_types):927 func_name = "get_template"928 elif isinstance(node.template.value, (tuple, list)):929 func_name = "select_template"930 elif isinstance(node.template, (nodes.Tuple, nodes.List)):931 func_name = "select_template"932933 self.writeline("template = environment.%s(" % func_name, node)934 self.visit(node.template, frame)935 self.write(", %r)" % self.name)936 if node.ignore_missing:937 self.outdent()938 self.writeline("except TemplateNotFound:")939 self.indent()940 self.writeline("pass")941 self.outdent()942 self.writeline("else:")943 self.indent()944945 skip_event_yield = False946 if node.with_context:947 loop = self.environment.is_async and "async for" or "for"948 self.writeline(949 "%s event in template.root_render_func("950 "template.new_context(context.get_all(), True, "951 "%s)):" % (loop, self.dump_local_context(frame))952 )953 elif self.environment.is_async:954 self.writeline(955 "for event in (await "956 "template._get_default_module_async())"957 "._body_stream:"958 )959 else:960 if supports_yield_from:961 self.writeline("yield from template._get_default_module()._body_stream")962 skip_event_yield = True963 else:964 self.writeline(965 "for event in template._get_default_module()._body_stream:"966 )967968 if not skip_event_yield:969 self.indent()970 self.simple_write("event", frame)971 self.outdent()972973 if node.ignore_missing:974 self.outdent()975976 def visit_Import(self, node, frame):977 """Visit regular imports."""978 self.writeline("%s = " % frame.symbols.ref(node.target), node)979 if frame.toplevel:980 self.write("context.vars[%r] = " % node.target)981 if self.environment.is_async:982 self.write("await ")983 self.write("environment.get_template(")984 self.visit(node.template, frame)985 self.write(", %r)." % self.name)986 if node.with_context:987 self.write(988 "make_module%s(context.get_all(), True, %s)"989 % (990 self.environment.is_async and "_async" or "",991 self.dump_local_context(frame),992 )993 )994 elif self.environment.is_async:995 self.write("_get_default_module_async()")996 else:997 self.write("_get_default_module()")998 if frame.toplevel and not node.target.startswith("_"):999 self.writeline("context.exported_vars.discard(%r)" % node.target)10001001 def visit_FromImport(self, node, frame):1002 """Visit named imports."""1003 self.newline(node)1004 self.write(1005 "included_template = %senvironment.get_template("1006 % (self.environment.is_async and "await " or "")1007 )1008 self.visit(node.template, frame)1009 self.write(", %r)." % self.name)1010 if node.with_context:1011 self.write(1012 "make_module%s(context.get_all(), True, %s)"1013 % (1014 self.environment.is_async and "_async" or "",1015 self.dump_local_context(frame),1016 )1017 )1018 elif self.environment.is_async:1019 self.write("_get_default_module_async()")1020 else:1021 self.write("_get_default_module()")10221023 var_names = []1024 discarded_names = []1025 for name in node.names:1026 if isinstance(name, tuple):1027 name, alias = name1028 else:1029 alias = name1030 self.writeline(1031 "%s = getattr(included_template, "1032 "%r, missing)" % (frame.symbols.ref(alias), name)1033 )1034 self.writeline("if %s is missing:" % frame.symbols.ref(alias))1035 self.indent()1036 self.writeline(1037 "%s = undefined(%r %% "1038 "included_template.__name__, "1039 "name=%r)"1040 % (1041 frame.symbols.ref(alias),1042 "the template %%r (imported on %s) does "1043 "not export the requested name %s"1044 % (self.position(node), repr(name)),1045 name,1046 )1047 )1048 self.outdent()1049 if frame.toplevel:1050 var_names.append(alias)1051 if not alias.startswith("_"):1052 discarded_names.append(alias)10531054 if var_names:1055 if len(var_names) == 1:1056 name = var_names[0]1057 self.writeline(1058 "context.vars[%r] = %s" % (name, frame.symbols.ref(name))1059 )1060 else:1061 self.writeline(1062 "context.vars.update({%s})"1063 % ", ".join(1064 "%r: %s" % (name, frame.symbols.ref(name)) for name in var_names1065 )1066 )1067 if discarded_names:1068 if len(discarded_names) == 1:1069 self.writeline("context.exported_vars.discard(%r)" % discarded_names[0])1070 else:1071 self.writeline(1072 "context.exported_vars.difference_"1073 "update((%s))" % ", ".join(imap(repr, discarded_names))1074 )10751076 def visit_For(self, node, frame):1077 loop_frame = frame.inner()1078 test_frame = frame.inner()1079 else_frame = frame.inner()10801081 # try to figure out if we have an extended loop. An extended loop1082 # is necessary if the loop is in recursive mode if the special loop1083 # variable is accessed in the body.1084 extended_loop = node.recursive or "loop" in find_undeclared(1085 node.iter_child_nodes(only=("body",)), ("loop",)1086 )10871088 loop_ref = None1089 if extended_loop:1090 loop_ref = loop_frame.symbols.declare_parameter("loop")10911092 loop_frame.symbols.analyze_node(node, for_branch="body")1093 if node.else_:1094 else_frame.symbols.analyze_node(node, for_branch="else")10951096 if node.test:1097 loop_filter_func = self.temporary_identifier()1098 test_frame.symbols.analyze_node(node, for_branch="test")1099 self.writeline("%s(fiter):" % self.func(loop_filter_func), node.test)1100 self.indent()1101 self.enter_frame(test_frame)1102 self.writeline(self.environment.is_async and "async for " or "for ")1103 self.visit(node.target, loop_frame)1104 self.write(" in ")1105 self.write(self.environment.is_async and "auto_aiter(fiter)" or "fiter")1106 self.write(":")1107 self.indent()1108 self.writeline("if ", node.test)1109 self.visit(node.test, test_frame)1110 self.write(":")1111 self.indent()1112 self.writeline("yield ")1113 self.visit(node.target, loop_frame)1114 self.outdent(3)1115 self.leave_frame(test_frame, with_python_scope=True)11161117 # if we don't have an recursive loop we have to find the shadowed1118 # variables at that point. Because loops can be nested but the loop1119 # variable is a special one we have to enforce aliasing for it.1120 if node.recursive:1121 self.writeline(1122 "%s(reciter, loop_render_func, depth=0):" % self.func("loop"), node1123 )1124 self.indent()1125 self.buffer(loop_frame)11261127 # Use the same buffer for the else frame1128 else_frame.buffer = loop_frame.buffer11291130 # make sure the loop variable is a special one and raise a template1131 # assertion error if a loop tries to write to loop1132 if extended_loop:1133 self.writeline("%s = missing" % loop_ref)11341135 for name in node.find_all(nodes.Name):1136 if name.ctx == "store" and name.name == "loop":1137 self.fail(1138 "Can't assign to special loop variable in for-loop target",1139 name.lineno,1140 )11411142 if node.else_:1143 iteration_indicator = self.temporary_identifier()1144 self.writeline("%s = 1" % iteration_indicator)11451146 self.writeline(self.environment.is_async and "async for " or "for ", node)1147 self.visit(node.target, loop_frame)1148 if extended_loop:1149 if self.environment.is_async:1150 self.write(", %s in AsyncLoopContext(" % loop_ref)1151 else:1152 self.write(", %s in LoopContext(" % loop_ref)1153 else:1154 self.write(" in ")11551156 if node.test:1157 self.write("%s(" % loop_filter_func)1158 if node.recursive:1159 self.write("reciter")1160 else:1161 if self.environment.is_async and not extended_loop:1162 self.write("auto_aiter(")1163 self.visit(node.iter, frame)1164 if self.environment.is_async and not extended_loop:1165 self.write(")")1166 if node.test:1167 self.write(")")11681169 if node.recursive:1170 self.write(", undefined, loop_render_func, depth):")1171 else:1172 self.write(extended_loop and ", undefined):" or ":")11731174 self.indent()1175 self.enter_frame(loop_frame)11761177 self.blockvisit(node.body, loop_frame)1178 if node.else_:1179 self.writeline("%s = 0" % iteration_indicator)1180 self.outdent()1181 self.leave_frame(1182 loop_frame, with_python_scope=node.recursive and not node.else_1183 )11841185 if node.else_:1186 self.writeline("if %s:" % iteration_indicator)1187 self.indent()1188 self.enter_frame(else_frame)1189 self.blockvisit(node.else_, else_frame)1190 self.leave_frame(else_frame)1191 self.outdent()11921193 # if the node was recursive we have to return the buffer contents1194 # and start the iteration code1195 if node.recursive:1196 self.return_buffer_contents(loop_frame)1197 self.outdent()1198 self.start_write(frame, node)1199 if self.environment.is_async:1200 self.write("await ")1201 self.write("loop(")1202 if self.environment.is_async:1203 self.write("auto_aiter(")1204 self.visit(node.iter, frame)1205 if self.environment.is_async:1206 self.write(")")1207 self.write(", loop)")1208 self.end_write(frame)12091210 def visit_If(self, node, frame):1211 if_frame = frame.soft()1212 self.writeline("if ", node)1213 self.visit(node.test, if_frame)1214 self.write(":")1215 self.indent()1216 self.blockvisit(node.body, if_frame)1217 self.outdent()1218 for elif_ in node.elif_:1219 self.writeline("elif ", elif_)1220 self.visit(elif_.test, if_frame)1221 self.write(":")1222 self.indent()1223 self.blockvisit(elif_.body, if_frame)1224 self.outdent()1225 if node.else_:1226 self.writeline("else:")1227 self.indent()1228 self.blockvisit(node.else_, if_frame)1229 self.outdent()12301231 def visit_Macro(self, node, frame):1232 macro_frame, macro_ref = self.macro_body(node, frame)1233 self.newline()1234 if frame.toplevel:1235 if not node.name.startswith("_"):1236 self.write("context.exported_vars.add(%r)" % node.name)1237 self.writeline("context.vars[%r] = " % node.name)1238 self.write("%s = " % frame.symbols.ref(node.name))1239 self.macro_def(macro_ref, macro_frame)12401241 def visit_CallBlock(self, node, frame):1242 call_frame, macro_ref = self.macro_body(node, frame)1243 self.writeline("caller = ")1244 self.macro_def(macro_ref, call_frame)1245 self.start_write(frame, node)1246 self.visit_Call(node.call, frame, forward_caller=True)1247 self.end_write(frame)12481249 def visit_FilterBlock(self, node, frame):1250 filter_frame = frame.inner()1251 filter_frame.symbols.analyze_node(node)1252 self.enter_frame(filter_frame)1253 self.buffer(filter_frame)1254 self.blockvisit(node.body, filter_frame)1255 self.start_write(frame, node)1256 self.visit_Filter(node.filter, filter_frame)1257 self.end_write(frame)1258 self.leave_frame(filter_frame)12591260 def visit_With(self, node, frame):1261 with_frame = frame.inner()1262 with_frame.symbols.analyze_node(node)1263 self.enter_frame(with_frame)1264 for target, expr in izip(node.targets, node.values):1265 self.newline()1266 self.visit(target, with_frame)1267 self.write(" = ")1268 self.visit(expr, frame)1269 self.blockvisit(node.body, with_frame)1270 self.leave_frame(with_frame)12711272 def visit_ExprStmt(self, node, frame):1273 self.newline(node)1274 self.visit(node.node, frame)12751276 _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1277 #: The default finalize function if the environment isn't configured1278 #: with one. Or if the environment has one, this is called on that1279 #: function's output for constants.1280 _default_finalize = text_type1281 _finalize = None12821283 def _make_finalize(self):1284 """Build the finalize function to be used on constants and at1285 runtime. Cached so it's only created once for all output nodes.12861287 Returns a ``namedtuple`` with the following attributes:12881289 ``const``1290 A function to finalize constant data at compile time.12911292 ``src``1293 Source code to output around nodes to be evaluated at1294 runtime.1295 """1296 if self._finalize is not None:1297 return self._finalize12981299 finalize = default = self._default_finalize1300 src = None13011302 if self.environment.finalize:1303 src = "environment.finalize("1304 env_finalize = self.environment.finalize13051306 def finalize(value):1307 return default(env_finalize(value))13081309 if getattr(env_finalize, "contextfunction", False):1310 src += "context, "1311 finalize = None # noqa: F8111312 elif getattr(env_finalize, "evalcontextfunction", False):1313 src += "context.eval_ctx, "1314 finalize = None1315 elif getattr(env_finalize, "environmentfunction", False):1316 src += "environment, "13171318 def finalize(value):1319 return default(env_finalize(self.environment, value))13201321 self._finalize = self._FinalizeInfo(finalize, src)1322 return self._finalize13231324 def _output_const_repr(self, group):1325 """Given a group of constant values converted from ``Output``1326 child nodes, produce a string to write to the template module1327 source.1328 """1329 return repr(concat(group))13301331 def _output_child_to_const(self, node, frame, finalize):1332 """Try to optimize a child of an ``Output`` node by trying to1333 convert it to constant, finalized data at compile time.13341335 If :exc:`Impossible` is raised, the node is not constant and1336 will be evaluated at runtime. Any other exception will also be1337 evaluated at runtime for easier debugging.1338 """1339 const = node.as_const(frame.eval_ctx)13401341 if frame.eval_ctx.autoescape:1342 const = escape(const)13431344 # Template data doesn't go through finalize.1345 if isinstance(node, nodes.TemplateData):1346 return text_type(const)13471348 return finalize.const(const)13491350 def _output_child_pre(self, node, frame, finalize):1351 """Output extra source code before visiting a child of an1352 ``Output`` node.1353 """1354 if frame.eval_ctx.volatile:1355 self.write("(escape if context.eval_ctx.autoescape else to_string)(")1356 elif frame.eval_ctx.autoescape:1357 self.write("escape(")1358 else:1359 self.write("to_string(")13601361 if finalize.src is not None:1362 self.write(finalize.src)13631364 def _output_child_post(self, node, frame, finalize):1365 """Output extra source code after visiting a child of an1366 ``Output`` node.1367 """1368 self.write(")")13691370 if finalize.src is not None:1371 self.write(")")13721373 def visit_Output(self, node, frame):1374 # If an extends is active, don't render outside a block.1375 if frame.require_output_check:1376 # A top-level extends is known to exist at compile time.1377 if self.has_known_extends:1378 return13791380 self.writeline("if parent_template is None:")1381 self.indent()13821383 finalize = self._make_finalize()1384 body = []13851386 # Evaluate constants at compile time if possible. Each item in1387 # body will be either a list of static data or a node to be1388 # evaluated at runtime.1389 for child in node.nodes:1390 try:1391 if not (1392 # If the finalize function requires runtime context,1393 # constants can't be evaluated at compile time.1394 finalize.const1395 # Unless it's basic template data that won't be1396 # finalized anyway.1397 or isinstance(child, nodes.TemplateData)1398 ):1399 raise nodes.Impossible()14001401 const = self._output_child_to_const(child, frame, finalize)1402 except (nodes.Impossible, Exception):1403 # The node was not constant and needs to be evaluated at1404 # runtime. Or another error was raised, which is easier1405 # to debug at runtime.1406 body.append(child)1407 continue14081409 if body and isinstance(body[-1], list):1410 body[-1].append(const)1411 else:1412 body.append([const])14131414 if frame.buffer is not None:1415 if len(body) == 1:1416 self.writeline("%s.append(" % frame.buffer)1417 else:1418 self.writeline("%s.extend((" % frame.buffer)14191420 self.indent()14211422 for item in body:1423 if isinstance(item, list):1424 # A group of constant data to join and output.1425 val = self._output_const_repr(item)14261427 if frame.buffer is None:1428 self.writeline("yield " + val)1429 else:1430 self.writeline(val + ",")1431 else:1432 if frame.buffer is None:1433 self.writeline("yield ", item)1434 else:1435 self.newline(item)14361437 # A node to be evaluated at runtime.1438 self._output_child_pre(item, frame, finalize)1439 self.visit(item, frame)1440 self._output_child_post(item, frame, finalize)14411442 if frame.buffer is not None:1443 self.write(",")14441445 if frame.buffer is not None:1446 self.outdent()1447 self.writeline(")" if len(body) == 1 else "))")14481449 if frame.require_output_check:1450 self.outdent()14511452 def visit_Assign(self, node, frame):1453 self.push_assign_tracking()1454 self.newline(node)1455 self.visit(node.target, frame)1456 self.write(" = ")1457 self.visit(node.node, frame)1458 self.pop_assign_tracking(frame)14591460 def visit_AssignBlock(self, node, frame):1461 self.push_assign_tracking()1462 block_frame = frame.inner()1463 # This is a special case. Since a set block always captures we1464 # will disable output checks. This way one can use set blocks1465 # toplevel even in extended templates.1466 block_frame.require_output_check = False1467 block_frame.symbols.analyze_node(node)1468 self.enter_frame(block_frame)1469 self.buffer(block_frame)1470 self.blockvisit(node.body, block_frame)1471 self.newline(node)1472 self.visit(node.target, frame)1473 self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")1474 if node.filter is not None:1475 self.visit_Filter(node.filter, block_frame)1476 else:1477 self.write("concat(%s)" % block_frame.buffer)1478 self.write(")")1479 self.pop_assign_tracking(frame)1480 self.leave_frame(block_frame)14811482 # -- Expression Visitors14831484 def visit_Name(self, node, frame):1485 if node.ctx == "store" and frame.toplevel:1486 if self._assign_stack:1487 self._assign_stack[-1].add(node.name)1488 ref = frame.symbols.ref(node.name)14891490 # If we are looking up a variable we might have to deal with the1491 # case where it's undefined. We can skip that case if the load1492 # instruction indicates a parameter which are always defined.1493 if node.ctx == "load":1494 load = frame.symbols.find_load(ref)1495 if not (1496 load is not None1497 and load[0] == VAR_LOAD_PARAMETER1498 and not self.parameter_is_undeclared(ref)1499 ):1500 self.write(1501 "(undefined(name=%r) if %s is missing else %s)"1502 % (node.name, ref, ref)1503 )1504 return15051506 self.write(ref)15071508 def visit_NSRef(self, node, frame):1509 # NSRefs can only be used to store values; since they use the normal1510 # `foo.bar` notation they will be parsed as a normal attribute access1511 # when used anywhere but in a `set` context1512 ref = frame.symbols.ref(node.name)1513 self.writeline("if not isinstance(%s, Namespace):" % ref)1514 self.indent()1515 self.writeline(1516 "raise TemplateRuntimeError(%r)"1517 % "cannot assign attribute on non-namespace object"1518 )1519 self.outdent()1520 self.writeline("%s[%r]" % (ref, node.attr))15211522 def visit_Const(self, node, frame):1523 val = node.as_const(frame.eval_ctx)1524 if isinstance(val, float):1525 self.write(str(val))1526 else:1527 self.write(repr(val))15281529 def visit_TemplateData(self, node, frame):1530 try:1531 self.write(repr(node.as_const(frame.eval_ctx)))1532 except nodes.Impossible:1533 self.write(1534 "(Markup if context.eval_ctx.autoescape else identity)(%r)" % node.data1535 )15361537 def visit_Tuple(self, node, frame):1538 self.write("(")1539 idx = -11540 for idx, item in enumerate(node.items):1541 if idx:1542 self.write(", ")1543 self.visit(item, frame)1544 self.write(idx == 0 and ",)" or ")")15451546 def visit_List(self, node, frame):1547 self.write("[")1548 for idx, item in enumerate(node.items):1549 if idx:1550 self.write(", ")1551 self.visit(item, frame)1552 self.write("]")15531554 def visit_Dict(self, node, frame):1555 self.write("{")1556 for idx, item in enumerate(node.items):1557 if idx:1558 self.write(", ")1559 self.visit(item.key, frame)1560 self.write(": ")1561 self.visit(item.value, frame)1562 self.write("}")15631564 def binop(operator, interceptable=True): # noqa: B9021565 @optimizeconst1566 def visitor(self, node, frame):1567 if (1568 self.environment.sandboxed1569 and operator in self.environment.intercepted_binops1570 ):1571 self.write("environment.call_binop(context, %r, " % operator)1572 self.visit(node.left, frame)1573 self.write(", ")1574 self.visit(node.right, frame)1575 else:1576 self.write("(")1577 self.visit(node.left, frame)1578 self.write(" %s " % operator)1579 self.visit(node.right, frame)1580 self.write(")")15811582 return visitor15831584 def uaop(operator, interceptable=True): # noqa: B9021585 @optimizeconst1586 def visitor(self, node, frame):1587 if (1588 self.environment.sandboxed1589 and operator in self.environment.intercepted_unops1590 ):1591 self.write("environment.call_unop(context, %r, " % operator)1592 self.visit(node.node, frame)1593 else:1594 self.write("(" + operator)1595 self.visit(node.node, frame)1596 self.write(")")15971598 return visitor15991600 visit_Add = binop("+")1601 visit_Sub = binop("-")1602 visit_Mul = binop("*")1603 visit_Div = binop("/")1604 visit_FloorDiv = binop("//")1605 visit_Pow = binop("**")1606 visit_Mod = binop("%")1607 visit_And = binop("and", interceptable=False)1608 visit_Or = binop("or", interceptable=False)1609 visit_Pos = uaop("+")1610 visit_Neg = uaop("-")1611 visit_Not = uaop("not ", interceptable=False)1612 del binop, uaop16131614 @optimizeconst1615 def visit_Concat(self, node, frame):1616 if frame.eval_ctx.volatile:1617 func_name = "(context.eval_ctx.volatile and markup_join or unicode_join)"1618 elif frame.eval_ctx.autoescape:1619 func_name = "markup_join"1620 else:1621 func_name = "unicode_join"1622 self.write("%s((" % func_name)1623 for arg in node.nodes:1624 self.visit(arg, frame)1625 self.write(", ")1626 self.write("))")16271628 @optimizeconst1629 def visit_Compare(self, node, frame):1630 self.write("(")1631 self.visit(node.expr, frame)1632 for op in node.ops:1633 self.visit(op, frame)1634 self.write(")")16351636 def visit_Operand(self, node, frame):1637 self.write(" %s " % operators[node.op])1638 self.visit(node.expr, frame)16391640 @optimizeconst1641 def visit_Getattr(self, node, frame):1642 if self.environment.is_async:1643 self.write("await auto_await(")16441645 self.write("environment.getattr(")1646 self.visit(node.node, frame)1647 self.write(", %r)" % node.attr)16481649 if self.environment.is_async:1650 self.write(")")16511652 @optimizeconst1653 def visit_Getitem(self, node, frame):1654 # slices bypass the environment getitem method.1655 if isinstance(node.arg, nodes.Slice):1656 self.visit(node.node, frame)1657 self.write("[")1658 self.visit(node.arg, frame)1659 self.write("]")1660 else:1661 if self.environment.is_async:1662 self.write("await auto_await(")16631664 self.write("environment.getitem(")1665 self.visit(node.node, frame)1666 self.write(", ")1667 self.visit(node.arg, frame)1668 self.write(")")16691670 if self.environment.is_async:1671 self.write(")")16721673 def visit_Slice(self, node, frame):1674 if node.start is not None:1675 self.visit(node.start, frame)1676 self.write(":")1677 if node.stop is not None:1678 self.visit(node.stop, frame)1679 if node.step is not None:1680 self.write(":")1681 self.visit(node.step, frame)16821683 @optimizeconst1684 def visit_Filter(self, node, frame):1685 if self.environment.is_async:1686 self.write("await auto_await(")1687 self.write(self.filters[node.name] + "(")1688 func = self.environment.filters.get(node.name)1689 if func is None:1690 self.fail("no filter named %r" % node.name, node.lineno)1691 if getattr(func, "contextfilter", False):1692 self.write("context, ")1693 elif getattr(func, "evalcontextfilter", False):1694 self.write("context.eval_ctx, ")1695 elif getattr(func, "environmentfilter", False):1696 self.write("environment, ")16971698 # if the filter node is None we are inside a filter block1699 # and want to write to the current buffer1700 if node.node is not None:1701 self.visit(node.node, frame)1702 elif frame.eval_ctx.volatile:1703 self.write(1704 "(context.eval_ctx.autoescape and"1705 " Markup(concat(%s)) or concat(%s))" % (frame.buffer, frame.buffer)1706 )1707 elif frame.eval_ctx.autoescape:1708 self.write("Markup(concat(%s))" % frame.buffer)1709 else:1710 self.write("concat(%s)" % frame.buffer)1711 self.signature(node, frame)1712 self.write(")")1713 if self.environment.is_async:1714 self.write(")")17151716 @optimizeconst1717 def visit_Test(self, node, frame):1718 self.write(self.tests[node.name] + "(")1719 if node.name not in self.environment.tests:1720 self.fail("no test named %r" % node.name, node.lineno)1721 self.visit(node.node, frame)1722 self.signature(node, frame)1723 self.write(")")17241725 @optimizeconst1726 def visit_CondExpr(self, node, frame):1727 def write_expr2():1728 if node.expr2 is not None:1729 return self.visit(node.expr2, frame)1730 self.write(1731 "cond_expr_undefined(%r)"1732 % (1733 "the inline if-"1734 "expression on %s evaluated to false and "1735 "no else section was defined." % self.position(node)1736 )1737 )17381739 self.write("(")1740 self.visit(node.expr1, frame)1741 self.write(" if ")1742 self.visit(node.test, frame)1743 self.write(" else ")1744 write_expr2()1745 self.write(")")17461747 @optimizeconst1748 def visit_Call(self, node, frame, forward_caller=False):1749 if self.environment.is_async:1750 self.write("await auto_await(")1751 if self.environment.sandboxed:1752 self.write("environment.call(context, ")1753 else:1754 self.write("context.call(")1755 self.visit(node.node, frame)1756 extra_kwargs = forward_caller and {"caller": "caller"} or None1757 self.signature(node, frame, extra_kwargs)1758 self.write(")")1759 if self.environment.is_async:1760 self.write(")")17611762 def visit_Keyword(self, node, frame):1763 self.write(node.key + "=")1764 self.visit(node.value, frame)17651766 # -- Unused nodes for extensions17671768 def visit_MarkSafe(self, node, frame):1769 self.write("Markup(")1770 self.visit(node.expr, frame)1771 self.write(")")17721773 def visit_MarkSafeIfAutoescape(self, node, frame):1774 self.write("(context.eval_ctx.autoescape and Markup or identity)(")1775 self.visit(node.expr, frame)1776 self.write(")")17771778 def visit_EnvironmentAttribute(self, node, frame):1779 self.write("environment." + node.name)17801781 def visit_ExtensionAttribute(self, node, frame):1782 self.write("environment.extensions[%r].%s" % (node.identifier, node.name))17831784 def visit_ImportedName(self, node, frame):1785 self.write(self.import_aliases[node.importname])17861787 def visit_InternalName(self, node, frame):1788 self.write(node.name)17891790 def visit_ContextReference(self, node, frame):1791 self.write("context")17921793 def visit_DerivedContextReference(self, node, frame):1794 self.write(self.derive_context(frame))17951796 def visit_Continue(self, node, frame):1797 self.writeline("continue", node)17981799 def visit_Break(self, node, frame):1800 self.writeline("break", node)18011802 def visit_Scope(self, node, frame):1803 scope_frame = frame.inner()1804 scope_frame.symbols.analyze_node(node)1805 self.enter_frame(scope_frame)1806 self.blockvisit(node.body, scope_frame)1807 self.leave_frame(scope_frame)18081809 def visit_OverlayScope(self, node, frame):1810 ctx = self.temporary_identifier()1811 self.writeline("%s = %s" % (ctx, self.derive_context(frame)))1812 self.writeline("%s.vars = " % ctx)1813 self.visit(node.context, frame)1814 self.push_context_reference(ctx)18151816 scope_frame = frame.inner(isolated=True)1817 scope_frame.symbols.analyze_node(node)1818 self.enter_frame(scope_frame)1819 self.blockvisit(node.body, scope_frame)1820 self.leave_frame(scope_frame)1821 self.pop_context_reference()18221823 def visit_EvalContextModifier(self, node, frame):1824 for keyword in node.options:1825 self.writeline("context.eval_ctx.%s = " % keyword.key)1826 self.visit(keyword.value, frame)1827 try:1828 val = keyword.value.as_const(frame.eval_ctx)1829 except nodes.Impossible:1830 frame.eval_ctx.volatile = True1831 else:1832 setattr(frame.eval_ctx, keyword.key, val)18331834 def visit_ScopedEvalContextModifier(self, node, frame):1835 old_ctx_name = self.temporary_identifier()1836 saved_ctx = frame.eval_ctx.save()1837 self.writeline("%s = context.eval_ctx.save()" % old_ctx_name)1838 self.visit_EvalContextModifier(node, frame)1839 for child in node.body:1840 self.visit(child, frame)1841 frame.eval_ctx.revert(saved_ctx)1842 self.writeline("context.eval_ctx.revert(%s)" % old_ctx_name)
deleted:src/jinja2/constants.py-21 removed
1# -*- coding: utf-8 -*-2#: list of lorem ipsum words used by the lipsum() helper function3LOREM_IPSUM_WORDS = u"""\4a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at5auctor augue bibendum blandit class commodo condimentum congue consectetuer6consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus7diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend8elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames9faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac10hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum11justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem12luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie13mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non14nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque15penatibus per pharetra phasellus placerat platea porta porttitor posuere16potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus17ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit18sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor19tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices20ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus21viverra volutpat vulputate"""
deleted:src/jinja2/debug.py-271 removed
1import sys2from types import CodeType34from . import TemplateSyntaxError5from ._compat import PYPY6from .utils import internal_code7from .utils import missing8910def rewrite_traceback_stack(source=None):11 """Rewrite the current exception to replace any tracebacks from12 within compiled template code with tracebacks that look like they13 came from the template source.1415 This must be called within an ``except`` block.1617 :param exc_info: A :meth:`sys.exc_info` tuple. If not provided,18 the current ``exc_info`` is used.19 :param source: For ``TemplateSyntaxError``, the original source if20 known.21 :return: A :meth:`sys.exc_info` tuple that can be re-raised.22 """23 exc_type, exc_value, tb = sys.exc_info()2425 if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:26 exc_value.translated = True27 exc_value.source = source2829 try:30 # Remove the old traceback on Python 3, otherwise the frames31 # from the compiler still show up.32 exc_value.with_traceback(None)33 except AttributeError:34 pass3536 # Outside of runtime, so the frame isn't executing template37 # code, but it still needs to point at the template.38 tb = fake_traceback(39 exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno40 )41 else:42 # Skip the frame for the render function.43 tb = tb.tb_next4445 stack = []4647 # Build the stack of traceback object, replacing any in template48 # code with the source file and line information.49 while tb is not None:50 # Skip frames decorated with @internalcode. These are internal51 # calls that aren't useful in template debugging output.52 if tb.tb_frame.f_code in internal_code:53 tb = tb.tb_next54 continue5556 template = tb.tb_frame.f_globals.get("__jinja_template__")5758 if template is not None:59 lineno = template.get_corresponding_lineno(tb.tb_lineno)60 fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)61 stack.append(fake_tb)62 else:63 stack.append(tb)6465 tb = tb.tb_next6667 tb_next = None6869 # Assign tb_next in reverse to avoid circular references.70 for tb in reversed(stack):71 tb_next = tb_set_next(tb, tb_next)7273 return exc_type, exc_value, tb_next747576def fake_traceback(exc_value, tb, filename, lineno):77 """Produce a new traceback object that looks like it came from the78 template source instead of the compiled code. The filename, line79 number, and location name will point to the template, and the local80 variables will be the current template context.8182 :param exc_value: The original exception to be re-raised to create83 the new traceback.84 :param tb: The original traceback to get the local variables and85 code info from.86 :param filename: The template filename.87 :param lineno: The line number in the template source.88 """89 if tb is not None:90 # Replace the real locals with the context that would be91 # available at that point in the template.92 locals = get_template_locals(tb.tb_frame.f_locals)93 locals.pop("__jinja_exception__", None)94 else:95 locals = {}9697 globals = {98 "__name__": filename,99 "__file__": filename,100 "__jinja_exception__": exc_value,101 }102 # Raise an exception at the correct line number.103 code = compile("\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec")104105 # Build a new code object that points to the template file and106 # replaces the location with a block name.107 try:108 location = "template"109110 if tb is not None:111 function = tb.tb_frame.f_code.co_name112113 if function == "root":114 location = "top-level template code"115 elif function.startswith("block_"):116 location = 'block "%s"' % function[6:]117118 # Collect arguments for the new code object. CodeType only119 # accepts positional arguments, and arguments were inserted in120 # new Python versions.121 code_args = []122123 for attr in (124 "argcount",125 "posonlyargcount", # Python 3.8126 "kwonlyargcount", # Python 3127 "nlocals",128 "stacksize",129 "flags",130 "code", # codestring131 "consts", # constants132 "names",133 "varnames",134 ("filename", filename),135 ("name", location),136 "firstlineno",137 "lnotab",138 "freevars",139 "cellvars",140 ):141 if isinstance(attr, tuple):142 # Replace with given value.143 code_args.append(attr[1])144 continue145146 try:147 # Copy original value if it exists.148 code_args.append(getattr(code, "co_" + attr))149 except AttributeError:150 # Some arguments were added later.151 continue152153 code = CodeType(*code_args)154 except Exception:155 # Some environments such as Google App Engine don't support156 # modifying code objects.157 pass158159 # Execute the new code, which is guaranteed to raise, and return160 # the new traceback without this frame.161 try:162 exec(code, globals, locals)163 except BaseException:164 return sys.exc_info()[2].tb_next165166167def get_template_locals(real_locals):168 """Based on the runtime locals, get the context that would be169 available at that point in the template.170 """171 # Start with the current template context.172 ctx = real_locals.get("context")173174 if ctx:175 data = ctx.get_all().copy()176 else:177 data = {}178179 # Might be in a derived context that only sets local variables180 # rather than pushing a context. Local variables follow the scheme181 # l_depth_name. Find the highest-depth local that has a value for182 # each name.183 local_overrides = {}184185 for name, value in real_locals.items():186 if not name.startswith("l_") or value is missing:187 # Not a template variable, or no longer relevant.188 continue189190 try:191 _, depth, name = name.split("_", 2)192 depth = int(depth)193 except ValueError:194 continue195196 cur_depth = local_overrides.get(name, (-1,))[0]197198 if cur_depth < depth:199 local_overrides[name] = (depth, value)200201 # Modify the context with any derived context.202 for name, (_, value) in local_overrides.items():203 if value is missing:204 data.pop(name, None)205 else:206 data[name] = value207208 return data209210211if sys.version_info >= (3, 7):212 # tb_next is directly assignable as of Python 3.7213 def tb_set_next(tb, tb_next):214 tb.tb_next = tb_next215 return tb216217218elif PYPY:219 # PyPy might have special support, and won't work with ctypes.220 try:221 import tputil222 except ImportError:223 # Without tproxy support, use the original traceback.224 def tb_set_next(tb, tb_next):225 return tb226227 else:228 # With tproxy support, create a proxy around the traceback that229 # returns the new tb_next.230 def tb_set_next(tb, tb_next):231 def controller(op):232 if op.opname == "__getattribute__" and op.args[0] == "tb_next":233 return tb_next234235 return op.delegate()236237 return tputil.make_proxy(controller, obj=tb)238239240else:241 # Use ctypes to assign tb_next at the C level since it's read-only242 # from Python.243 import ctypes244245 class _CTraceback(ctypes.Structure):246 _fields_ = [247 # Extra PyObject slots when compiled with Py_TRACE_REFS.248 (249 "PyObject_HEAD",250 ctypes.c_byte * (32 if hasattr(sys, "getobjects") else 16),251 ),252 # Only care about tb_next as an object, not a traceback.253 ("tb_next", ctypes.py_object),254 ]255256 def tb_set_next(tb, tb_next):257 c_tb = _CTraceback.from_address(id(tb))258259 # Clear out the old tb_next.260 if tb.tb_next is not None:261 c_tb_next = ctypes.py_object(tb.tb_next)262 c_tb.tb_next = ctypes.py_object()263 ctypes.pythonapi.Py_DecRef(c_tb_next)264265 # Assign the new tb_next.266 if tb_next is not None:267 c_tb_next = ctypes.py_object(tb_next)268 ctypes.pythonapi.Py_IncRef(c_tb_next)269 c_tb.tb_next = c_tb_next270271 return tb
deleted:src/jinja2/defaults.py-47 removed
1# -*- coding: utf-8 -*-2from ._compat import range_type3from .filters import FILTERS as DEFAULT_FILTERS # noqa: F4014from .tests import TESTS as DEFAULT_TESTS # noqa: F4015from .utils import Cycler6from .utils import generate_lorem_ipsum7from .utils import Joiner8from .utils import Namespace910# defaults for the parser / lexer11BLOCK_START_STRING = "{%"12BLOCK_END_STRING = "%}"13VARIABLE_START_STRING = "{{"14VARIABLE_END_STRING = "}}"15COMMENT_START_STRING = "{#"16COMMENT_END_STRING = "#}"17LINE_STATEMENT_PREFIX = None18LINE_COMMENT_PREFIX = None19TRIM_BLOCKS = False20LSTRIP_BLOCKS = False21NEWLINE_SEQUENCE = "\n"22KEEP_TRAILING_NEWLINE = False2324# default filters, tests and namespace2526DEFAULT_NAMESPACE = {27 "range": range_type,28 "dict": dict,29 "lipsum": generate_lorem_ipsum,30 "cycler": Cycler,31 "joiner": Joiner,32 "namespace": Namespace,33}3435# default policies36DEFAULT_POLICIES = {37 "compiler.ascii_str": True,38 "urlize.rel": "noopener",39 "urlize.target": None,40 "truncate.leeway": 5,41 "json.dumps_function": None,42 "json.dumps_kwargs": {"sort_keys": True},43 "ext.i18n.trimmed": False,44}4546# export all constants47__all__ = tuple(x for x in locals().keys() if x.isupper())
deleted:src/jinja2/environment.py-1361 removed
1# -*- coding: utf-8 -*-2"""Classes for managing templates and their runtime and compile time3options.4"""5import os6import sys7import weakref8from functools import partial9from functools import reduce1011from . import nodes12from ._compat import encode_filename13from ._compat import implements_iterator14from ._compat import implements_to_string15from ._compat import iteritems16from ._compat import PY217from ._compat import PYPY18from ._compat import reraise19from ._compat import string_types20from ._compat import text_type21from .compiler import CodeGenerator22from .compiler import generate23from .defaults import BLOCK_END_STRING24from .defaults import BLOCK_START_STRING25from .defaults import COMMENT_END_STRING26from .defaults import COMMENT_START_STRING27from .defaults import DEFAULT_FILTERS28from .defaults import DEFAULT_NAMESPACE29from .defaults import DEFAULT_POLICIES30from .defaults import DEFAULT_TESTS31from .defaults import KEEP_TRAILING_NEWLINE32from .defaults import LINE_COMMENT_PREFIX33from .defaults import LINE_STATEMENT_PREFIX34from .defaults import LSTRIP_BLOCKS35from .defaults import NEWLINE_SEQUENCE36from .defaults import TRIM_BLOCKS37from .defaults import VARIABLE_END_STRING38from .defaults import VARIABLE_START_STRING39from .exceptions import TemplateNotFound40from .exceptions import TemplateRuntimeError41from .exceptions import TemplatesNotFound42from .exceptions import TemplateSyntaxError43from .exceptions import UndefinedError44from .lexer import get_lexer45from .lexer import TokenStream46from .nodes import EvalContext47from .parser import Parser48from .runtime import Context49from .runtime import new_context50from .runtime import Undefined51from .utils import concat52from .utils import consume53from .utils import have_async_gen54from .utils import import_string55from .utils import internalcode56from .utils import LRUCache57from .utils import Markup58from .utils import missing5960# for direct template usage we have up to ten living environments61_spontaneous_environments = LRUCache(10)626364def get_spontaneous_environment(cls, *args):65 """Return a new spontaneous environment. A spontaneous environment66 is used for templates created directly rather than through an67 existing environment.6869 :param cls: Environment class to create.70 :param args: Positional arguments passed to environment.71 """72 key = (cls, args)7374 try:75 return _spontaneous_environments[key]76 except KeyError:77 _spontaneous_environments[key] = env = cls(*args)78 env.shared = True79 return env808182def create_cache(size):83 """Return the cache class for the given size."""84 if size == 0:85 return None86 if size < 0:87 return {}88 return LRUCache(size)899091def copy_cache(cache):92 """Create an empty copy of the given cache."""93 if cache is None:94 return None95 elif type(cache) is dict:96 return {}97 return LRUCache(cache.capacity)9899100def load_extensions(environment, extensions):101 """Load the extensions from the list and bind it to the environment.102 Returns a dict of instantiated environments.103 """104 result = {}105 for extension in extensions:106 if isinstance(extension, string_types):107 extension = import_string(extension)108 result[extension.identifier] = extension(environment)109 return result110111112def fail_for_missing_callable(string, name):113 msg = string % name114 if isinstance(name, Undefined):115 try:116 name._fail_with_undefined_error()117 except Exception as e:118 msg = "%s (%s; did you forget to quote the callable name?)" % (msg, e)119 raise TemplateRuntimeError(msg)120121122def _environment_sanity_check(environment):123 """Perform a sanity check on the environment."""124 assert issubclass(125 environment.undefined, Undefined126 ), "undefined must be a subclass of undefined because filters depend on it."127 assert (128 environment.block_start_string129 != environment.variable_start_string130 != environment.comment_start_string131 ), "block, variable and comment start strings must be different"132 assert environment.newline_sequence in (133 "\r",134 "\r\n",135 "\n",136 ), "newline_sequence set to unknown line ending string."137 return environment138139140class Environment(object):141 r"""The core component of Jinja is the `Environment`. It contains142 important shared variables like configuration, filters, tests,143 globals and others. Instances of this class may be modified if144 they are not shared and if no template was loaded so far.145 Modifications on environments after the first template was loaded146 will lead to surprising effects and undefined behavior.147148 Here are the possible initialization parameters:149150 `block_start_string`151 The string marking the beginning of a block. Defaults to ``'{%'``.152153 `block_end_string`154 The string marking the end of a block. Defaults to ``'%}'``.155156 `variable_start_string`157 The string marking the beginning of a print statement.158 Defaults to ``'{{'``.159160 `variable_end_string`161 The string marking the end of a print statement. Defaults to162 ``'}}'``.163164 `comment_start_string`165 The string marking the beginning of a comment. Defaults to ``'{#'``.166167 `comment_end_string`168 The string marking the end of a comment. Defaults to ``'#}'``.169170 `line_statement_prefix`171 If given and a string, this will be used as prefix for line based172 statements. See also :ref:`line-statements`.173174 `line_comment_prefix`175 If given and a string, this will be used as prefix for line based176 comments. See also :ref:`line-statements`.177178 .. versionadded:: 2.2179180 `trim_blocks`181 If this is set to ``True`` the first newline after a block is182 removed (block, not variable tag!). Defaults to `False`.183184 `lstrip_blocks`185 If this is set to ``True`` leading spaces and tabs are stripped186 from the start of a line to a block. Defaults to `False`.187188 `newline_sequence`189 The sequence that starts a newline. Must be one of ``'\r'``,190 ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a191 useful default for Linux and OS X systems as well as web192 applications.193194 `keep_trailing_newline`195 Preserve the trailing newline when rendering templates.196 The default is ``False``, which causes a single newline,197 if present, to be stripped from the end of the template.198199 .. versionadded:: 2.7200201 `extensions`202 List of Jinja extensions to use. This can either be import paths203 as strings or extension classes. For more information have a204 look at :ref:`the extensions documentation <jinja-extensions>`.205206 `optimized`207 should the optimizer be enabled? Default is ``True``.208209 `undefined`210 :class:`Undefined` or a subclass of it that is used to represent211 undefined values in the template.212213 `finalize`214 A callable that can be used to process the result of a variable215 expression before it is output. For example one can convert216 ``None`` implicitly into an empty string here.217218 `autoescape`219 If set to ``True`` the XML/HTML autoescaping feature is enabled by220 default. For more details about autoescaping see221 :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also222 be a callable that is passed the template name and has to223 return ``True`` or ``False`` depending on autoescape should be224 enabled by default.225226 .. versionchanged:: 2.4227 `autoescape` can now be a function228229 `loader`230 The template loader for this environment.231232 `cache_size`233 The size of the cache. Per default this is ``400`` which means234 that if more than 400 templates are loaded the loader will clean235 out the least recently used template. If the cache size is set to236 ``0`` templates are recompiled all the time, if the cache size is237 ``-1`` the cache will not be cleaned.238239 .. versionchanged:: 2.8240 The cache size was increased to 400 from a low 50.241242 `auto_reload`243 Some loaders load templates from locations where the template244 sources may change (ie: file system or database). If245 ``auto_reload`` is set to ``True`` (default) every time a template is246 requested the loader checks if the source changed and if yes, it247 will reload the template. For higher performance it's possible to248 disable that.249250 `bytecode_cache`251 If set to a bytecode cache object, this object will provide a252 cache for the internal Jinja bytecode so that templates don't253 have to be parsed if they were not changed.254255 See :ref:`bytecode-cache` for more information.256257 `enable_async`258 If set to true this enables async template execution which allows259 you to take advantage of newer Python features. This requires260 Python 3.6 or later.261 """262263 #: if this environment is sandboxed. Modifying this variable won't make264 #: the environment sandboxed though. For a real sandboxed environment265 #: have a look at jinja2.sandbox. This flag alone controls the code266 #: generation by the compiler.267 sandboxed = False268269 #: True if the environment is just an overlay270 overlayed = False271272 #: the environment this environment is linked to if it is an overlay273 linked_to = None274275 #: shared environments have this set to `True`. A shared environment276 #: must not be modified277 shared = False278279 #: the class that is used for code generation. See280 #: :class:`~jinja2.compiler.CodeGenerator` for more information.281 code_generator_class = CodeGenerator282283 #: the context class thatis used for templates. See284 #: :class:`~jinja2.runtime.Context` for more information.285 context_class = Context286287 def __init__(288 self,289 block_start_string=BLOCK_START_STRING,290 block_end_string=BLOCK_END_STRING,291 variable_start_string=VARIABLE_START_STRING,292 variable_end_string=VARIABLE_END_STRING,293 comment_start_string=COMMENT_START_STRING,294 comment_end_string=COMMENT_END_STRING,295 line_statement_prefix=LINE_STATEMENT_PREFIX,296 line_comment_prefix=LINE_COMMENT_PREFIX,297 trim_blocks=TRIM_BLOCKS,298 lstrip_blocks=LSTRIP_BLOCKS,299 newline_sequence=NEWLINE_SEQUENCE,300 keep_trailing_newline=KEEP_TRAILING_NEWLINE,301 extensions=(),302 optimized=True,303 undefined=Undefined,304 finalize=None,305 autoescape=False,306 loader=None,307 cache_size=400,308 auto_reload=True,309 bytecode_cache=None,310 enable_async=False,311 ):312 # !!Important notice!!313 # The constructor accepts quite a few arguments that should be314 # passed by keyword rather than position. However it's important to315 # not change the order of arguments because it's used at least316 # internally in those cases:317 # - spontaneous environments (i18n extension and Template)318 # - unittests319 # If parameter changes are required only add parameters at the end320 # and don't change the arguments (or the defaults!) of the arguments321 # existing already.322323 # lexer / parser information324 self.block_start_string = block_start_string325 self.block_end_string = block_end_string326 self.variable_start_string = variable_start_string327 self.variable_end_string = variable_end_string328 self.comment_start_string = comment_start_string329 self.comment_end_string = comment_end_string330 self.line_statement_prefix = line_statement_prefix331 self.line_comment_prefix = line_comment_prefix332 self.trim_blocks = trim_blocks333 self.lstrip_blocks = lstrip_blocks334 self.newline_sequence = newline_sequence335 self.keep_trailing_newline = keep_trailing_newline336337 # runtime information338 self.undefined = undefined339 self.optimized = optimized340 self.finalize = finalize341 self.autoescape = autoescape342343 # defaults344 self.filters = DEFAULT_FILTERS.copy()345 self.tests = DEFAULT_TESTS.copy()346 self.globals = DEFAULT_NAMESPACE.copy()347348 # set the loader provided349 self.loader = loader350 self.cache = create_cache(cache_size)351 self.bytecode_cache = bytecode_cache352 self.auto_reload = auto_reload353354 # configurable policies355 self.policies = DEFAULT_POLICIES.copy()356357 # load extensions358 self.extensions = load_extensions(self, extensions)359360 self.enable_async = enable_async361 self.is_async = self.enable_async and have_async_gen362 if self.is_async:363 # runs patch_all() to enable async support364 from . import asyncsupport # noqa: F401365366 _environment_sanity_check(self)367368 def add_extension(self, extension):369 """Adds an extension after the environment was created.370371 .. versionadded:: 2.5372 """373 self.extensions.update(load_extensions(self, [extension]))374375 def extend(self, **attributes):376 """Add the items to the instance of the environment if they do not exist377 yet. This is used by :ref:`extensions <writing-extensions>` to register378 callbacks and configuration values without breaking inheritance.379 """380 for key, value in iteritems(attributes):381 if not hasattr(self, key):382 setattr(self, key, value)383384 def overlay(385 self,386 block_start_string=missing,387 block_end_string=missing,388 variable_start_string=missing,389 variable_end_string=missing,390 comment_start_string=missing,391 comment_end_string=missing,392 line_statement_prefix=missing,393 line_comment_prefix=missing,394 trim_blocks=missing,395 lstrip_blocks=missing,396 extensions=missing,397 optimized=missing,398 undefined=missing,399 finalize=missing,400 autoescape=missing,401 loader=missing,402 cache_size=missing,403 auto_reload=missing,404 bytecode_cache=missing,405 ):406 """Create a new overlay environment that shares all the data with the407 current environment except for cache and the overridden attributes.408 Extensions cannot be removed for an overlayed environment. An overlayed409 environment automatically gets all the extensions of the environment it410 is linked to plus optional extra extensions.411412 Creating overlays should happen after the initial environment was set413 up completely. Not all attributes are truly linked, some are just414 copied over so modifications on the original environment may not shine415 through.416 """417 args = dict(locals())418 del args["self"], args["cache_size"], args["extensions"]419420 rv = object.__new__(self.__class__)421 rv.__dict__.update(self.__dict__)422 rv.overlayed = True423 rv.linked_to = self424425 for key, value in iteritems(args):426 if value is not missing:427 setattr(rv, key, value)428429 if cache_size is not missing:430 rv.cache = create_cache(cache_size)431 else:432 rv.cache = copy_cache(self.cache)433434 rv.extensions = {}435 for key, value in iteritems(self.extensions):436 rv.extensions[key] = value.bind(rv)437 if extensions is not missing:438 rv.extensions.update(load_extensions(rv, extensions))439440 return _environment_sanity_check(rv)441442 lexer = property(get_lexer, doc="The lexer for this environment.")443444 def iter_extensions(self):445 """Iterates over the extensions by priority."""446 return iter(sorted(self.extensions.values(), key=lambda x: x.priority))447448 def getitem(self, obj, argument):449 """Get an item or attribute of an object but prefer the item."""450 try:451 return obj[argument]452 except (AttributeError, TypeError, LookupError):453 if isinstance(argument, string_types):454 try:455 attr = str(argument)456 except Exception:457 pass458 else:459 try:460 return getattr(obj, attr)461 except AttributeError:462 pass463 return self.undefined(obj=obj, name=argument)464465 def getattr(self, obj, attribute):466 """Get an item or attribute of an object but prefer the attribute.467 Unlike :meth:`getitem` the attribute *must* be a bytestring.468 """469 try:470 return getattr(obj, attribute)471 except AttributeError:472 pass473 try:474 return obj[attribute]475 except (TypeError, LookupError, AttributeError):476 return self.undefined(obj=obj, name=attribute)477478 def call_filter(479 self, name, value, args=None, kwargs=None, context=None, eval_ctx=None480 ):481 """Invokes a filter on a value the same way the compiler does it.482483 Note that on Python 3 this might return a coroutine in case the484 filter is running from an environment in async mode and the filter485 supports async execution. It's your responsibility to await this486 if needed.487488 .. versionadded:: 2.7489 """490 func = self.filters.get(name)491 if func is None:492 fail_for_missing_callable("no filter named %r", name)493 args = [value] + list(args or ())494 if getattr(func, "contextfilter", False):495 if context is None:496 raise TemplateRuntimeError(497 "Attempted to invoke context filter without context"498 )499 args.insert(0, context)500 elif getattr(func, "evalcontextfilter", False):501 if eval_ctx is None:502 if context is not None:503 eval_ctx = context.eval_ctx504 else:505 eval_ctx = EvalContext(self)506 args.insert(0, eval_ctx)507 elif getattr(func, "environmentfilter", False):508 args.insert(0, self)509 return func(*args, **(kwargs or {}))510511 def call_test(self, name, value, args=None, kwargs=None):512 """Invokes a test on a value the same way the compiler does it.513514 .. versionadded:: 2.7515 """516 func = self.tests.get(name)517 if func is None:518 fail_for_missing_callable("no test named %r", name)519 return func(value, *(args or ()), **(kwargs or {}))520521 @internalcode522 def parse(self, source, name=None, filename=None):523 """Parse the sourcecode and return the abstract syntax tree. This524 tree of nodes is used by the compiler to convert the template into525 executable source- or bytecode. This is useful for debugging or to526 extract information from templates.527528 If you are :ref:`developing Jinja extensions <writing-extensions>`529 this gives you a good overview of the node tree generated.530 """531 try:532 return self._parse(source, name, filename)533 except TemplateSyntaxError:534 self.handle_exception(source=source)535536 def _parse(self, source, name, filename):537 """Internal parsing function used by `parse` and `compile`."""538 return Parser(self, source, name, encode_filename(filename)).parse()539540 def lex(self, source, name=None, filename=None):541 """Lex the given sourcecode and return a generator that yields542 tokens as tuples in the form ``(lineno, token_type, value)``.543 This can be useful for :ref:`extension development <writing-extensions>`544 and debugging templates.545546 This does not perform preprocessing. If you want the preprocessing547 of the extensions to be applied you have to filter source through548 the :meth:`preprocess` method.549 """550 source = text_type(source)551 try:552 return self.lexer.tokeniter(source, name, filename)553 except TemplateSyntaxError:554 self.handle_exception(source=source)555556 def preprocess(self, source, name=None, filename=None):557 """Preprocesses the source with all extensions. This is automatically558 called for all parsing and compiling methods but *not* for :meth:`lex`559 because there you usually only want the actual source tokenized.560 """561 return reduce(562 lambda s, e: e.preprocess(s, name, filename),563 self.iter_extensions(),564 text_type(source),565 )566567 def _tokenize(self, source, name, filename=None, state=None):568 """Called by the parser to do the preprocessing and filtering569 for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.570 """571 source = self.preprocess(source, name, filename)572 stream = self.lexer.tokenize(source, name, filename, state)573 for ext in self.iter_extensions():574 stream = ext.filter_stream(stream)575 if not isinstance(stream, TokenStream):576 stream = TokenStream(stream, name, filename)577 return stream578579 def _generate(self, source, name, filename, defer_init=False):580 """Internal hook that can be overridden to hook a different generate581 method in.582583 .. versionadded:: 2.5584 """585 return generate(586 source,587 self,588 name,589 filename,590 defer_init=defer_init,591 optimized=self.optimized,592 )593594 def _compile(self, source, filename):595 """Internal hook that can be overridden to hook a different compile596 method in.597598 .. versionadded:: 2.5599 """600 return compile(source, filename, "exec")601602 @internalcode603 def compile(self, source, name=None, filename=None, raw=False, defer_init=False):604 """Compile a node or template source code. The `name` parameter is605 the load name of the template after it was joined using606 :meth:`join_path` if necessary, not the filename on the file system.607 the `filename` parameter is the estimated filename of the template on608 the file system. If the template came from a database or memory this609 can be omitted.610611 The return value of this method is a python code object. If the `raw`612 parameter is `True` the return value will be a string with python613 code equivalent to the bytecode returned otherwise. This method is614 mainly used internally.615616 `defer_init` is use internally to aid the module code generator. This617 causes the generated code to be able to import without the global618 environment variable to be set.619620 .. versionadded:: 2.4621 `defer_init` parameter added.622 """623 source_hint = None624 try:625 if isinstance(source, string_types):626 source_hint = source627 source = self._parse(source, name, filename)628 source = self._generate(source, name, filename, defer_init=defer_init)629 if raw:630 return source631 if filename is None:632 filename = "<template>"633 else:634 filename = encode_filename(filename)635 return self._compile(source, filename)636 except TemplateSyntaxError:637 self.handle_exception(source=source_hint)638639 def compile_expression(self, source, undefined_to_none=True):640 """A handy helper method that returns a callable that accepts keyword641 arguments that appear as variables in the expression. If called it642 returns the result of the expression.643644 This is useful if applications want to use the same rules as Jinja645 in template "configuration files" or similar situations.646647 Example usage:648649 >>> env = Environment()650 >>> expr = env.compile_expression('foo == 42')651 >>> expr(foo=23)652 False653 >>> expr(foo=42)654 True655656 Per default the return value is converted to `None` if the657 expression returns an undefined value. This can be changed658 by setting `undefined_to_none` to `False`.659660 >>> env.compile_expression('var')() is None661 True662 >>> env.compile_expression('var', undefined_to_none=False)()663 Undefined664665 .. versionadded:: 2.1666 """667 parser = Parser(self, source, state="variable")668 try:669 expr = parser.parse_expression()670 if not parser.stream.eos:671 raise TemplateSyntaxError(672 "chunk after expression", parser.stream.current.lineno, None, None673 )674 expr.set_environment(self)675 except TemplateSyntaxError:676 if sys.exc_info() is not None:677 self.handle_exception(source=source)678679 body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]680 template = self.from_string(nodes.Template(body, lineno=1))681 return TemplateExpression(template, undefined_to_none)682683 def compile_templates(684 self,685 target,686 extensions=None,687 filter_func=None,688 zip="deflated",689 log_function=None,690 ignore_errors=True,691 py_compile=False,692 ):693 """Finds all the templates the loader can find, compiles them694 and stores them in `target`. If `zip` is `None`, instead of in a695 zipfile, the templates will be stored in a directory.696 By default a deflate zip algorithm is used. To switch to697 the stored algorithm, `zip` can be set to ``'stored'``.698699 `extensions` and `filter_func` are passed to :meth:`list_templates`.700 Each template returned will be compiled to the target folder or701 zipfile.702703 By default template compilation errors are ignored. In case a704 log function is provided, errors are logged. If you want template705 syntax errors to abort the compilation you can set `ignore_errors`706 to `False` and you will get an exception on syntax errors.707708 If `py_compile` is set to `True` .pyc files will be written to the709 target instead of standard .py files. This flag does not do anything710 on pypy and Python 3 where pyc files are not picked up by itself and711 don't give much benefit.712713 .. versionadded:: 2.4714 """715 from .loaders import ModuleLoader716717 if log_function is None:718719 def log_function(x):720 pass721722 if py_compile:723 if not PY2 or PYPY:724 import warnings725726 warnings.warn(727 "'py_compile=True' has no effect on PyPy or Python"728 " 3 and will be removed in version 3.0",729 DeprecationWarning,730 stacklevel=2,731 )732 py_compile = False733 else:734 import imp735 import marshal736737 py_header = imp.get_magic() + u"\xff\xff\xff\xff".encode("iso-8859-15")738739 # Python 3.3 added a source filesize to the header740 if sys.version_info >= (3, 3):741 py_header += u"\x00\x00\x00\x00".encode("iso-8859-15")742743 def write_file(filename, data):744 if zip:745 info = ZipInfo(filename)746 info.external_attr = 0o755 << 16747 zip_file.writestr(info, data)748 else:749 if isinstance(data, text_type):750 data = data.encode("utf8")751752 with open(os.path.join(target, filename), "wb") as f:753 f.write(data)754755 if zip is not None:756 from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED757758 zip_file = ZipFile(759 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]760 )761 log_function('Compiling into Zip archive "%s"' % target)762 else:763 if not os.path.isdir(target):764 os.makedirs(target)765 log_function('Compiling into folder "%s"' % target)766767 try:768 for name in self.list_templates(extensions, filter_func):769 source, filename, _ = self.loader.get_source(self, name)770 try:771 code = self.compile(source, name, filename, True, True)772 except TemplateSyntaxError as e:773 if not ignore_errors:774 raise775 log_function('Could not compile "%s": %s' % (name, e))776 continue777778 filename = ModuleLoader.get_module_filename(name)779780 if py_compile:781 c = self._compile(code, encode_filename(filename))782 write_file(filename + "c", py_header + marshal.dumps(c))783 log_function('Byte-compiled "%s" as %s' % (name, filename + "c"))784 else:785 write_file(filename, code)786 log_function('Compiled "%s" as %s' % (name, filename))787 finally:788 if zip:789 zip_file.close()790791 log_function("Finished compiling templates")792793 def list_templates(self, extensions=None, filter_func=None):794 """Returns a list of templates for this environment. This requires795 that the loader supports the loader's796 :meth:`~BaseLoader.list_templates` method.797798 If there are other files in the template folder besides the799 actual templates, the returned list can be filtered. There are two800 ways: either `extensions` is set to a list of file extensions for801 templates, or a `filter_func` can be provided which is a callable that802 is passed a template name and should return `True` if it should end up803 in the result list.804805 If the loader does not support that, a :exc:`TypeError` is raised.806807 .. versionadded:: 2.4808 """809 names = self.loader.list_templates()810811 if extensions is not None:812 if filter_func is not None:813 raise TypeError(814 "either extensions or filter_func can be passed, but not both"815 )816817 def filter_func(x):818 return "." in x and x.rsplit(".", 1)[1] in extensions819820 if filter_func is not None:821 names = [name for name in names if filter_func(name)]822823 return names824825 def handle_exception(self, source=None):826 """Exception handling helper. This is used internally to either raise827 rewritten exceptions or return a rendered traceback for the template.828 """829 from .debug import rewrite_traceback_stack830831 reraise(*rewrite_traceback_stack(source=source))832833 def join_path(self, template, parent):834 """Join a template with the parent. By default all the lookups are835 relative to the loader root so this method returns the `template`836 parameter unchanged, but if the paths should be relative to the837 parent template, this function can be used to calculate the real838 template name.839840 Subclasses may override this method and implement template path841 joining here.842 """843 return template844845 @internalcode846 def _load_template(self, name, globals):847 if self.loader is None:848 raise TypeError("no loader for this environment specified")849 cache_key = (weakref.ref(self.loader), name)850 if self.cache is not None:851 template = self.cache.get(cache_key)852 if template is not None and (853 not self.auto_reload or template.is_up_to_date854 ):855 return template856 template = self.loader.load(self, name, globals)857 if self.cache is not None:858 self.cache[cache_key] = template859 return template860861 @internalcode862 def get_template(self, name, parent=None, globals=None):863 """Load a template from the loader. If a loader is configured this864 method asks the loader for the template and returns a :class:`Template`.865 If the `parent` parameter is not `None`, :meth:`join_path` is called866 to get the real template name before loading.867868 The `globals` parameter can be used to provide template wide globals.869 These variables are available in the context at render time.870871 If the template does not exist a :exc:`TemplateNotFound` exception is872 raised.873874 .. versionchanged:: 2.4875 If `name` is a :class:`Template` object it is returned from the876 function unchanged.877 """878 if isinstance(name, Template):879 return name880 if parent is not None:881 name = self.join_path(name, parent)882 return self._load_template(name, self.make_globals(globals))883884 @internalcode885 def select_template(self, names, parent=None, globals=None):886 """Works like :meth:`get_template` but tries a number of templates887 before it fails. If it cannot find any of the templates, it will888 raise a :exc:`TemplatesNotFound` exception.889890 .. versionchanged:: 2.11891 If names is :class:`Undefined`, an :exc:`UndefinedError` is892 raised instead. If no templates were found and names893 contains :class:`Undefined`, the message is more helpful.894895 .. versionchanged:: 2.4896 If `names` contains a :class:`Template` object it is returned897 from the function unchanged.898899 .. versionadded:: 2.3900 """901 if isinstance(names, Undefined):902 names._fail_with_undefined_error()903904 if not names:905 raise TemplatesNotFound(906 message=u"Tried to select from an empty list " u"of templates."907 )908 globals = self.make_globals(globals)909 for name in names:910 if isinstance(name, Template):911 return name912 if parent is not None:913 name = self.join_path(name, parent)914 try:915 return self._load_template(name, globals)916 except (TemplateNotFound, UndefinedError):917 pass918 raise TemplatesNotFound(names)919920 @internalcode921 def get_or_select_template(self, template_name_or_list, parent=None, globals=None):922 """Does a typecheck and dispatches to :meth:`select_template`923 if an iterable of template names is given, otherwise to924 :meth:`get_template`.925926 .. versionadded:: 2.3927 """928 if isinstance(template_name_or_list, (string_types, Undefined)):929 return self.get_template(template_name_or_list, parent, globals)930 elif isinstance(template_name_or_list, Template):931 return template_name_or_list932 return self.select_template(template_name_or_list, parent, globals)933934 def from_string(self, source, globals=None, template_class=None):935 """Load a template from a string. This parses the source given and936 returns a :class:`Template` object.937 """938 globals = self.make_globals(globals)939 cls = template_class or self.template_class940 return cls.from_code(self, self.compile(source), globals, None)941942 def make_globals(self, d):943 """Return a dict for the globals."""944 if not d:945 return self.globals946 return dict(self.globals, **d)947948949class Template(object):950 """The central template object. This class represents a compiled template951 and is used to evaluate it.952953 Normally the template object is generated from an :class:`Environment` but954 it also has a constructor that makes it possible to create a template955 instance directly using the constructor. It takes the same arguments as956 the environment constructor but it's not possible to specify a loader.957958 Every template object has a few methods and members that are guaranteed959 to exist. However it's important that a template object should be960 considered immutable. Modifications on the object are not supported.961962 Template objects created from the constructor rather than an environment963 do have an `environment` attribute that points to a temporary environment964 that is probably shared with other templates created with the constructor965 and compatible settings.966967 >>> template = Template('Hello {{ name }}!')968 >>> template.render(name='John Doe') == u'Hello John Doe!'969 True970 >>> stream = template.stream(name='John Doe')971 >>> next(stream) == u'Hello John Doe!'972 True973 >>> next(stream)974 Traceback (most recent call last):975 ...976 StopIteration977 """978979 #: Type of environment to create when creating a template directly980 #: rather than through an existing environment.981 environment_class = Environment982983 def __new__(984 cls,985 source,986 block_start_string=BLOCK_START_STRING,987 block_end_string=BLOCK_END_STRING,988 variable_start_string=VARIABLE_START_STRING,989 variable_end_string=VARIABLE_END_STRING,990 comment_start_string=COMMENT_START_STRING,991 comment_end_string=COMMENT_END_STRING,992 line_statement_prefix=LINE_STATEMENT_PREFIX,993 line_comment_prefix=LINE_COMMENT_PREFIX,994 trim_blocks=TRIM_BLOCKS,995 lstrip_blocks=LSTRIP_BLOCKS,996 newline_sequence=NEWLINE_SEQUENCE,997 keep_trailing_newline=KEEP_TRAILING_NEWLINE,998 extensions=(),999 optimized=True,1000 undefined=Undefined,1001 finalize=None,1002 autoescape=False,1003 enable_async=False,1004 ):1005 env = get_spontaneous_environment(1006 cls.environment_class,1007 block_start_string,1008 block_end_string,1009 variable_start_string,1010 variable_end_string,1011 comment_start_string,1012 comment_end_string,1013 line_statement_prefix,1014 line_comment_prefix,1015 trim_blocks,1016 lstrip_blocks,1017 newline_sequence,1018 keep_trailing_newline,1019 frozenset(extensions),1020 optimized,1021 undefined,1022 finalize,1023 autoescape,1024 None,1025 0,1026 False,1027 None,1028 enable_async,1029 )1030 return env.from_string(source, template_class=cls)10311032 @classmethod1033 def from_code(cls, environment, code, globals, uptodate=None):1034 """Creates a template object from compiled code and the globals. This1035 is used by the loaders and environment to create a template object.1036 """1037 namespace = {"environment": environment, "__file__": code.co_filename}1038 exec(code, namespace)1039 rv = cls._from_namespace(environment, namespace, globals)1040 rv._uptodate = uptodate1041 return rv10421043 @classmethod1044 def from_module_dict(cls, environment, module_dict, globals):1045 """Creates a template object from a module. This is used by the1046 module loader to create a template object.10471048 .. versionadded:: 2.41049 """1050 return cls._from_namespace(environment, module_dict, globals)10511052 @classmethod1053 def _from_namespace(cls, environment, namespace, globals):1054 t = object.__new__(cls)1055 t.environment = environment1056 t.globals = globals1057 t.name = namespace["name"]1058 t.filename = namespace["__file__"]1059 t.blocks = namespace["blocks"]10601061 # render function and module1062 t.root_render_func = namespace["root"]1063 t._module = None10641065 # debug and loader helpers1066 t._debug_info = namespace["debug_info"]1067 t._uptodate = None10681069 # store the reference1070 namespace["environment"] = environment1071 namespace["__jinja_template__"] = t10721073 return t10741075 def render(self, *args, **kwargs):1076 """This method accepts the same arguments as the `dict` constructor:1077 A dict, a dict subclass or some keyword arguments. If no arguments1078 are given the context will be empty. These two calls do the same::10791080 template.render(knights='that say nih')1081 template.render({'knights': 'that say nih'})10821083 This will return the rendered template as unicode string.1084 """1085 vars = dict(*args, **kwargs)1086 try:1087 return concat(self.root_render_func(self.new_context(vars)))1088 except Exception:1089 self.environment.handle_exception()10901091 def render_async(self, *args, **kwargs):1092 """This works similar to :meth:`render` but returns a coroutine1093 that when awaited returns the entire rendered template string. This1094 requires the async feature to be enabled.10951096 Example usage::10971098 await template.render_async(knights='that say nih; asynchronously')1099 """1100 # see asyncsupport for the actual implementation1101 raise NotImplementedError(1102 "This feature is not available for this version of Python"1103 )11041105 def stream(self, *args, **kwargs):1106 """Works exactly like :meth:`generate` but returns a1107 :class:`TemplateStream`.1108 """1109 return TemplateStream(self.generate(*args, **kwargs))11101111 def generate(self, *args, **kwargs):1112 """For very large templates it can be useful to not render the whole1113 template at once but evaluate each statement after another and yield1114 piece for piece. This method basically does exactly that and returns1115 a generator that yields one item after another as unicode strings.11161117 It accepts the same arguments as :meth:`render`.1118 """1119 vars = dict(*args, **kwargs)1120 try:1121 for event in self.root_render_func(self.new_context(vars)):1122 yield event1123 except Exception:1124 yield self.environment.handle_exception()11251126 def generate_async(self, *args, **kwargs):1127 """An async version of :meth:`generate`. Works very similarly but1128 returns an async iterator instead.1129 """1130 # see asyncsupport for the actual implementation1131 raise NotImplementedError(1132 "This feature is not available for this version of Python"1133 )11341135 def new_context(self, vars=None, shared=False, locals=None):1136 """Create a new :class:`Context` for this template. The vars1137 provided will be passed to the template. Per default the globals1138 are added to the context. If shared is set to `True` the data1139 is passed as is to the context without adding the globals.11401141 `locals` can be a dict of local variables for internal usage.1142 """1143 return new_context(1144 self.environment, self.name, self.blocks, vars, shared, self.globals, locals1145 )11461147 def make_module(self, vars=None, shared=False, locals=None):1148 """This method works like the :attr:`module` attribute when called1149 without arguments but it will evaluate the template on every call1150 rather than caching it. It's also possible to provide1151 a dict which is then used as context. The arguments are the same1152 as for the :meth:`new_context` method.1153 """1154 return TemplateModule(self, self.new_context(vars, shared, locals))11551156 def make_module_async(self, vars=None, shared=False, locals=None):1157 """As template module creation can invoke template code for1158 asynchronous executions this method must be used instead of the1159 normal :meth:`make_module` one. Likewise the module attribute1160 becomes unavailable in async mode.1161 """1162 # see asyncsupport for the actual implementation1163 raise NotImplementedError(1164 "This feature is not available for this version of Python"1165 )11661167 @internalcode1168 def _get_default_module(self):1169 if self._module is not None:1170 return self._module1171 self._module = rv = self.make_module()1172 return rv11731174 @property1175 def module(self):1176 """The template as module. This is used for imports in the1177 template runtime but is also useful if one wants to access1178 exported template variables from the Python layer:11791180 >>> t = Template('{% macro foo() %}42{% endmacro %}23')1181 >>> str(t.module)1182 '23'1183 >>> t.module.foo() == u'42'1184 True11851186 This attribute is not available if async mode is enabled.1187 """1188 return self._get_default_module()11891190 def get_corresponding_lineno(self, lineno):1191 """Return the source line number of a line number in the1192 generated bytecode as they are not in sync.1193 """1194 for template_line, code_line in reversed(self.debug_info):1195 if code_line <= lineno:1196 return template_line1197 return 111981199 @property1200 def is_up_to_date(self):1201 """If this variable is `False` there is a newer version available."""1202 if self._uptodate is None:1203 return True1204 return self._uptodate()12051206 @property1207 def debug_info(self):1208 """The debug info mapping."""1209 if self._debug_info:1210 return [tuple(map(int, x.split("="))) for x in self._debug_info.split("&")]1211 return []12121213 def __repr__(self):1214 if self.name is None:1215 name = "memory:%x" % id(self)1216 else:1217 name = repr(self.name)1218 return "<%s %s>" % (self.__class__.__name__, name)121912201221@implements_to_string1222class TemplateModule(object):1223 """Represents an imported template. All the exported names of the1224 template are available as attributes on this object. Additionally1225 converting it into an unicode- or bytestrings renders the contents.1226 """12271228 def __init__(self, template, context, body_stream=None):1229 if body_stream is None:1230 if context.environment.is_async:1231 raise RuntimeError(1232 "Async mode requires a body stream "1233 "to be passed to a template module. Use "1234 "the async methods of the API you are "1235 "using."1236 )1237 body_stream = list(template.root_render_func(context))1238 self._body_stream = body_stream1239 self.__dict__.update(context.get_exported())1240 self.__name__ = template.name12411242 def __html__(self):1243 return Markup(concat(self._body_stream))12441245 def __str__(self):1246 return concat(self._body_stream)12471248 def __repr__(self):1249 if self.__name__ is None:1250 name = "memory:%x" % id(self)1251 else:1252 name = repr(self.__name__)1253 return "<%s %s>" % (self.__class__.__name__, name)125412551256class TemplateExpression(object):1257 """The :meth:`jinja2.Environment.compile_expression` method returns an1258 instance of this object. It encapsulates the expression-like access1259 to the template with an expression it wraps.1260 """12611262 def __init__(self, template, undefined_to_none):1263 self._template = template1264 self._undefined_to_none = undefined_to_none12651266 def __call__(self, *args, **kwargs):1267 context = self._template.new_context(dict(*args, **kwargs))1268 consume(self._template.root_render_func(context))1269 rv = context.vars["result"]1270 if self._undefined_to_none and isinstance(rv, Undefined):1271 rv = None1272 return rv127312741275@implements_iterator1276class TemplateStream(object):1277 """A template stream works pretty much like an ordinary python generator1278 but it can buffer multiple items to reduce the number of total iterations.1279 Per default the output is unbuffered which means that for every unbuffered1280 instruction in the template one unicode string is yielded.12811282 If buffering is enabled with a buffer size of 5, five items are combined1283 into a new unicode string. This is mainly useful if you are streaming1284 big templates to a client via WSGI which flushes after each iteration.1285 """12861287 def __init__(self, gen):1288 self._gen = gen1289 self.disable_buffering()12901291 def dump(self, fp, encoding=None, errors="strict"):1292 """Dump the complete stream into a file or file-like object.1293 Per default unicode strings are written, if you want to encode1294 before writing specify an `encoding`.12951296 Example usage::12971298 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1299 """1300 close = False1301 if isinstance(fp, string_types):1302 if encoding is None:1303 encoding = "utf-8"1304 fp = open(fp, "wb")1305 close = True1306 try:1307 if encoding is not None:1308 iterable = (x.encode(encoding, errors) for x in self)1309 else:1310 iterable = self1311 if hasattr(fp, "writelines"):1312 fp.writelines(iterable)1313 else:1314 for item in iterable:1315 fp.write(item)1316 finally:1317 if close:1318 fp.close()13191320 def disable_buffering(self):1321 """Disable the output buffering."""1322 self._next = partial(next, self._gen)1323 self.buffered = False13241325 def _buffered_generator(self, size):1326 buf = []1327 c_size = 01328 push = buf.append13291330 while 1:1331 try:1332 while c_size < size:1333 c = next(self._gen)1334 push(c)1335 if c:1336 c_size += 11337 except StopIteration:1338 if not c_size:1339 return1340 yield concat(buf)1341 del buf[:]1342 c_size = 013431344 def enable_buffering(self, size=5):1345 """Enable buffering. Buffer `size` items before yielding them."""1346 if size <= 1:1347 raise ValueError("buffer size too small")13481349 self.buffered = True1350 self._next = partial(next, self._buffered_generator(size))13511352 def __iter__(self):1353 return self13541355 def __next__(self):1356 return self._next()135713581359# hook in default template class. if anyone reads this comment: ignore that1360# it's possible to use custom templates ;-)1361Environment.template_class = Template
deleted:src/jinja2/exceptions.py-177 removed
1# -*- coding: utf-8 -*-2from ._compat import imap3from ._compat import implements_to_string4from ._compat import PY25from ._compat import text_type678class TemplateError(Exception):9 """Baseclass for all template errors."""1011 if PY2:1213 def __init__(self, message=None):14 if message is not None:15 message = text_type(message).encode("utf-8")16 Exception.__init__(self, message)1718 @property19 def message(self):20 if self.args:21 message = self.args[0]22 if message is not None:23 return message.decode("utf-8", "replace")2425 def __unicode__(self):26 return self.message or u""2728 else:2930 def __init__(self, message=None):31 Exception.__init__(self, message)3233 @property34 def message(self):35 if self.args:36 message = self.args[0]37 if message is not None:38 return message394041@implements_to_string42class TemplateNotFound(IOError, LookupError, TemplateError):43 """Raised if a template does not exist.4445 .. versionchanged:: 2.1146 If the given name is :class:`Undefined` and no message was47 provided, an :exc:`UndefinedError` is raised.48 """4950 # looks weird, but removes the warning descriptor that just51 # bogusly warns us about message being deprecated52 message = None5354 def __init__(self, name, message=None):55 IOError.__init__(self, name)5657 if message is None:58 from .runtime import Undefined5960 if isinstance(name, Undefined):61 name._fail_with_undefined_error()6263 message = name6465 self.message = message66 self.name = name67 self.templates = [name]6869 def __str__(self):70 return self.message717273class TemplatesNotFound(TemplateNotFound):74 """Like :class:`TemplateNotFound` but raised if multiple templates75 are selected. This is a subclass of :class:`TemplateNotFound`76 exception, so just catching the base exception will catch both.7778 .. versionchanged:: 2.1179 If a name in the list of names is :class:`Undefined`, a message80 about it being undefined is shown rather than the empty string.8182 .. versionadded:: 2.283 """8485 def __init__(self, names=(), message=None):86 if message is None:87 from .runtime import Undefined8889 parts = []9091 for name in names:92 if isinstance(name, Undefined):93 parts.append(name._undefined_message)94 else:95 parts.append(name)9697 message = u"none of the templates given were found: " + u", ".join(98 imap(text_type, parts)99 )100 TemplateNotFound.__init__(self, names and names[-1] or None, message)101 self.templates = list(names)102103104@implements_to_string105class TemplateSyntaxError(TemplateError):106 """Raised to tell the user that there is a problem with the template."""107108 def __init__(self, message, lineno, name=None, filename=None):109 TemplateError.__init__(self, message)110 self.lineno = lineno111 self.name = name112 self.filename = filename113 self.source = None114115 # this is set to True if the debug.translate_syntax_error116 # function translated the syntax error into a new traceback117 self.translated = False118119 def __str__(self):120 # for translated errors we only return the message121 if self.translated:122 return self.message123124 # otherwise attach some stuff125 location = "line %d" % self.lineno126 name = self.filename or self.name127 if name:128 location = 'File "%s", %s' % (name, location)129 lines = [self.message, " " + location]130131 # if the source is set, add the line to the output132 if self.source is not None:133 try:134 line = self.source.splitlines()[self.lineno - 1]135 except IndexError:136 line = None137 if line:138 lines.append(" " + line.strip())139140 return u"\n".join(lines)141142 def __reduce__(self):143 # https://bugs.python.org/issue1692335 Exceptions that take144 # multiple required arguments have problems with pickling.145 # Without this, raises TypeError: __init__() missing 1 required146 # positional argument: 'lineno'147 return self.__class__, (self.message, self.lineno, self.name, self.filename)148149150class TemplateAssertionError(TemplateSyntaxError):151 """Like a template syntax error, but covers cases where something in the152 template caused an error at compile time that wasn't necessarily caused153 by a syntax error. However it's a direct subclass of154 :exc:`TemplateSyntaxError` and has the same attributes.155 """156157158class TemplateRuntimeError(TemplateError):159 """A generic runtime error in the template engine. Under some situations160 Jinja may raise this exception.161 """162163164class UndefinedError(TemplateRuntimeError):165 """Raised if a template tries to operate on :class:`Undefined`."""166167168class SecurityError(TemplateRuntimeError):169 """Raised if a template tries to do something insecure if the170 sandbox is enabled.171 """172173174class FilterArgumentError(TemplateRuntimeError):175 """This error is raised if a filter was called with inappropriate176 arguments177 """
deleted:src/jinja2/ext.py-703 removed
1# -*- coding: utf-8 -*-2"""Extension API for adding custom tags and behavior."""3import pprint4import re5from sys import version_info67from . import nodes8from ._compat import iteritems9from ._compat import string_types10from ._compat import with_metaclass11from .defaults import BLOCK_END_STRING12from .defaults import BLOCK_START_STRING13from .defaults import COMMENT_END_STRING14from .defaults import COMMENT_START_STRING15from .defaults import KEEP_TRAILING_NEWLINE16from .defaults import LINE_COMMENT_PREFIX17from .defaults import LINE_STATEMENT_PREFIX18from .defaults import LSTRIP_BLOCKS19from .defaults import NEWLINE_SEQUENCE20from .defaults import TRIM_BLOCKS21from .defaults import VARIABLE_END_STRING22from .defaults import VARIABLE_START_STRING23from .environment import Environment24from .exceptions import TemplateAssertionError25from .exceptions import TemplateSyntaxError26from .nodes import ContextReference27from .runtime import concat28from .utils import contextfunction29from .utils import import_string30from .utils import Markup3132# the only real useful gettext functions for a Jinja template. Note33# that ugettext must be assigned to gettext as Jinja doesn't support34# non unicode strings.35GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext")3637_ws_re = re.compile(r"\s*\n\s*")383940class ExtensionRegistry(type):41 """Gives the extension an unique identifier."""4243 def __new__(mcs, name, bases, d):44 rv = type.__new__(mcs, name, bases, d)45 rv.identifier = rv.__module__ + "." + rv.__name__46 return rv474849class Extension(with_metaclass(ExtensionRegistry, object)):50 """Extensions can be used to add extra functionality to the Jinja template51 system at the parser level. Custom extensions are bound to an environment52 but may not store environment specific data on `self`. The reason for53 this is that an extension can be bound to another environment (for54 overlays) by creating a copy and reassigning the `environment` attribute.5556 As extensions are created by the environment they cannot accept any57 arguments for configuration. One may want to work around that by using58 a factory function, but that is not possible as extensions are identified59 by their import name. The correct way to configure the extension is60 storing the configuration values on the environment. Because this way the61 environment ends up acting as central configuration storage the62 attributes may clash which is why extensions have to ensure that the names63 they choose for configuration are not too generic. ``prefix`` for example64 is a terrible name, ``fragment_cache_prefix`` on the other hand is a good65 name as includes the name of the extension (fragment cache).66 """6768 #: if this extension parses this is the list of tags it's listening to.69 tags = set()7071 #: the priority of that extension. This is especially useful for72 #: extensions that preprocess values. A lower value means higher73 #: priority.74 #:75 #: .. versionadded:: 2.476 priority = 1007778 def __init__(self, environment):79 self.environment = environment8081 def bind(self, environment):82 """Create a copy of this extension bound to another environment."""83 rv = object.__new__(self.__class__)84 rv.__dict__.update(self.__dict__)85 rv.environment = environment86 return rv8788 def preprocess(self, source, name, filename=None):89 """This method is called before the actual lexing and can be used to90 preprocess the source. The `filename` is optional. The return value91 must be the preprocessed source.92 """93 return source9495 def filter_stream(self, stream):96 """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used97 to filter tokens returned. This method has to return an iterable of98 :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a99 :class:`~jinja2.lexer.TokenStream`.100 """101 return stream102103 def parse(self, parser):104 """If any of the :attr:`tags` matched this method is called with the105 parser as first argument. The token the parser stream is pointing at106 is the name token that matched. This method has to return one or a107 list of multiple nodes.108 """109 raise NotImplementedError()110111 def attr(self, name, lineno=None):112 """Return an attribute node for the current extension. This is useful113 to pass constants on extensions to generated template code.114115 ::116117 self.attr('_my_attribute', lineno=lineno)118 """119 return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)120121 def call_method(122 self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None123 ):124 """Call a method of the extension. This is a shortcut for125 :meth:`attr` + :class:`jinja2.nodes.Call`.126 """127 if args is None:128 args = []129 if kwargs is None:130 kwargs = []131 return nodes.Call(132 self.attr(name, lineno=lineno),133 args,134 kwargs,135 dyn_args,136 dyn_kwargs,137 lineno=lineno,138 )139140141@contextfunction142def _gettext_alias(__context, *args, **kwargs):143 return __context.call(__context.resolve("gettext"), *args, **kwargs)144145146def _make_new_gettext(func):147 @contextfunction148 def gettext(__context, __string, **variables):149 rv = __context.call(func, __string)150 if __context.eval_ctx.autoescape:151 rv = Markup(rv)152 # Always treat as a format string, even if there are no153 # variables. This makes translation strings more consistent154 # and predictable. This requires escaping155 return rv % variables156157 return gettext158159160def _make_new_ngettext(func):161 @contextfunction162 def ngettext(__context, __singular, __plural, __num, **variables):163 variables.setdefault("num", __num)164 rv = __context.call(func, __singular, __plural, __num)165 if __context.eval_ctx.autoescape:166 rv = Markup(rv)167 # Always treat as a format string, see gettext comment above.168 return rv % variables169170 return ngettext171172173class InternationalizationExtension(Extension):174 """This extension adds gettext support to Jinja."""175176 tags = {"trans"}177178 # TODO: the i18n extension is currently reevaluating values in a few179 # situations. Take this example:180 # {% trans count=something() %}{{ count }} foo{% pluralize181 # %}{{ count }} fooss{% endtrans %}182 # something is called twice here. One time for the gettext value and183 # the other time for the n-parameter of the ngettext function.184185 def __init__(self, environment):186 Extension.__init__(self, environment)187 environment.globals["_"] = _gettext_alias188 environment.extend(189 install_gettext_translations=self._install,190 install_null_translations=self._install_null,191 install_gettext_callables=self._install_callables,192 uninstall_gettext_translations=self._uninstall,193 extract_translations=self._extract,194 newstyle_gettext=False,195 )196197 def _install(self, translations, newstyle=None):198 gettext = getattr(translations, "ugettext", None)199 if gettext is None:200 gettext = translations.gettext201 ngettext = getattr(translations, "ungettext", None)202 if ngettext is None:203 ngettext = translations.ngettext204 self._install_callables(gettext, ngettext, newstyle)205206 def _install_null(self, newstyle=None):207 self._install_callables(208 lambda x: x, lambda s, p, n: (n != 1 and (p,) or (s,))[0], newstyle209 )210211 def _install_callables(self, gettext, ngettext, newstyle=None):212 if newstyle is not None:213 self.environment.newstyle_gettext = newstyle214 if self.environment.newstyle_gettext:215 gettext = _make_new_gettext(gettext)216 ngettext = _make_new_ngettext(ngettext)217 self.environment.globals.update(gettext=gettext, ngettext=ngettext)218219 def _uninstall(self, translations):220 for key in "gettext", "ngettext":221 self.environment.globals.pop(key, None)222223 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):224 if isinstance(source, string_types):225 source = self.environment.parse(source)226 return extract_from_ast(source, gettext_functions)227228 def parse(self, parser):229 """Parse a translatable tag."""230 lineno = next(parser.stream).lineno231 num_called_num = False232233 # find all the variables referenced. Additionally a variable can be234 # defined in the body of the trans block too, but this is checked at235 # a later state.236 plural_expr = None237 plural_expr_assignment = None238 variables = {}239 trimmed = None240 while parser.stream.current.type != "block_end":241 if variables:242 parser.stream.expect("comma")243244 # skip colon for python compatibility245 if parser.stream.skip_if("colon"):246 break247248 name = parser.stream.expect("name")249 if name.value in variables:250 parser.fail(251 "translatable variable %r defined twice." % name.value,252 name.lineno,253 exc=TemplateAssertionError,254 )255256 # expressions257 if parser.stream.current.type == "assign":258 next(parser.stream)259 variables[name.value] = var = parser.parse_expression()260 elif trimmed is None and name.value in ("trimmed", "notrimmed"):261 trimmed = name.value == "trimmed"262 continue263 else:264 variables[name.value] = var = nodes.Name(name.value, "load")265266 if plural_expr is None:267 if isinstance(var, nodes.Call):268 plural_expr = nodes.Name("_trans", "load")269 variables[name.value] = plural_expr270 plural_expr_assignment = nodes.Assign(271 nodes.Name("_trans", "store"), var272 )273 else:274 plural_expr = var275 num_called_num = name.value == "num"276277 parser.stream.expect("block_end")278279 plural = None280 have_plural = False281 referenced = set()282283 # now parse until endtrans or pluralize284 singular_names, singular = self._parse_block(parser, True)285 if singular_names:286 referenced.update(singular_names)287 if plural_expr is None:288 plural_expr = nodes.Name(singular_names[0], "load")289 num_called_num = singular_names[0] == "num"290291 # if we have a pluralize block, we parse that too292 if parser.stream.current.test("name:pluralize"):293 have_plural = True294 next(parser.stream)295 if parser.stream.current.type != "block_end":296 name = parser.stream.expect("name")297 if name.value not in variables:298 parser.fail(299 "unknown variable %r for pluralization" % name.value,300 name.lineno,301 exc=TemplateAssertionError,302 )303 plural_expr = variables[name.value]304 num_called_num = name.value == "num"305 parser.stream.expect("block_end")306 plural_names, plural = self._parse_block(parser, False)307 next(parser.stream)308 referenced.update(plural_names)309 else:310 next(parser.stream)311312 # register free names as simple name expressions313 for var in referenced:314 if var not in variables:315 variables[var] = nodes.Name(var, "load")316317 if not have_plural:318 plural_expr = None319 elif plural_expr is None:320 parser.fail("pluralize without variables", lineno)321322 if trimmed is None:323 trimmed = self.environment.policies["ext.i18n.trimmed"]324 if trimmed:325 singular = self._trim_whitespace(singular)326 if plural:327 plural = self._trim_whitespace(plural)328329 node = self._make_node(330 singular,331 plural,332 variables,333 plural_expr,334 bool(referenced),335 num_called_num and have_plural,336 )337 node.set_lineno(lineno)338 if plural_expr_assignment is not None:339 return [plural_expr_assignment, node]340 else:341 return node342343 def _trim_whitespace(self, string, _ws_re=_ws_re):344 return _ws_re.sub(" ", string.strip())345346 def _parse_block(self, parser, allow_pluralize):347 """Parse until the next block tag with a given name."""348 referenced = []349 buf = []350 while 1:351 if parser.stream.current.type == "data":352 buf.append(parser.stream.current.value.replace("%", "%%"))353 next(parser.stream)354 elif parser.stream.current.type == "variable_begin":355 next(parser.stream)356 name = parser.stream.expect("name").value357 referenced.append(name)358 buf.append("%%(%s)s" % name)359 parser.stream.expect("variable_end")360 elif parser.stream.current.type == "block_begin":361 next(parser.stream)362 if parser.stream.current.test("name:endtrans"):363 break364 elif parser.stream.current.test("name:pluralize"):365 if allow_pluralize:366 break367 parser.fail(368 "a translatable section can have only one pluralize section"369 )370 parser.fail(371 "control structures in translatable sections are not allowed"372 )373 elif parser.stream.eos:374 parser.fail("unclosed translation block")375 else:376 raise RuntimeError("internal parser error")377378 return referenced, concat(buf)379380 def _make_node(381 self, singular, plural, variables, plural_expr, vars_referenced, num_called_num382 ):383 """Generates a useful node from the data provided."""384 # no variables referenced? no need to escape for old style385 # gettext invocations only if there are vars.386 if not vars_referenced and not self.environment.newstyle_gettext:387 singular = singular.replace("%%", "%")388 if plural:389 plural = plural.replace("%%", "%")390391 # singular only:392 if plural_expr is None:393 gettext = nodes.Name("gettext", "load")394 node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None)395396 # singular and plural397 else:398 ngettext = nodes.Name("ngettext", "load")399 node = nodes.Call(400 ngettext,401 [nodes.Const(singular), nodes.Const(plural), plural_expr],402 [],403 None,404 None,405 )406407 # in case newstyle gettext is used, the method is powerful408 # enough to handle the variable expansion and autoescape409 # handling itself410 if self.environment.newstyle_gettext:411 for key, value in iteritems(variables):412 # the function adds that later anyways in case num was413 # called num, so just skip it.414 if num_called_num and key == "num":415 continue416 node.kwargs.append(nodes.Keyword(key, value))417418 # otherwise do that here419 else:420 # mark the return value as safe if we are in an421 # environment with autoescaping turned on422 node = nodes.MarkSafeIfAutoescape(node)423 if variables:424 node = nodes.Mod(425 node,426 nodes.Dict(427 [428 nodes.Pair(nodes.Const(key), value)429 for key, value in variables.items()430 ]431 ),432 )433 return nodes.Output([node])434435436class ExprStmtExtension(Extension):437 """Adds a `do` tag to Jinja that works like the print statement just438 that it doesn't print the return value.439 """440441 tags = set(["do"])442443 def parse(self, parser):444 node = nodes.ExprStmt(lineno=next(parser.stream).lineno)445 node.node = parser.parse_tuple()446 return node447448449class LoopControlExtension(Extension):450 """Adds break and continue to the template engine."""451452 tags = set(["break", "continue"])453454 def parse(self, parser):455 token = next(parser.stream)456 if token.value == "break":457 return nodes.Break(lineno=token.lineno)458 return nodes.Continue(lineno=token.lineno)459460461class WithExtension(Extension):462 pass463464465class AutoEscapeExtension(Extension):466 pass467468469class DebugExtension(Extension):470 """A ``{% debug %}`` tag that dumps the available variables,471 filters, and tests.472473 .. code-block:: html+jinja474475 <pre>{% debug %}</pre>476477 .. code-block:: text478479 {'context': {'cycler': <class 'jinja2.utils.Cycler'>,480 ...,481 'namespace': <class 'jinja2.utils.Namespace'>},482 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',483 ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],484 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',485 ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}486487 .. versionadded:: 2.11.0488 """489490 tags = {"debug"}491492 def parse(self, parser):493 lineno = parser.stream.expect("name:debug").lineno494 context = ContextReference()495 result = self.call_method("_render", [context], lineno=lineno)496 return nodes.Output([result], lineno=lineno)497498 def _render(self, context):499 result = {500 "context": context.get_all(),501 "filters": sorted(self.environment.filters.keys()),502 "tests": sorted(self.environment.tests.keys()),503 }504505 # Set the depth since the intent is to show the top few names.506 if version_info[:2] >= (3, 4):507 return pprint.pformat(result, depth=3, compact=True)508 else:509 return pprint.pformat(result, depth=3)510511512def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True):513 """Extract localizable strings from the given template node. Per514 default this function returns matches in babel style that means non string515 parameters as well as keyword arguments are returned as `None`. This516 allows Babel to figure out what you really meant if you are using517 gettext functions that allow keyword arguments for placeholder expansion.518 If you don't want that behavior set the `babel_style` parameter to `False`519 which causes only strings to be returned and parameters are always stored520 in tuples. As a consequence invalid gettext calls (calls without a single521 string parameter or string parameters after non-string parameters) are522 skipped.523524 This example explains the behavior:525526 >>> from jinja2 import Environment527 >>> env = Environment()528 >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')529 >>> list(extract_from_ast(node))530 [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]531 >>> list(extract_from_ast(node, babel_style=False))532 [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]533534 For every string found this function yields a ``(lineno, function,535 message)`` tuple, where:536537 * ``lineno`` is the number of the line on which the string was found,538 * ``function`` is the name of the ``gettext`` function used (if the539 string was extracted from embedded Python code), and540 * ``message`` is the string itself (a ``unicode`` object, or a tuple541 of ``unicode`` objects for functions with multiple string arguments).542543 This extraction function operates on the AST and is because of that unable544 to extract any comments. For comment support you have to use the babel545 extraction interface or extract comments yourself.546 """547 for node in node.find_all(nodes.Call):548 if (549 not isinstance(node.node, nodes.Name)550 or node.node.name not in gettext_functions551 ):552 continue553554 strings = []555 for arg in node.args:556 if isinstance(arg, nodes.Const) and isinstance(arg.value, string_types):557 strings.append(arg.value)558 else:559 strings.append(None)560561 for _ in node.kwargs:562 strings.append(None)563 if node.dyn_args is not None:564 strings.append(None)565 if node.dyn_kwargs is not None:566 strings.append(None)567568 if not babel_style:569 strings = tuple(x for x in strings if x is not None)570 if not strings:571 continue572 else:573 if len(strings) == 1:574 strings = strings[0]575 else:576 strings = tuple(strings)577 yield node.lineno, node.node.name, strings578579580class _CommentFinder(object):581 """Helper class to find comments in a token stream. Can only582 find comments for gettext calls forwards. Once the comment583 from line 4 is found, a comment for line 1 will not return a584 usable value.585 """586587 def __init__(self, tokens, comment_tags):588 self.tokens = tokens589 self.comment_tags = comment_tags590 self.offset = 0591 self.last_lineno = 0592593 def find_backwards(self, offset):594 try:595 for _, token_type, token_value in reversed(596 self.tokens[self.offset : offset]597 ):598 if token_type in ("comment", "linecomment"):599 try:600 prefix, comment = token_value.split(None, 1)601 except ValueError:602 continue603 if prefix in self.comment_tags:604 return [comment.rstrip()]605 return []606 finally:607 self.offset = offset608609 def find_comments(self, lineno):610 if not self.comment_tags or self.last_lineno > lineno:611 return []612 for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):613 if token_lineno > lineno:614 return self.find_backwards(self.offset + idx)615 return self.find_backwards(len(self.tokens))616617618def babel_extract(fileobj, keywords, comment_tags, options):619 """Babel extraction method for Jinja templates.620621 .. versionchanged:: 2.3622 Basic support for translation comments was added. If `comment_tags`623 is now set to a list of keywords for extraction, the extractor will624 try to find the best preceding comment that begins with one of the625 keywords. For best results, make sure to not have more than one626 gettext call in one line of code and the matching comment in the627 same line or the line before.628629 .. versionchanged:: 2.5.1630 The `newstyle_gettext` flag can be set to `True` to enable newstyle631 gettext calls.632633 .. versionchanged:: 2.7634 A `silent` option can now be provided. If set to `False` template635 syntax errors are propagated instead of being ignored.636637 :param fileobj: the file-like object the messages should be extracted from638 :param keywords: a list of keywords (i.e. function names) that should be639 recognized as translation functions640 :param comment_tags: a list of translator tags to search for and include641 in the results.642 :param options: a dictionary of additional options (optional)643 :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.644 (comments will be empty currently)645 """646 extensions = set()647 for extension in options.get("extensions", "").split(","):648 extension = extension.strip()649 if not extension:650 continue651 extensions.add(import_string(extension))652 if InternationalizationExtension not in extensions:653 extensions.add(InternationalizationExtension)654655 def getbool(options, key, default=False):656 return options.get(key, str(default)).lower() in ("1", "on", "yes", "true")657658 silent = getbool(options, "silent", True)659 environment = Environment(660 options.get("block_start_string", BLOCK_START_STRING),661 options.get("block_end_string", BLOCK_END_STRING),662 options.get("variable_start_string", VARIABLE_START_STRING),663 options.get("variable_end_string", VARIABLE_END_STRING),664 options.get("comment_start_string", COMMENT_START_STRING),665 options.get("comment_end_string", COMMENT_END_STRING),666 options.get("line_statement_prefix") or LINE_STATEMENT_PREFIX,667 options.get("line_comment_prefix") or LINE_COMMENT_PREFIX,668 getbool(options, "trim_blocks", TRIM_BLOCKS),669 getbool(options, "lstrip_blocks", LSTRIP_BLOCKS),670 NEWLINE_SEQUENCE,671 getbool(options, "keep_trailing_newline", KEEP_TRAILING_NEWLINE),672 frozenset(extensions),673 cache_size=0,674 auto_reload=False,675 )676677 if getbool(options, "trimmed"):678 environment.policies["ext.i18n.trimmed"] = True679 if getbool(options, "newstyle_gettext"):680 environment.newstyle_gettext = True681682 source = fileobj.read().decode(options.get("encoding", "utf-8"))683 try:684 node = environment.parse(source)685 tokens = list(environment.lex(environment.preprocess(source)))686 except TemplateSyntaxError:687 if not silent:688 raise689 # skip templates with syntax errors690 return691692 finder = _CommentFinder(tokens, comment_tags)693 for lineno, func, message in extract_from_ast(node, keywords):694 yield lineno, func, message, finder.find_comments(lineno)695696697#: nicer import names698i18n = InternationalizationExtension699do = ExprStmtExtension700loopcontrols = LoopControlExtension701with_ = WithExtension702autoescape = AutoEscapeExtension703debug = DebugExtension
deleted:src/jinja2/filters.py-1382 removed
1# -*- coding: utf-8 -*-2"""Built-in template filters used with the ``|`` operator."""3import math4import random5import re6import warnings7from collections import namedtuple8from itertools import chain9from itertools import groupby1011from markupsafe import escape12from markupsafe import Markup13from markupsafe import soft_unicode1415from ._compat import abc16from ._compat import imap17from ._compat import iteritems18from ._compat import string_types19from ._compat import text_type20from .exceptions import FilterArgumentError21from .runtime import Undefined22from .utils import htmlsafe_json_dumps23from .utils import pformat24from .utils import unicode_urlencode25from .utils import urlize2627_word_re = re.compile(r"\w+", re.UNICODE)28_word_beginning_split_re = re.compile(r"([-\s\(\{\[\<]+)", re.UNICODE)293031def contextfilter(f):32 """Decorator for marking context dependent filters. The current33 :class:`Context` will be passed as first argument.34 """35 f.contextfilter = True36 return f373839def evalcontextfilter(f):40 """Decorator for marking eval-context dependent filters. An eval41 context object is passed as first argument. For more information42 about the eval context, see :ref:`eval-context`.4344 .. versionadded:: 2.445 """46 f.evalcontextfilter = True47 return f484950def environmentfilter(f):51 """Decorator for marking environment dependent filters. The current52 :class:`Environment` is passed to the filter as first argument.53 """54 f.environmentfilter = True55 return f565758def ignore_case(value):59 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings60 to lowercase and returns other types as-is."""61 return value.lower() if isinstance(value, string_types) else value626364def make_attrgetter(environment, attribute, postprocess=None, default=None):65 """Returns a callable that looks up the given attribute from a66 passed object with the rules of the environment. Dots are allowed67 to access attributes of attributes. Integer parts in paths are68 looked up as integers.69 """70 attribute = _prepare_attribute_parts(attribute)7172 def attrgetter(item):73 for part in attribute:74 item = environment.getitem(item, part)7576 if default and isinstance(item, Undefined):77 item = default7879 if postprocess is not None:80 item = postprocess(item)8182 return item8384 return attrgetter858687def make_multi_attrgetter(environment, attribute, postprocess=None):88 """Returns a callable that looks up the given comma separated89 attributes from a passed object with the rules of the environment.90 Dots are allowed to access attributes of each attribute. Integer91 parts in paths are looked up as integers.9293 The value returned by the returned callable is a list of extracted94 attribute values.9596 Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.97 """98 attribute_parts = (99 attribute.split(",") if isinstance(attribute, string_types) else [attribute]100 )101 attribute = [102 _prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts103 ]104105 def attrgetter(item):106 items = [None] * len(attribute)107 for i, attribute_part in enumerate(attribute):108 item_i = item109 for part in attribute_part:110 item_i = environment.getitem(item_i, part)111112 if postprocess is not None:113 item_i = postprocess(item_i)114115 items[i] = item_i116 return items117118 return attrgetter119120121def _prepare_attribute_parts(attr):122 if attr is None:123 return []124 elif isinstance(attr, string_types):125 return [int(x) if x.isdigit() else x for x in attr.split(".")]126 else:127 return [attr]128129130def do_forceescape(value):131 """Enforce HTML escaping. This will probably double escape variables."""132 if hasattr(value, "__html__"):133 value = value.__html__()134 return escape(text_type(value))135136137def do_urlencode(value):138 """Quote data for use in a URL path or query using UTF-8.139140 Basic wrapper around :func:`urllib.parse.quote` when given a141 string, or :func:`urllib.parse.urlencode` for a dict or iterable.142143 :param value: Data to quote. A string will be quoted directly. A144 dict or iterable of ``(key, value)`` pairs will be joined as a145 query string.146147 When given a string, "/" is not quoted. HTTP servers treat "/" and148 "%2F" equivalently in paths. If you need quoted slashes, use the149 ``|replace("/", "%2F")`` filter.150151 .. versionadded:: 2.7152 """153 if isinstance(value, string_types) or not isinstance(value, abc.Iterable):154 return unicode_urlencode(value)155156 if isinstance(value, dict):157 items = iteritems(value)158 else:159 items = iter(value)160161 return u"&".join(162 "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))163 for k, v in items164 )165166167@evalcontextfilter168def do_replace(eval_ctx, s, old, new, count=None):169 """Return a copy of the value with all occurrences of a substring170 replaced with a new one. The first argument is the substring171 that should be replaced, the second is the replacement string.172 If the optional third argument ``count`` is given, only the first173 ``count`` occurrences are replaced:174175 .. sourcecode:: jinja176177 {{ "Hello World"|replace("Hello", "Goodbye") }}178 -> Goodbye World179180 {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}181 -> d'oh, d'oh, aaargh182 """183 if count is None:184 count = -1185 if not eval_ctx.autoescape:186 return text_type(s).replace(text_type(old), text_type(new), count)187 if (188 hasattr(old, "__html__")189 or hasattr(new, "__html__")190 and not hasattr(s, "__html__")191 ):192 s = escape(s)193 else:194 s = soft_unicode(s)195 return s.replace(soft_unicode(old), soft_unicode(new), count)196197198def do_upper(s):199 """Convert a value to uppercase."""200 return soft_unicode(s).upper()201202203def do_lower(s):204 """Convert a value to lowercase."""205 return soft_unicode(s).lower()206207208@evalcontextfilter209def do_xmlattr(_eval_ctx, d, autospace=True):210 """Create an SGML/XML attribute string based on the items in a dict.211 All values that are neither `none` nor `undefined` are automatically212 escaped:213214 .. sourcecode:: html+jinja215216 <ul{{ {'class': 'my_list', 'missing': none,217 'id': 'list-%d'|format(variable)}|xmlattr }}>218 ...219 </ul>220221 Results in something like this:222223 .. sourcecode:: html224225 <ul class="my_list" id="list-42">226 ...227 </ul>228229 As you can see it automatically prepends a space in front of the item230 if the filter returned something unless the second parameter is false.231 """232 rv = u" ".join(233 u'%s="%s"' % (escape(key), escape(value))234 for key, value in iteritems(d)235 if value is not None and not isinstance(value, Undefined)236 )237 if autospace and rv:238 rv = u" " + rv239 if _eval_ctx.autoescape:240 rv = Markup(rv)241 return rv242243244def do_capitalize(s):245 """Capitalize a value. The first character will be uppercase, all others246 lowercase.247 """248 return soft_unicode(s).capitalize()249250251def do_title(s):252 """Return a titlecased version of the value. I.e. words will start with253 uppercase letters, all remaining characters are lowercase.254 """255 return "".join(256 [257 item[0].upper() + item[1:].lower()258 for item in _word_beginning_split_re.split(soft_unicode(s))259 if item260 ]261 )262263264def do_dictsort(value, case_sensitive=False, by="key", reverse=False):265 """Sort a dict and yield (key, value) pairs. Because python dicts are266 unsorted you may want to use this function to order them by either267 key or value:268269 .. sourcecode:: jinja270271 {% for item in mydict|dictsort %}272 sort the dict by key, case insensitive273274 {% for item in mydict|dictsort(reverse=true) %}275 sort the dict by key, case insensitive, reverse order276277 {% for item in mydict|dictsort(true) %}278 sort the dict by key, case sensitive279280 {% for item in mydict|dictsort(false, 'value') %}281 sort the dict by value, case insensitive282 """283 if by == "key":284 pos = 0285 elif by == "value":286 pos = 1287 else:288 raise FilterArgumentError('You can only sort by either "key" or "value"')289290 def sort_func(item):291 value = item[pos]292293 if not case_sensitive:294 value = ignore_case(value)295296 return value297298 return sorted(value.items(), key=sort_func, reverse=reverse)299300301@environmentfilter302def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):303 """Sort an iterable using Python's :func:`sorted`.304305 .. sourcecode:: jinja306307 {% for city in cities|sort %}308 ...309 {% endfor %}310311 :param reverse: Sort descending instead of ascending.312 :param case_sensitive: When sorting strings, sort upper and lower313 case separately.314 :param attribute: When sorting objects or dicts, an attribute or315 key to sort by. Can use dot notation like ``"address.city"``.316 Can be a list of attributes like ``"age,name"``.317318 The sort is stable, it does not change the relative order of319 elements that compare equal. This makes it is possible to chain320 sorts on different attributes and ordering.321322 .. sourcecode:: jinja323324 {% for user in users|sort(attribute="name")325 |sort(reverse=true, attribute="age") %}326 ...327 {% endfor %}328329 As a shortcut to chaining when the direction is the same for all330 attributes, pass a comma separate list of attributes.331332 .. sourcecode:: jinja333334 {% for user users|sort(attribute="age,name") %}335 ...336 {% endfor %}337338 .. versionchanged:: 2.11.0339 The ``attribute`` parameter can be a comma separated list of340 attributes, e.g. ``"age,name"``.341342 .. versionchanged:: 2.6343 The ``attribute`` parameter was added.344 """345 key_func = make_multi_attrgetter(346 environment, attribute, postprocess=ignore_case if not case_sensitive else None347 )348 return sorted(value, key=key_func, reverse=reverse)349350351@environmentfilter352def do_unique(environment, value, case_sensitive=False, attribute=None):353 """Returns a list of unique items from the given iterable.354355 .. sourcecode:: jinja356357 {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}358 -> ['foo', 'bar', 'foobar']359360 The unique items are yielded in the same order as their first occurrence in361 the iterable passed to the filter.362363 :param case_sensitive: Treat upper and lower case strings as distinct.364 :param attribute: Filter objects with unique values for this attribute.365 """366 getter = make_attrgetter(367 environment, attribute, postprocess=ignore_case if not case_sensitive else None368 )369 seen = set()370371 for item in value:372 key = getter(item)373374 if key not in seen:375 seen.add(key)376 yield item377378379def _min_or_max(environment, value, func, case_sensitive, attribute):380 it = iter(value)381382 try:383 first = next(it)384 except StopIteration:385 return environment.undefined("No aggregated item, sequence was empty.")386387 key_func = make_attrgetter(388 environment, attribute, postprocess=ignore_case if not case_sensitive else None389 )390 return func(chain([first], it), key=key_func)391392393@environmentfilter394def do_min(environment, value, case_sensitive=False, attribute=None):395 """Return the smallest item from the sequence.396397 .. sourcecode:: jinja398399 {{ [1, 2, 3]|min }}400 -> 1401402 :param case_sensitive: Treat upper and lower case strings as distinct.403 :param attribute: Get the object with the min value of this attribute.404 """405 return _min_or_max(environment, value, min, case_sensitive, attribute)406407408@environmentfilter409def do_max(environment, value, case_sensitive=False, attribute=None):410 """Return the largest item from the sequence.411412 .. sourcecode:: jinja413414 {{ [1, 2, 3]|max }}415 -> 3416417 :param case_sensitive: Treat upper and lower case strings as distinct.418 :param attribute: Get the object with the max value of this attribute.419 """420 return _min_or_max(environment, value, max, case_sensitive, attribute)421422423def do_default(value, default_value=u"", boolean=False):424 """If the value is undefined it will return the passed default value,425 otherwise the value of the variable:426427 .. sourcecode:: jinja428429 {{ my_variable|default('my_variable is not defined') }}430431 This will output the value of ``my_variable`` if the variable was432 defined, otherwise ``'my_variable is not defined'``. If you want433 to use default with variables that evaluate to false you have to434 set the second parameter to `true`:435436 .. sourcecode:: jinja437438 {{ ''|default('the string was empty', true) }}439440 .. versionchanged:: 2.11441 It's now possible to configure the :class:`~jinja2.Environment` with442 :class:`~jinja2.ChainableUndefined` to make the `default` filter work443 on nested elements and attributes that may contain undefined values444 in the chain without getting an :exc:`~jinja2.UndefinedError`.445 """446 if isinstance(value, Undefined) or (boolean and not value):447 return default_value448 return value449450451@evalcontextfilter452def do_join(eval_ctx, value, d=u"", attribute=None):453 """Return a string which is the concatenation of the strings in the454 sequence. The separator between elements is an empty string per455 default, you can define it with the optional parameter:456457 .. sourcecode:: jinja458459 {{ [1, 2, 3]|join('|') }}460 -> 1|2|3461462 {{ [1, 2, 3]|join }}463 -> 123464465 It is also possible to join certain attributes of an object:466467 .. sourcecode:: jinja468469 {{ users|join(', ', attribute='username') }}470471 .. versionadded:: 2.6472 The `attribute` parameter was added.473 """474 if attribute is not None:475 value = imap(make_attrgetter(eval_ctx.environment, attribute), value)476477 # no automatic escaping? joining is a lot easier then478 if not eval_ctx.autoescape:479 return text_type(d).join(imap(text_type, value))480481 # if the delimiter doesn't have an html representation we check482 # if any of the items has. If yes we do a coercion to Markup483 if not hasattr(d, "__html__"):484 value = list(value)485 do_escape = False486 for idx, item in enumerate(value):487 if hasattr(item, "__html__"):488 do_escape = True489 else:490 value[idx] = text_type(item)491 if do_escape:492 d = escape(d)493 else:494 d = text_type(d)495 return d.join(value)496497 # no html involved, to normal joining498 return soft_unicode(d).join(imap(soft_unicode, value))499500501def do_center(value, width=80):502 """Centers the value in a field of a given width."""503 return text_type(value).center(width)504505506@environmentfilter507def do_first(environment, seq):508 """Return the first item of a sequence."""509 try:510 return next(iter(seq))511 except StopIteration:512 return environment.undefined("No first item, sequence was empty.")513514515@environmentfilter516def do_last(environment, seq):517 """518 Return the last item of a sequence.519520 Note: Does not work with generators. You may want to explicitly521 convert it to a list:522523 .. sourcecode:: jinja524525 {{ data | selectattr('name', '==', 'Jinja') | list | last }}526 """527 try:528 return next(iter(reversed(seq)))529 except StopIteration:530 return environment.undefined("No last item, sequence was empty.")531532533@contextfilter534def do_random(context, seq):535 """Return a random item from the sequence."""536 try:537 return random.choice(seq)538 except IndexError:539 return context.environment.undefined("No random item, sequence was empty.")540541542def do_filesizeformat(value, binary=False):543 """Format the value like a 'human-readable' file size (i.e. 13 kB,544 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,545 Giga, etc.), if the second parameter is set to `True` the binary546 prefixes are used (Mebi, Gibi).547 """548 bytes = float(value)549 base = binary and 1024 or 1000550 prefixes = [551 (binary and "KiB" or "kB"),552 (binary and "MiB" or "MB"),553 (binary and "GiB" or "GB"),554 (binary and "TiB" or "TB"),555 (binary and "PiB" or "PB"),556 (binary and "EiB" or "EB"),557 (binary and "ZiB" or "ZB"),558 (binary and "YiB" or "YB"),559 ]560 if bytes == 1:561 return "1 Byte"562 elif bytes < base:563 return "%d Bytes" % bytes564 else:565 for i, prefix in enumerate(prefixes):566 unit = base ** (i + 2)567 if bytes < unit:568 return "%.1f %s" % ((base * bytes / unit), prefix)569 return "%.1f %s" % ((base * bytes / unit), prefix)570571572def do_pprint(value, verbose=False):573 """Pretty print a variable. Useful for debugging.574575 With Jinja 1.2 onwards you can pass it a parameter. If this parameter576 is truthy the output will be more verbose (this requires `pretty`)577 """578 return pformat(value, verbose=verbose)579580581@evalcontextfilter582def do_urlize(583 eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None584):585 """Converts URLs in plain text into clickable links.586587 If you pass the filter an additional integer it will shorten the urls588 to that number. Also a third argument exists that makes the urls589 "nofollow":590591 .. sourcecode:: jinja592593 {{ mytext|urlize(40, true) }}594 links are shortened to 40 chars and defined with rel="nofollow"595596 If *target* is specified, the ``target`` attribute will be added to the597 ``<a>`` tag:598599 .. sourcecode:: jinja600601 {{ mytext|urlize(40, target='_blank') }}602603 .. versionchanged:: 2.8+604 The *target* parameter was added.605 """606 policies = eval_ctx.environment.policies607 rel = set((rel or "").split() or [])608 if nofollow:609 rel.add("nofollow")610 rel.update((policies["urlize.rel"] or "").split())611 if target is None:612 target = policies["urlize.target"]613 rel = " ".join(sorted(rel)) or None614 rv = urlize(value, trim_url_limit, rel=rel, target=target)615 if eval_ctx.autoescape:616 rv = Markup(rv)617 return rv618619620def do_indent(s, width=4, first=False, blank=False, indentfirst=None):621 """Return a copy of the string with each line indented by 4 spaces. The622 first line and blank lines are not indented by default.623624 :param width: Number of spaces to indent by.625 :param first: Don't skip indenting the first line.626 :param blank: Don't skip indenting empty lines.627628 .. versionchanged:: 2.10629 Blank lines are not indented by default.630631 Rename the ``indentfirst`` argument to ``first``.632 """633 if indentfirst is not None:634 warnings.warn(635 "The 'indentfirst' argument is renamed to 'first' and will"636 " be removed in version 3.0.",637 DeprecationWarning,638 stacklevel=2,639 )640 first = indentfirst641642 indention = u" " * width643 newline = u"\n"644645 if isinstance(s, Markup):646 indention = Markup(indention)647 newline = Markup(newline)648649 s += newline # this quirk is necessary for splitlines method650651 if blank:652 rv = (newline + indention).join(s.splitlines())653 else:654 lines = s.splitlines()655 rv = lines.pop(0)656657 if lines:658 rv += newline + newline.join(659 indention + line if line else line for line in lines660 )661662 if first:663 rv = indention + rv664665 return rv666667668@environmentfilter669def do_truncate(env, s, length=255, killwords=False, end="...", leeway=None):670 """Return a truncated copy of the string. The length is specified671 with the first parameter which defaults to ``255``. If the second672 parameter is ``true`` the filter will cut the text at length. Otherwise673 it will discard the last word. If the text was in fact674 truncated it will append an ellipsis sign (``"..."``). If you want a675 different ellipsis sign than ``"..."`` you can specify it using the676 third parameter. Strings that only exceed the length by the tolerance677 margin given in the fourth parameter will not be truncated.678679 .. sourcecode:: jinja680681 {{ "foo bar baz qux"|truncate(9) }}682 -> "foo..."683 {{ "foo bar baz qux"|truncate(9, True) }}684 -> "foo ba..."685 {{ "foo bar baz qux"|truncate(11) }}686 -> "foo bar baz qux"687 {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}688 -> "foo bar..."689690 The default leeway on newer Jinja versions is 5 and was 0 before but691 can be reconfigured globally.692 """693 if leeway is None:694 leeway = env.policies["truncate.leeway"]695 assert length >= len(end), "expected length >= %s, got %s" % (len(end), length)696 assert leeway >= 0, "expected leeway >= 0, got %s" % leeway697 if len(s) <= length + leeway:698 return s699 if killwords:700 return s[: length - len(end)] + end701 result = s[: length - len(end)].rsplit(" ", 1)[0]702 return result + end703704705@environmentfilter706def do_wordwrap(707 environment,708 s,709 width=79,710 break_long_words=True,711 wrapstring=None,712 break_on_hyphens=True,713):714 """Wrap a string to the given width. Existing newlines are treated715 as paragraphs to be wrapped separately.716717 :param s: Original text to wrap.718 :param width: Maximum length of wrapped lines.719 :param break_long_words: If a word is longer than ``width``, break720 it across lines.721 :param break_on_hyphens: If a word contains hyphens, it may be split722 across lines.723 :param wrapstring: String to join each wrapped line. Defaults to724 :attr:`Environment.newline_sequence`.725726 .. versionchanged:: 2.11727 Existing newlines are treated as paragraphs wrapped separately.728729 .. versionchanged:: 2.11730 Added the ``break_on_hyphens`` parameter.731732 .. versionchanged:: 2.7733 Added the ``wrapstring`` parameter.734 """735736 import textwrap737738 if not wrapstring:739 wrapstring = environment.newline_sequence740741 # textwrap.wrap doesn't consider existing newlines when wrapping.742 # If the string has a newline before width, wrap will still insert743 # a newline at width, resulting in a short line. Instead, split and744 # wrap each paragraph individually.745 return wrapstring.join(746 [747 wrapstring.join(748 textwrap.wrap(749 line,750 width=width,751 expand_tabs=False,752 replace_whitespace=False,753 break_long_words=break_long_words,754 break_on_hyphens=break_on_hyphens,755 )756 )757 for line in s.splitlines()758 ]759 )760761762def do_wordcount(s):763 """Count the words in that string."""764 return len(_word_re.findall(s))765766767def do_int(value, default=0, base=10):768 """Convert the value into an integer. If the769 conversion doesn't work it will return ``0``. You can770 override this default using the first parameter. You771 can also override the default base (10) in the second772 parameter, which handles input with prefixes such as773 0b, 0o and 0x for bases 2, 8 and 16 respectively.774 The base is ignored for decimal numbers and non-string values.775 """776 try:777 if isinstance(value, string_types):778 return int(value, base)779 return int(value)780 except (TypeError, ValueError):781 # this quirk is necessary so that "42.23"|int gives 42.782 try:783 return int(float(value))784 except (TypeError, ValueError):785 return default786787788def do_float(value, default=0.0):789 """Convert the value into a floating point number. If the790 conversion doesn't work it will return ``0.0``. You can791 override this default using the first parameter.792 """793 try:794 return float(value)795 except (TypeError, ValueError):796 return default797798799def do_format(value, *args, **kwargs):800 """Apply the given values to a `printf-style`_ format string, like801 ``string % values``.802803 .. sourcecode:: jinja804805 {{ "%s, %s!"|format(greeting, name) }}806 Hello, World!807808 In most cases it should be more convenient and efficient to use the809 ``%`` operator or :meth:`str.format`.810811 .. code-block:: text812813 {{ "%s, %s!" % (greeting, name) }}814 {{ "{}, {}!".format(greeting, name) }}815816 .. _printf-style: https://docs.python.org/library/stdtypes.html817 #printf-style-string-formatting818 """819 if args and kwargs:820 raise FilterArgumentError(821 "can't handle positional and keyword arguments at the same time"822 )823 return soft_unicode(value) % (kwargs or args)824825826def do_trim(value, chars=None):827 """Strip leading and trailing characters, by default whitespace."""828 return soft_unicode(value).strip(chars)829830831def do_striptags(value):832 """Strip SGML/XML tags and replace adjacent whitespace by one space."""833 if hasattr(value, "__html__"):834 value = value.__html__()835 return Markup(text_type(value)).striptags()836837838def do_slice(value, slices, fill_with=None):839 """Slice an iterator and return a list of lists containing840 those items. Useful if you want to create a div containing841 three ul tags that represent columns:842843 .. sourcecode:: html+jinja844845 <div class="columnwrapper">846 {%- for column in items|slice(3) %}847 <ul class="column-{{ loop.index }}">848 {%- for item in column %}849 <li>{{ item }}</li>850 {%- endfor %}851 </ul>852 {%- endfor %}853 </div>854855 If you pass it a second argument it's used to fill missing856 values on the last iteration.857 """858 seq = list(value)859 length = len(seq)860 items_per_slice = length // slices861 slices_with_extra = length % slices862 offset = 0863 for slice_number in range(slices):864 start = offset + slice_number * items_per_slice865 if slice_number < slices_with_extra:866 offset += 1867 end = offset + (slice_number + 1) * items_per_slice868 tmp = seq[start:end]869 if fill_with is not None and slice_number >= slices_with_extra:870 tmp.append(fill_with)871 yield tmp872873874def do_batch(value, linecount, fill_with=None):875 """876 A filter that batches items. It works pretty much like `slice`877 just the other way round. It returns a list of lists with the878 given number of items. If you provide a second parameter this879 is used to fill up missing items. See this example:880881 .. sourcecode:: html+jinja882883 <table>884 {%- for row in items|batch(3, '&nbsp;') %}885 <tr>886 {%- for column in row %}887 <td>{{ column }}</td>888 {%- endfor %}889 </tr>890 {%- endfor %}891 </table>892 """893 tmp = []894 for item in value:895 if len(tmp) == linecount:896 yield tmp897 tmp = []898 tmp.append(item)899 if tmp:900 if fill_with is not None and len(tmp) < linecount:901 tmp += [fill_with] * (linecount - len(tmp))902 yield tmp903904905def do_round(value, precision=0, method="common"):906 """Round the number to a given precision. The first907 parameter specifies the precision (default is ``0``), the908 second the rounding method:909910 - ``'common'`` rounds either up or down911 - ``'ceil'`` always rounds up912 - ``'floor'`` always rounds down913914 If you don't specify a method ``'common'`` is used.915916 .. sourcecode:: jinja917918 {{ 42.55|round }}919 -> 43.0920 {{ 42.55|round(1, 'floor') }}921 -> 42.5922923 Note that even if rounded to 0 precision, a float is returned. If924 you need a real integer, pipe it through `int`:925926 .. sourcecode:: jinja927928 {{ 42.55|round|int }}929 -> 43930 """931 if method not in {"common", "ceil", "floor"}:932 raise FilterArgumentError("method must be common, ceil or floor")933 if method == "common":934 return round(value, precision)935 func = getattr(math, method)936 return func(value * (10 ** precision)) / (10 ** precision)937938939# Use a regular tuple repr here. This is what we did in the past and we940# really want to hide this custom type as much as possible. In particular941# we do not want to accidentally expose an auto generated repr in case942# people start to print this out in comments or something similar for943# debugging.944_GroupTuple = namedtuple("_GroupTuple", ["grouper", "list"])945_GroupTuple.__repr__ = tuple.__repr__946_GroupTuple.__str__ = tuple.__str__947948949@environmentfilter950def do_groupby(environment, value, attribute):951 """Group a sequence of objects by an attribute using Python's952 :func:`itertools.groupby`. The attribute can use dot notation for953 nested access, like ``"address.city"``. Unlike Python's ``groupby``,954 the values are sorted first so only one group is returned for each955 unique value.956957 For example, a list of ``User`` objects with a ``city`` attribute958 can be rendered in groups. In this example, ``grouper`` refers to959 the ``city`` value of the group.960961 .. sourcecode:: html+jinja962963 <ul>{% for city, items in users|groupby("city") %}964 <li>{{ city }}965 <ul>{% for user in items %}966 <li>{{ user.name }}967 {% endfor %}</ul>968 </li>969 {% endfor %}</ul>970971 ``groupby`` yields namedtuples of ``(grouper, list)``, which972 can be used instead of the tuple unpacking above. ``grouper`` is the973 value of the attribute, and ``list`` is the items with that value.974975 .. sourcecode:: html+jinja976977 <ul>{% for group in users|groupby("city") %}978 <li>{{ group.grouper }}: {{ group.list|join(", ") }}979 {% endfor %}</ul>980981 .. versionchanged:: 2.6982 The attribute supports dot notation for nested access.983 """984 expr = make_attrgetter(environment, attribute)985 return [986 _GroupTuple(key, list(values))987 for key, values in groupby(sorted(value, key=expr), expr)988 ]989990991@environmentfilter992def do_sum(environment, iterable, attribute=None, start=0):993 """Returns the sum of a sequence of numbers plus the value of parameter994 'start' (which defaults to 0). When the sequence is empty it returns995 start.996997 It is also possible to sum up only certain attributes:998999 .. sourcecode:: jinja10001001 Total: {{ items|sum(attribute='price') }}10021003 .. versionchanged:: 2.61004 The `attribute` parameter was added to allow suming up over1005 attributes. Also the `start` parameter was moved on to the right.1006 """1007 if attribute is not None:1008 iterable = imap(make_attrgetter(environment, attribute), iterable)1009 return sum(iterable, start)101010111012def do_list(value):1013 """Convert the value into a list. If it was a string the returned list1014 will be a list of characters.1015 """1016 return list(value)101710181019def do_mark_safe(value):1020 """Mark the value as safe which means that in an environment with automatic1021 escaping enabled this variable will not be escaped.1022 """1023 return Markup(value)102410251026def do_mark_unsafe(value):1027 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1028 return text_type(value)102910301031def do_reverse(value):1032 """Reverse the object or return an iterator that iterates over it the other1033 way round.1034 """1035 if isinstance(value, string_types):1036 return value[::-1]1037 try:1038 return reversed(value)1039 except TypeError:1040 try:1041 rv = list(value)1042 rv.reverse()1043 return rv1044 except TypeError:1045 raise FilterArgumentError("argument must be iterable")104610471048@environmentfilter1049def do_attr(environment, obj, name):1050 """Get an attribute of an object. ``foo|attr("bar")`` works like1051 ``foo.bar`` just that always an attribute is returned and items are not1052 looked up.10531054 See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.1055 """1056 try:1057 name = str(name)1058 except UnicodeError:1059 pass1060 else:1061 try:1062 value = getattr(obj, name)1063 except AttributeError:1064 pass1065 else:1066 if environment.sandboxed and not environment.is_safe_attribute(1067 obj, name, value1068 ):1069 return environment.unsafe_undefined(obj, name)1070 return value1071 return environment.undefined(obj=obj, name=name)107210731074@contextfilter1075def do_map(*args, **kwargs):1076 """Applies a filter on a sequence of objects or looks up an attribute.1077 This is useful when dealing with lists of objects but you are really1078 only interested in a certain value of it.10791080 The basic usage is mapping on an attribute. Imagine you have a list1081 of users but you are only interested in a list of usernames:10821083 .. sourcecode:: jinja10841085 Users on this page: {{ users|map(attribute='username')|join(', ') }}10861087 You can specify a ``default`` value to use if an object in the list1088 does not have the given attribute.10891090 .. sourcecode:: jinja10911092 {{ users|map(attribute="username", default="Anonymous")|join(", ") }}10931094 Alternatively you can let it invoke a filter by passing the name of the1095 filter and the arguments afterwards. A good example would be applying a1096 text conversion filter on a sequence:10971098 .. sourcecode:: jinja10991100 Users on this page: {{ titles|map('lower')|join(', ') }}11011102 Similar to a generator comprehension such as:11031104 .. code-block:: python11051106 (u.username for u in users)1107 (u.username or "Anonymous" for u in users)1108 (do_lower(x) for x in titles)11091110 .. versionchanged:: 2.11.01111 Added the ``default`` parameter.11121113 .. versionadded:: 2.71114 """1115 seq, func = prepare_map(args, kwargs)1116 if seq:1117 for item in seq:1118 yield func(item)111911201121@contextfilter1122def do_select(*args, **kwargs):1123 """Filters a sequence of objects by applying a test to each object,1124 and only selecting the objects with the test succeeding.11251126 If no test is specified, each object will be evaluated as a boolean.11271128 Example usage:11291130 .. sourcecode:: jinja11311132 {{ numbers|select("odd") }}1133 {{ numbers|select("odd") }}1134 {{ numbers|select("divisibleby", 3) }}1135 {{ numbers|select("lessthan", 42) }}1136 {{ strings|select("equalto", "mystring") }}11371138 Similar to a generator comprehension such as:11391140 .. code-block:: python11411142 (n for n in numbers if test_odd(n))1143 (n for n in numbers if test_divisibleby(n, 3))11441145 .. versionadded:: 2.71146 """1147 return select_or_reject(args, kwargs, lambda x: x, False)114811491150@contextfilter1151def do_reject(*args, **kwargs):1152 """Filters a sequence of objects by applying a test to each object,1153 and rejecting the objects with the test succeeding.11541155 If no test is specified, each object will be evaluated as a boolean.11561157 Example usage:11581159 .. sourcecode:: jinja11601161 {{ numbers|reject("odd") }}11621163 Similar to a generator comprehension such as:11641165 .. code-block:: python11661167 (n for n in numbers if not test_odd(n))11681169 .. versionadded:: 2.71170 """1171 return select_or_reject(args, kwargs, lambda x: not x, False)117211731174@contextfilter1175def do_selectattr(*args, **kwargs):1176 """Filters a sequence of objects by applying a test to the specified1177 attribute of each object, and only selecting the objects with the1178 test succeeding.11791180 If no test is specified, the attribute's value will be evaluated as1181 a boolean.11821183 Example usage:11841185 .. sourcecode:: jinja11861187 {{ users|selectattr("is_active") }}1188 {{ users|selectattr("email", "none") }}11891190 Similar to a generator comprehension such as:11911192 .. code-block:: python11931194 (u for user in users if user.is_active)1195 (u for user in users if test_none(user.email))11961197 .. versionadded:: 2.71198 """1199 return select_or_reject(args, kwargs, lambda x: x, True)120012011202@contextfilter1203def do_rejectattr(*args, **kwargs):1204 """Filters a sequence of objects by applying a test to the specified1205 attribute of each object, and rejecting the objects with the test1206 succeeding.12071208 If no test is specified, the attribute's value will be evaluated as1209 a boolean.12101211 .. sourcecode:: jinja12121213 {{ users|rejectattr("is_active") }}1214 {{ users|rejectattr("email", "none") }}12151216 Similar to a generator comprehension such as:12171218 .. code-block:: python12191220 (u for user in users if not user.is_active)1221 (u for user in users if not test_none(user.email))12221223 .. versionadded:: 2.71224 """1225 return select_or_reject(args, kwargs, lambda x: not x, True)122612271228@evalcontextfilter1229def do_tojson(eval_ctx, value, indent=None):1230 """Dumps a structure to JSON so that it's safe to use in ``<script>``1231 tags. It accepts the same arguments and returns a JSON string. Note that1232 this is available in templates through the ``|tojson`` filter which will1233 also mark the result as safe. Due to how this function escapes certain1234 characters this is safe even if used outside of ``<script>`` tags.12351236 The following characters are escaped in strings:12371238 - ``<``1239 - ``>``1240 - ``&``1241 - ``'``12421243 This makes it safe to embed such strings in any place in HTML with the1244 notable exception of double quoted attributes. In that case single1245 quote your attributes or HTML escape it in addition.12461247 The indent parameter can be used to enable pretty printing. Set it to1248 the number of spaces that the structures should be indented with.12491250 Note that this filter is for use in HTML contexts only.12511252 .. versionadded:: 2.91253 """1254 policies = eval_ctx.environment.policies1255 dumper = policies["json.dumps_function"]1256 options = policies["json.dumps_kwargs"]1257 if indent is not None:1258 options = dict(options)1259 options["indent"] = indent1260 return htmlsafe_json_dumps(value, dumper=dumper, **options)126112621263def prepare_map(args, kwargs):1264 context = args[0]1265 seq = args[1]1266 default = None12671268 if len(args) == 2 and "attribute" in kwargs:1269 attribute = kwargs.pop("attribute")1270 default = kwargs.pop("default", None)1271 if kwargs:1272 raise FilterArgumentError(1273 "Unexpected keyword argument %r" % next(iter(kwargs))1274 )1275 func = make_attrgetter(context.environment, attribute, default=default)1276 else:1277 try:1278 name = args[2]1279 args = args[3:]1280 except LookupError:1281 raise FilterArgumentError("map requires a filter argument")12821283 def func(item):1284 return context.environment.call_filter(1285 name, item, args, kwargs, context=context1286 )12871288 return seq, func128912901291def prepare_select_or_reject(args, kwargs, modfunc, lookup_attr):1292 context = args[0]1293 seq = args[1]1294 if lookup_attr:1295 try:1296 attr = args[2]1297 except LookupError:1298 raise FilterArgumentError("Missing parameter for attribute name")1299 transfunc = make_attrgetter(context.environment, attr)1300 off = 11301 else:1302 off = 013031304 def transfunc(x):1305 return x13061307 try:1308 name = args[2 + off]1309 args = args[3 + off :]13101311 def func(item):1312 return context.environment.call_test(name, item, args, kwargs)13131314 except LookupError:1315 func = bool13161317 return seq, lambda item: modfunc(func(transfunc(item)))131813191320def select_or_reject(args, kwargs, modfunc, lookup_attr):1321 seq, func = prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)1322 if seq:1323 for item in seq:1324 if func(item):1325 yield item132613271328FILTERS = {1329 "abs": abs,1330 "attr": do_attr,1331 "batch": do_batch,1332 "capitalize": do_capitalize,1333 "center": do_center,1334 "count": len,1335 "d": do_default,1336 "default": do_default,1337 "dictsort": do_dictsort,1338 "e": escape,1339 "escape": escape,1340 "filesizeformat": do_filesizeformat,1341 "first": do_first,1342 "float": do_float,1343 "forceescape": do_forceescape,1344 "format": do_format,1345 "groupby": do_groupby,1346 "indent": do_indent,1347 "int": do_int,1348 "join": do_join,1349 "last": do_last,1350 "length": len,1351 "list": do_list,1352 "lower": do_lower,1353 "map": do_map,1354 "min": do_min,1355 "max": do_max,1356 "pprint": do_pprint,1357 "random": do_random,1358 "reject": do_reject,1359 "rejectattr": do_rejectattr,1360 "replace": do_replace,1361 "reverse": do_reverse,1362 "round": do_round,1363 "safe": do_mark_safe,1364 "select": do_select,1365 "selectattr": do_selectattr,1366 "slice": do_slice,1367 "sort": do_sort,1368 "string": soft_unicode,1369 "striptags": do_striptags,1370 "sum": do_sum,1371 "title": do_title,1372 "trim": do_trim,1373 "truncate": do_truncate,1374 "unique": do_unique,1375 "upper": do_upper,1376 "urlencode": do_urlencode,1377 "urlize": do_urlize,1378 "wordcount": do_wordcount,1379 "wordwrap": do_wordwrap,1380 "xmlattr": do_xmlattr,1381 "tojson": do_tojson,1382}
deleted:src/jinja2/idtracking.py-290 removed
1from ._compat import iteritems2from .visitor import NodeVisitor34VAR_LOAD_PARAMETER = "param"5VAR_LOAD_RESOLVE = "resolve"6VAR_LOAD_ALIAS = "alias"7VAR_LOAD_UNDEFINED = "undefined"8910def find_symbols(nodes, parent_symbols=None):11 sym = Symbols(parent=parent_symbols)12 visitor = FrameSymbolVisitor(sym)13 for node in nodes:14 visitor.visit(node)15 return sym161718def symbols_for_node(node, parent_symbols=None):19 sym = Symbols(parent=parent_symbols)20 sym.analyze_node(node)21 return sym222324class Symbols(object):25 def __init__(self, parent=None, level=None):26 if level is None:27 if parent is None:28 level = 029 else:30 level = parent.level + 131 self.level = level32 self.parent = parent33 self.refs = {}34 self.loads = {}35 self.stores = set()3637 def analyze_node(self, node, **kwargs):38 visitor = RootVisitor(self)39 visitor.visit(node, **kwargs)4041 def _define_ref(self, name, load=None):42 ident = "l_%d_%s" % (self.level, name)43 self.refs[name] = ident44 if load is not None:45 self.loads[ident] = load46 return ident4748 def find_load(self, target):49 if target in self.loads:50 return self.loads[target]51 if self.parent is not None:52 return self.parent.find_load(target)5354 def find_ref(self, name):55 if name in self.refs:56 return self.refs[name]57 if self.parent is not None:58 return self.parent.find_ref(name)5960 def ref(self, name):61 rv = self.find_ref(name)62 if rv is None:63 raise AssertionError(64 "Tried to resolve a name to a reference that "65 "was unknown to the frame (%r)" % name66 )67 return rv6869 def copy(self):70 rv = object.__new__(self.__class__)71 rv.__dict__.update(self.__dict__)72 rv.refs = self.refs.copy()73 rv.loads = self.loads.copy()74 rv.stores = self.stores.copy()75 return rv7677 def store(self, name):78 self.stores.add(name)7980 # If we have not see the name referenced yet, we need to figure81 # out what to set it to.82 if name not in self.refs:83 # If there is a parent scope we check if the name has a84 # reference there. If it does it means we might have to alias85 # to a variable there.86 if self.parent is not None:87 outer_ref = self.parent.find_ref(name)88 if outer_ref is not None:89 self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref))90 return9192 # Otherwise we can just set it to undefined.93 self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))9495 def declare_parameter(self, name):96 self.stores.add(name)97 return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))9899 def load(self, name):100 target = self.find_ref(name)101 if target is None:102 self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))103104 def branch_update(self, branch_symbols):105 stores = {}106 for branch in branch_symbols:107 for target in branch.stores:108 if target in self.stores:109 continue110 stores[target] = stores.get(target, 0) + 1111112 for sym in branch_symbols:113 self.refs.update(sym.refs)114 self.loads.update(sym.loads)115 self.stores.update(sym.stores)116117 for name, branch_count in iteritems(stores):118 if branch_count == len(branch_symbols):119 continue120 target = self.find_ref(name)121 assert target is not None, "should not happen"122123 if self.parent is not None:124 outer_target = self.parent.find_ref(name)125 if outer_target is not None:126 self.loads[target] = (VAR_LOAD_ALIAS, outer_target)127 continue128 self.loads[target] = (VAR_LOAD_RESOLVE, name)129130 def dump_stores(self):131 rv = {}132 node = self133 while node is not None:134 for name in node.stores:135 if name not in rv:136 rv[name] = self.find_ref(name)137 node = node.parent138 return rv139140 def dump_param_targets(self):141 rv = set()142 node = self143 while node is not None:144 for target, (instr, _) in iteritems(self.loads):145 if instr == VAR_LOAD_PARAMETER:146 rv.add(target)147 node = node.parent148 return rv149150151class RootVisitor(NodeVisitor):152 def __init__(self, symbols):153 self.sym_visitor = FrameSymbolVisitor(symbols)154155 def _simple_visit(self, node, **kwargs):156 for child in node.iter_child_nodes():157 self.sym_visitor.visit(child)158159 visit_Template = (160 visit_Block161 ) = (162 visit_Macro163 ) = (164 visit_FilterBlock165 ) = visit_Scope = visit_If = visit_ScopedEvalContextModifier = _simple_visit166167 def visit_AssignBlock(self, node, **kwargs):168 for child in node.body:169 self.sym_visitor.visit(child)170171 def visit_CallBlock(self, node, **kwargs):172 for child in node.iter_child_nodes(exclude=("call",)):173 self.sym_visitor.visit(child)174175 def visit_OverlayScope(self, node, **kwargs):176 for child in node.body:177 self.sym_visitor.visit(child)178179 def visit_For(self, node, for_branch="body", **kwargs):180 if for_branch == "body":181 self.sym_visitor.visit(node.target, store_as_param=True)182 branch = node.body183 elif for_branch == "else":184 branch = node.else_185 elif for_branch == "test":186 self.sym_visitor.visit(node.target, store_as_param=True)187 if node.test is not None:188 self.sym_visitor.visit(node.test)189 return190 else:191 raise RuntimeError("Unknown for branch")192 for item in branch or ():193 self.sym_visitor.visit(item)194195 def visit_With(self, node, **kwargs):196 for target in node.targets:197 self.sym_visitor.visit(target)198 for child in node.body:199 self.sym_visitor.visit(child)200201 def generic_visit(self, node, *args, **kwargs):202 raise NotImplementedError(203 "Cannot find symbols for %r" % node.__class__.__name__204 )205206207class FrameSymbolVisitor(NodeVisitor):208 """A visitor for `Frame.inspect`."""209210 def __init__(self, symbols):211 self.symbols = symbols212213 def visit_Name(self, node, store_as_param=False, **kwargs):214 """All assignments to names go through this function."""215 if store_as_param or node.ctx == "param":216 self.symbols.declare_parameter(node.name)217 elif node.ctx == "store":218 self.symbols.store(node.name)219 elif node.ctx == "load":220 self.symbols.load(node.name)221222 def visit_NSRef(self, node, **kwargs):223 self.symbols.load(node.name)224225 def visit_If(self, node, **kwargs):226 self.visit(node.test, **kwargs)227228 original_symbols = self.symbols229230 def inner_visit(nodes):231 self.symbols = rv = original_symbols.copy()232 for subnode in nodes:233 self.visit(subnode, **kwargs)234 self.symbols = original_symbols235 return rv236237 body_symbols = inner_visit(node.body)238 elif_symbols = inner_visit(node.elif_)239 else_symbols = inner_visit(node.else_ or ())240241 self.symbols.branch_update([body_symbols, elif_symbols, else_symbols])242243 def visit_Macro(self, node, **kwargs):244 self.symbols.store(node.name)245246 def visit_Import(self, node, **kwargs):247 self.generic_visit(node, **kwargs)248 self.symbols.store(node.target)249250 def visit_FromImport(self, node, **kwargs):251 self.generic_visit(node, **kwargs)252 for name in node.names:253 if isinstance(name, tuple):254 self.symbols.store(name[1])255 else:256 self.symbols.store(name)257258 def visit_Assign(self, node, **kwargs):259 """Visit assignments in the correct order."""260 self.visit(node.node, **kwargs)261 self.visit(node.target, **kwargs)262263 def visit_For(self, node, **kwargs):264 """Visiting stops at for blocks. However the block sequence265 is visited as part of the outer scope.266 """267 self.visit(node.iter, **kwargs)268269 def visit_CallBlock(self, node, **kwargs):270 self.visit(node.call, **kwargs)271272 def visit_FilterBlock(self, node, **kwargs):273 self.visit(node.filter, **kwargs)274275 def visit_With(self, node, **kwargs):276 for target in node.values:277 self.visit(target)278279 def visit_AssignBlock(self, node, **kwargs):280 """Stop visiting at block assigns."""281 self.visit(node.target, **kwargs)282283 def visit_Scope(self, node, **kwargs):284 """Stop visiting at scopes."""285286 def visit_Block(self, node, **kwargs):287 """Stop visiting at blocks."""288289 def visit_OverlayScope(self, node, **kwargs):290 """Do not visit into overlay scopes."""
deleted:src/jinja2/lexer.py-841 removed
1# -*- coding: utf-8 -*-2"""Implements a Jinja / Python combination lexer. The ``Lexer`` class3is used to do some preprocessing. It filters out invalid operators like4the bitshift operators we don't allow in templates. It separates5template code and python code in expressions.6"""7import re8from ast import literal_eval9from collections import deque10from operator import itemgetter1112from ._compat import implements_iterator13from ._compat import intern14from ._compat import iteritems15from ._compat import text_type16from .exceptions import TemplateSyntaxError17from .utils import LRUCache1819# cache for the lexers. Exists in order to be able to have multiple20# environments with the same lexer21_lexer_cache = LRUCache(50)2223# static regular expressions24whitespace_re = re.compile(r"\s+", re.U)25newline_re = re.compile(r"(\r\n|\r|\n)")26string_re = re.compile(27 r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S28)29integer_re = re.compile(r"(\d+_)*\d+")30float_re = re.compile(31 r"""32 (?<!\.) # doesn't start with a .33 (\d+_)*\d+ # digits, possibly _ separated34 (35 (\.(\d+_)*\d+)? # optional fractional part36 e[+\-]?(\d+_)*\d+ # exponent part37 |38 \.(\d+_)*\d+ # required fractional part39 )40 """,41 re.IGNORECASE | re.VERBOSE,42)4344try:45 # check if this Python supports Unicode identifiers46 compile("föö", "<unknown>", "eval")47except SyntaxError:48 # Python 2, no Unicode support, use ASCII identifiers49 name_re = re.compile(r"[a-zA-Z_][a-zA-Z0-9_]*")50 check_ident = False51else:52 # Unicode support, import generated re pattern and set flag to use53 # str.isidentifier to validate during lexing.54 from ._identifier import pattern as name_re5556 check_ident = True5758# internal the tokens and keep references to them59TOKEN_ADD = intern("add")60TOKEN_ASSIGN = intern("assign")61TOKEN_COLON = intern("colon")62TOKEN_COMMA = intern("comma")63TOKEN_DIV = intern("div")64TOKEN_DOT = intern("dot")65TOKEN_EQ = intern("eq")66TOKEN_FLOORDIV = intern("floordiv")67TOKEN_GT = intern("gt")68TOKEN_GTEQ = intern("gteq")69TOKEN_LBRACE = intern("lbrace")70TOKEN_LBRACKET = intern("lbracket")71TOKEN_LPAREN = intern("lparen")72TOKEN_LT = intern("lt")73TOKEN_LTEQ = intern("lteq")74TOKEN_MOD = intern("mod")75TOKEN_MUL = intern("mul")76TOKEN_NE = intern("ne")77TOKEN_PIPE = intern("pipe")78TOKEN_POW = intern("pow")79TOKEN_RBRACE = intern("rbrace")80TOKEN_RBRACKET = intern("rbracket")81TOKEN_RPAREN = intern("rparen")82TOKEN_SEMICOLON = intern("semicolon")83TOKEN_SUB = intern("sub")84TOKEN_TILDE = intern("tilde")85TOKEN_WHITESPACE = intern("whitespace")86TOKEN_FLOAT = intern("float")87TOKEN_INTEGER = intern("integer")88TOKEN_NAME = intern("name")89TOKEN_STRING = intern("string")90TOKEN_OPERATOR = intern("operator")91TOKEN_BLOCK_BEGIN = intern("block_begin")92TOKEN_BLOCK_END = intern("block_end")93TOKEN_VARIABLE_BEGIN = intern("variable_begin")94TOKEN_VARIABLE_END = intern("variable_end")95TOKEN_RAW_BEGIN = intern("raw_begin")96TOKEN_RAW_END = intern("raw_end")97TOKEN_COMMENT_BEGIN = intern("comment_begin")98TOKEN_COMMENT_END = intern("comment_end")99TOKEN_COMMENT = intern("comment")100TOKEN_LINESTATEMENT_BEGIN = intern("linestatement_begin")101TOKEN_LINESTATEMENT_END = intern("linestatement_end")102TOKEN_LINECOMMENT_BEGIN = intern("linecomment_begin")103TOKEN_LINECOMMENT_END = intern("linecomment_end")104TOKEN_LINECOMMENT = intern("linecomment")105TOKEN_DATA = intern("data")106TOKEN_INITIAL = intern("initial")107TOKEN_EOF = intern("eof")108109# bind operators to token types110operators = {111 "+": TOKEN_ADD,112 "-": TOKEN_SUB,113 "/": TOKEN_DIV,114 "//": TOKEN_FLOORDIV,115 "*": TOKEN_MUL,116 "%": TOKEN_MOD,117 "**": TOKEN_POW,118 "~": TOKEN_TILDE,119 "[": TOKEN_LBRACKET,120 "]": TOKEN_RBRACKET,121 "(": TOKEN_LPAREN,122 ")": TOKEN_RPAREN,123 "{": TOKEN_LBRACE,124 "}": TOKEN_RBRACE,125 "==": TOKEN_EQ,126 "!=": TOKEN_NE,127 ">": TOKEN_GT,128 ">=": TOKEN_GTEQ,129 "<": TOKEN_LT,130 "<=": TOKEN_LTEQ,131 "=": TOKEN_ASSIGN,132 ".": TOKEN_DOT,133 ":": TOKEN_COLON,134 "|": TOKEN_PIPE,135 ",": TOKEN_COMMA,136 ";": TOKEN_SEMICOLON,137}138139reverse_operators = dict([(v, k) for k, v in iteritems(operators)])140assert len(operators) == len(reverse_operators), "operators dropped"141operator_re = re.compile(142 "(%s)" % "|".join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))143)144145ignored_tokens = frozenset(146 [147 TOKEN_COMMENT_BEGIN,148 TOKEN_COMMENT,149 TOKEN_COMMENT_END,150 TOKEN_WHITESPACE,151 TOKEN_LINECOMMENT_BEGIN,152 TOKEN_LINECOMMENT_END,153 TOKEN_LINECOMMENT,154 ]155)156ignore_if_empty = frozenset(157 [TOKEN_WHITESPACE, TOKEN_DATA, TOKEN_COMMENT, TOKEN_LINECOMMENT]158)159160161def _describe_token_type(token_type):162 if token_type in reverse_operators:163 return reverse_operators[token_type]164 return {165 TOKEN_COMMENT_BEGIN: "begin of comment",166 TOKEN_COMMENT_END: "end of comment",167 TOKEN_COMMENT: "comment",168 TOKEN_LINECOMMENT: "comment",169 TOKEN_BLOCK_BEGIN: "begin of statement block",170 TOKEN_BLOCK_END: "end of statement block",171 TOKEN_VARIABLE_BEGIN: "begin of print statement",172 TOKEN_VARIABLE_END: "end of print statement",173 TOKEN_LINESTATEMENT_BEGIN: "begin of line statement",174 TOKEN_LINESTATEMENT_END: "end of line statement",175 TOKEN_DATA: "template data / text",176 TOKEN_EOF: "end of template",177 }.get(token_type, token_type)178179180def describe_token(token):181 """Returns a description of the token."""182 if token.type == TOKEN_NAME:183 return token.value184 return _describe_token_type(token.type)185186187def describe_token_expr(expr):188 """Like `describe_token` but for token expressions."""189 if ":" in expr:190 type, value = expr.split(":", 1)191 if type == TOKEN_NAME:192 return value193 else:194 type = expr195 return _describe_token_type(type)196197198def count_newlines(value):199 """Count the number of newline characters in the string. This is200 useful for extensions that filter a stream.201 """202 return len(newline_re.findall(value))203204205def compile_rules(environment):206 """Compiles all the rules from the environment into a list of rules."""207 e = re.escape208 rules = [209 (210 len(environment.comment_start_string),211 TOKEN_COMMENT_BEGIN,212 e(environment.comment_start_string),213 ),214 (215 len(environment.block_start_string),216 TOKEN_BLOCK_BEGIN,217 e(environment.block_start_string),218 ),219 (220 len(environment.variable_start_string),221 TOKEN_VARIABLE_BEGIN,222 e(environment.variable_start_string),223 ),224 ]225226 if environment.line_statement_prefix is not None:227 rules.append(228 (229 len(environment.line_statement_prefix),230 TOKEN_LINESTATEMENT_BEGIN,231 r"^[ \t\v]*" + e(environment.line_statement_prefix),232 )233 )234 if environment.line_comment_prefix is not None:235 rules.append(236 (237 len(environment.line_comment_prefix),238 TOKEN_LINECOMMENT_BEGIN,239 r"(?:^|(?<=\S))[^\S\r\n]*" + e(environment.line_comment_prefix),240 )241 )242243 return [x[1:] for x in sorted(rules, reverse=True)]244245246class Failure(object):247 """Class that raises a `TemplateSyntaxError` if called.248 Used by the `Lexer` to specify known errors.249 """250251 def __init__(self, message, cls=TemplateSyntaxError):252 self.message = message253 self.error_class = cls254255 def __call__(self, lineno, filename):256 raise self.error_class(self.message, lineno, filename)257258259class Token(tuple):260 """Token class."""261262 __slots__ = ()263 lineno, type, value = (property(itemgetter(x)) for x in range(3))264265 def __new__(cls, lineno, type, value):266 return tuple.__new__(cls, (lineno, intern(str(type)), value))267268 def __str__(self):269 if self.type in reverse_operators:270 return reverse_operators[self.type]271 elif self.type == "name":272 return self.value273 return self.type274275 def test(self, expr):276 """Test a token against a token expression. This can either be a277 token type or ``'token_type:token_value'``. This can only test278 against string values and types.279 """280 # here we do a regular string equality check as test_any is usually281 # passed an iterable of not interned strings.282 if self.type == expr:283 return True284 elif ":" in expr:285 return expr.split(":", 1) == [self.type, self.value]286 return False287288 def test_any(self, *iterable):289 """Test against multiple token expressions."""290 for expr in iterable:291 if self.test(expr):292 return True293 return False294295 def __repr__(self):296 return "Token(%r, %r, %r)" % (self.lineno, self.type, self.value)297298299@implements_iterator300class TokenStreamIterator(object):301 """The iterator for tokenstreams. Iterate over the stream302 until the eof token is reached.303 """304305 def __init__(self, stream):306 self.stream = stream307308 def __iter__(self):309 return self310311 def __next__(self):312 token = self.stream.current313 if token.type is TOKEN_EOF:314 self.stream.close()315 raise StopIteration()316 next(self.stream)317 return token318319320@implements_iterator321class TokenStream(object):322 """A token stream is an iterable that yields :class:`Token`\\s. The323 parser however does not iterate over it but calls :meth:`next` to go324 one token ahead. The current active token is stored as :attr:`current`.325 """326327 def __init__(self, generator, name, filename):328 self._iter = iter(generator)329 self._pushed = deque()330 self.name = name331 self.filename = filename332 self.closed = False333 self.current = Token(1, TOKEN_INITIAL, "")334 next(self)335336 def __iter__(self):337 return TokenStreamIterator(self)338339 def __bool__(self):340 return bool(self._pushed) or self.current.type is not TOKEN_EOF341342 __nonzero__ = __bool__ # py2343344 @property345 def eos(self):346 """Are we at the end of the stream?"""347 return not self348349 def push(self, token):350 """Push a token back to the stream."""351 self._pushed.append(token)352353 def look(self):354 """Look at the next token."""355 old_token = next(self)356 result = self.current357 self.push(result)358 self.current = old_token359 return result360361 def skip(self, n=1):362 """Got n tokens ahead."""363 for _ in range(n):364 next(self)365366 def next_if(self, expr):367 """Perform the token test and return the token if it matched.368 Otherwise the return value is `None`.369 """370 if self.current.test(expr):371 return next(self)372373 def skip_if(self, expr):374 """Like :meth:`next_if` but only returns `True` or `False`."""375 return self.next_if(expr) is not None376377 def __next__(self):378 """Go one token ahead and return the old one.379380 Use the built-in :func:`next` instead of calling this directly.381 """382 rv = self.current383 if self._pushed:384 self.current = self._pushed.popleft()385 elif self.current.type is not TOKEN_EOF:386 try:387 self.current = next(self._iter)388 except StopIteration:389 self.close()390 return rv391392 def close(self):393 """Close the stream."""394 self.current = Token(self.current.lineno, TOKEN_EOF, "")395 self._iter = None396 self.closed = True397398 def expect(self, expr):399 """Expect a given token type and return it. This accepts the same400 argument as :meth:`jinja2.lexer.Token.test`.401 """402 if not self.current.test(expr):403 expr = describe_token_expr(expr)404 if self.current.type is TOKEN_EOF:405 raise TemplateSyntaxError(406 "unexpected end of template, expected %r." % expr,407 self.current.lineno,408 self.name,409 self.filename,410 )411 raise TemplateSyntaxError(412 "expected token %r, got %r" % (expr, describe_token(self.current)),413 self.current.lineno,414 self.name,415 self.filename,416 )417 try:418 return self.current419 finally:420 next(self)421422423def get_lexer(environment):424 """Return a lexer which is probably cached."""425 key = (426 environment.block_start_string,427 environment.block_end_string,428 environment.variable_start_string,429 environment.variable_end_string,430 environment.comment_start_string,431 environment.comment_end_string,432 environment.line_statement_prefix,433 environment.line_comment_prefix,434 environment.trim_blocks,435 environment.lstrip_blocks,436 environment.newline_sequence,437 environment.keep_trailing_newline,438 )439 lexer = _lexer_cache.get(key)440 if lexer is None:441 lexer = Lexer(environment)442 _lexer_cache[key] = lexer443 return lexer444445446class OptionalLStrip(tuple):447 """A special tuple for marking a point in the state that can have448 lstrip applied.449 """450451 __slots__ = ()452453 # Even though it looks like a no-op, creating instances fails454 # without this.455 def __new__(cls, *members, **kwargs):456 return super(OptionalLStrip, cls).__new__(cls, members)457458459class Lexer(object):460 """Class that implements a lexer for a given environment. Automatically461 created by the environment class, usually you don't have to do that.462463 Note that the lexer is not automatically bound to an environment.464 Multiple environments can share the same lexer.465 """466467 def __init__(self, environment):468 # shortcuts469 e = re.escape470471 def c(x):472 return re.compile(x, re.M | re.S)473474 # lexing rules for tags475 tag_rules = [476 (whitespace_re, TOKEN_WHITESPACE, None),477 (float_re, TOKEN_FLOAT, None),478 (integer_re, TOKEN_INTEGER, None),479 (name_re, TOKEN_NAME, None),480 (string_re, TOKEN_STRING, None),481 (operator_re, TOKEN_OPERATOR, None),482 ]483484 # assemble the root lexing rule. because "|" is ungreedy485 # we have to sort by length so that the lexer continues working486 # as expected when we have parsing rules like <% for block and487 # <%= for variables. (if someone wants asp like syntax)488 # variables are just part of the rules if variable processing489 # is required.490 root_tag_rules = compile_rules(environment)491492 # block suffix if trimming is enabled493 block_suffix_re = environment.trim_blocks and "\\n?" or ""494495 # If lstrip is enabled, it should not be applied if there is any496 # non-whitespace between the newline and block.497 self.lstrip_unless_re = c(r"[^ \t]") if environment.lstrip_blocks else None498499 self.newline_sequence = environment.newline_sequence500 self.keep_trailing_newline = environment.keep_trailing_newline501502 # global lexing rules503 self.rules = {504 "root": [505 # directives506 (507 c(508 "(.*?)(?:%s)"509 % "|".join(510 [511 r"(?P<raw_begin>%s(\-|\+|)\s*raw\s*(?:\-%s\s*|%s))"512 % (513 e(environment.block_start_string),514 e(environment.block_end_string),515 e(environment.block_end_string),516 )517 ]518 + [519 r"(?P<%s>%s(\-|\+|))" % (n, r)520 for n, r in root_tag_rules521 ]522 )523 ),524 OptionalLStrip(TOKEN_DATA, "#bygroup"),525 "#bygroup",526 ),527 # data528 (c(".+"), TOKEN_DATA, None),529 ],530 # comments531 TOKEN_COMMENT_BEGIN: [532 (533 c(534 r"(.*?)((?:\-%s\s*|%s)%s)"535 % (536 e(environment.comment_end_string),537 e(environment.comment_end_string),538 block_suffix_re,539 )540 ),541 (TOKEN_COMMENT, TOKEN_COMMENT_END),542 "#pop",543 ),544 (c("(.)"), (Failure("Missing end of comment tag"),), None),545 ],546 # blocks547 TOKEN_BLOCK_BEGIN: [548 (549 c(550 r"(?:\-%s\s*|%s)%s"551 % (552 e(environment.block_end_string),553 e(environment.block_end_string),554 block_suffix_re,555 )556 ),557 TOKEN_BLOCK_END,558 "#pop",559 ),560 ]561 + tag_rules,562 # variables563 TOKEN_VARIABLE_BEGIN: [564 (565 c(566 r"\-%s\s*|%s"567 % (568 e(environment.variable_end_string),569 e(environment.variable_end_string),570 )571 ),572 TOKEN_VARIABLE_END,573 "#pop",574 )575 ]576 + tag_rules,577 # raw block578 TOKEN_RAW_BEGIN: [579 (580 c(581 r"(.*?)((?:%s(\-|\+|))\s*endraw\s*(?:\-%s\s*|%s%s))"582 % (583 e(environment.block_start_string),584 e(environment.block_end_string),585 e(environment.block_end_string),586 block_suffix_re,587 )588 ),589 OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END),590 "#pop",591 ),592 (c("(.)"), (Failure("Missing end of raw directive"),), None),593 ],594 # line statements595 TOKEN_LINESTATEMENT_BEGIN: [596 (c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")597 ]598 + tag_rules,599 # line comments600 TOKEN_LINECOMMENT_BEGIN: [601 (602 c(r"(.*?)()(?=\n|$)"),603 (TOKEN_LINECOMMENT, TOKEN_LINECOMMENT_END),604 "#pop",605 )606 ],607 }608609 def _normalize_newlines(self, value):610 """Called for strings and template data to normalize it to unicode."""611 return newline_re.sub(self.newline_sequence, value)612613 def tokenize(self, source, name=None, filename=None, state=None):614 """Calls tokeniter + tokenize and wraps it in a token stream."""615 stream = self.tokeniter(source, name, filename, state)616 return TokenStream(self.wrap(stream, name, filename), name, filename)617618 def wrap(self, stream, name=None, filename=None):619 """This is called with the stream as returned by `tokenize` and wraps620 every token in a :class:`Token` and converts the value.621 """622 for lineno, token, value in stream:623 if token in ignored_tokens:624 continue625 elif token == TOKEN_LINESTATEMENT_BEGIN:626 token = TOKEN_BLOCK_BEGIN627 elif token == TOKEN_LINESTATEMENT_END:628 token = TOKEN_BLOCK_END629 # we are not interested in those tokens in the parser630 elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END):631 continue632 elif token == TOKEN_DATA:633 value = self._normalize_newlines(value)634 elif token == "keyword":635 token = value636 elif token == TOKEN_NAME:637 value = str(value)638 if check_ident and not value.isidentifier():639 raise TemplateSyntaxError(640 "Invalid character in identifier", lineno, name, filename641 )642 elif token == TOKEN_STRING:643 # try to unescape string644 try:645 value = (646 self._normalize_newlines(value[1:-1])647 .encode("ascii", "backslashreplace")648 .decode("unicode-escape")649 )650 except Exception as e:651 msg = str(e).split(":")[-1].strip()652 raise TemplateSyntaxError(msg, lineno, name, filename)653 elif token == TOKEN_INTEGER:654 value = int(value.replace("_", ""))655 elif token == TOKEN_FLOAT:656 # remove all "_" first to support more Python versions657 value = literal_eval(value.replace("_", ""))658 elif token == TOKEN_OPERATOR:659 token = operators[value]660 yield Token(lineno, token, value)661662 def tokeniter(self, source, name, filename=None, state=None):663 """This method tokenizes the text and returns the tokens in a664 generator. Use this method if you just want to tokenize a template.665 """666 source = text_type(source)667 lines = source.splitlines()668 if self.keep_trailing_newline and source:669 for newline in ("\r\n", "\r", "\n"):670 if source.endswith(newline):671 lines.append("")672 break673 source = "\n".join(lines)674 pos = 0675 lineno = 1676 stack = ["root"]677 if state is not None and state != "root":678 assert state in ("variable", "block"), "invalid state"679 stack.append(state + "_begin")680 statetokens = self.rules[stack[-1]]681 source_length = len(source)682 balancing_stack = []683 lstrip_unless_re = self.lstrip_unless_re684685 while 1:686 # tokenizer loop687 for regex, tokens, new_state in statetokens:688 m = regex.match(source, pos)689 # if no match we try again with the next rule690 if m is None:691 continue692693 # we only match blocks and variables if braces / parentheses694 # are balanced. continue parsing with the lower rule which695 # is the operator rule. do this only if the end tags look696 # like operators697 if balancing_stack and tokens in (698 TOKEN_VARIABLE_END,699 TOKEN_BLOCK_END,700 TOKEN_LINESTATEMENT_END,701 ):702 continue703704 # tuples support more options705 if isinstance(tokens, tuple):706 groups = m.groups()707708 if isinstance(tokens, OptionalLStrip):709 # Rule supports lstrip. Match will look like710 # text, block type, whitespace control, type, control, ...711 text = groups[0]712713 # Skipping the text and first type, every other group is the714 # whitespace control for each type. One of the groups will be715 # -, +, or empty string instead of None.716 strip_sign = next(g for g in groups[2::2] if g is not None)717718 if strip_sign == "-":719 # Strip all whitespace between the text and the tag.720 groups = (text.rstrip(),) + groups[1:]721 elif (722 # Not marked for preserving whitespace.723 strip_sign != "+"724 # lstrip is enabled.725 and lstrip_unless_re is not None726 # Not a variable expression.727 and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)728 ):729 # The start of text between the last newline and the tag.730 l_pos = text.rfind("\n") + 1731732 # If there's only whitespace between the newline and the733 # tag, strip it.734 if not lstrip_unless_re.search(text, l_pos):735 groups = (text[:l_pos],) + groups[1:]736737 for idx, token in enumerate(tokens):738 # failure group739 if token.__class__ is Failure:740 raise token(lineno, filename)741 # bygroup is a bit more complex, in that case we742 # yield for the current token the first named743 # group that matched744 elif token == "#bygroup":745 for key, value in iteritems(m.groupdict()):746 if value is not None:747 yield lineno, key, value748 lineno += value.count("\n")749 break750 else:751 raise RuntimeError(752 "%r wanted to resolve "753 "the token dynamically"754 " but no group matched" % regex755 )756 # normal group757 else:758 data = groups[idx]759 if data or token not in ignore_if_empty:760 yield lineno, token, data761 lineno += data.count("\n")762763 # strings as token just are yielded as it.764 else:765 data = m.group()766 # update brace/parentheses balance767 if tokens == TOKEN_OPERATOR:768 if data == "{":769 balancing_stack.append("}")770 elif data == "(":771 balancing_stack.append(")")772 elif data == "[":773 balancing_stack.append("]")774 elif data in ("}", ")", "]"):775 if not balancing_stack:776 raise TemplateSyntaxError(777 "unexpected '%s'" % data, lineno, name, filename778 )779 expected_op = balancing_stack.pop()780 if expected_op != data:781 raise TemplateSyntaxError(782 "unexpected '%s', "783 "expected '%s'" % (data, expected_op),784 lineno,785 name,786 filename,787 )788 # yield items789 if data or tokens not in ignore_if_empty:790 yield lineno, tokens, data791 lineno += data.count("\n")792793 # fetch new position into new variable so that we can check794 # if there is a internal parsing error which would result795 # in an infinite loop796 pos2 = m.end()797798 # handle state changes799 if new_state is not None:800 # remove the uppermost state801 if new_state == "#pop":802 stack.pop()803 # resolve the new state by group checking804 elif new_state == "#bygroup":805 for key, value in iteritems(m.groupdict()):806 if value is not None:807 stack.append(key)808 break809 else:810 raise RuntimeError(811 "%r wanted to resolve the "812 "new state dynamically but"813 " no group matched" % regex814 )815 # direct state name given816 else:817 stack.append(new_state)818 statetokens = self.rules[stack[-1]]819 # we are still at the same position and no stack change.820 # this means a loop without break condition, avoid that and821 # raise error822 elif pos2 == pos:823 raise RuntimeError(824 "%r yielded empty string without stack change" % regex825 )826 # publish new function and start again827 pos = pos2828 break829 # if loop terminated without break we haven't found a single match830 # either we are at the end of the file or we have a problem831 else:832 # end of text833 if pos >= source_length:834 return835 # something went wrong836 raise TemplateSyntaxError(837 "unexpected char %r at %d" % (source[pos], pos),838 lineno,839 name,840 filename,841 )
deleted:src/jinja2/loaders.py-572 removed
1# -*- coding: utf-8 -*-2"""API and implementations for loading templates from different data3sources.4"""5import os6import pkgutil7import sys8import weakref9from hashlib import sha110from importlib import import_module11from os import path12from types import ModuleType1314from ._compat import abc15from ._compat import fspath16from ._compat import iteritems17from ._compat import string_types18from .exceptions import TemplateNotFound19from .utils import internalcode20from .utils import open_if_exists212223def split_template_path(template):24 """Split a path into segments and perform a sanity check. If it detects25 '..' in the path it will raise a `TemplateNotFound` error.26 """27 pieces = []28 for piece in template.split("/"):29 if (30 path.sep in piece31 or (path.altsep and path.altsep in piece)32 or piece == path.pardir33 ):34 raise TemplateNotFound(template)35 elif piece and piece != ".":36 pieces.append(piece)37 return pieces383940class BaseLoader(object):41 """Baseclass for all loaders. Subclass this and override `get_source` to42 implement a custom loading mechanism. The environment provides a43 `get_template` method that calls the loader's `load` method to get the44 :class:`Template` object.4546 A very basic example for a loader that looks up templates on the file47 system could look like this::4849 from jinja2 import BaseLoader, TemplateNotFound50 from os.path import join, exists, getmtime5152 class MyLoader(BaseLoader):5354 def __init__(self, path):55 self.path = path5657 def get_source(self, environment, template):58 path = join(self.path, template)59 if not exists(path):60 raise TemplateNotFound(template)61 mtime = getmtime(path)62 with file(path) as f:63 source = f.read().decode('utf-8')64 return source, path, lambda: mtime == getmtime(path)65 """6667 #: if set to `False` it indicates that the loader cannot provide access68 #: to the source of templates.69 #:70 #: .. versionadded:: 2.471 has_source_access = True7273 def get_source(self, environment, template):74 """Get the template source, filename and reload helper for a template.75 It's passed the environment and template name and has to return a76 tuple in the form ``(source, filename, uptodate)`` or raise a77 `TemplateNotFound` error if it can't locate the template.7879 The source part of the returned tuple must be the source of the80 template as unicode string or a ASCII bytestring. The filename should81 be the name of the file on the filesystem if it was loaded from there,82 otherwise `None`. The filename is used by python for the tracebacks83 if no loader extension is used.8485 The last item in the tuple is the `uptodate` function. If auto86 reloading is enabled it's always called to check if the template87 changed. No arguments are passed so the function must store the88 old state somewhere (for example in a closure). If it returns `False`89 the template will be reloaded.90 """91 if not self.has_source_access:92 raise RuntimeError(93 "%s cannot provide access to the source" % self.__class__.__name__94 )95 raise TemplateNotFound(template)9697 def list_templates(self):98 """Iterates over all templates. If the loader does not support that99 it should raise a :exc:`TypeError` which is the default behavior.100 """101 raise TypeError("this loader cannot iterate over all templates")102103 @internalcode104 def load(self, environment, name, globals=None):105 """Loads a template. This method looks up the template in the cache106 or loads one by calling :meth:`get_source`. Subclasses should not107 override this method as loaders working on collections of other108 loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)109 will not call this method but `get_source` directly.110 """111 code = None112 if globals is None:113 globals = {}114115 # first we try to get the source for this template together116 # with the filename and the uptodate function.117 source, filename, uptodate = self.get_source(environment, name)118119 # try to load the code from the bytecode cache if there is a120 # bytecode cache configured.121 bcc = environment.bytecode_cache122 if bcc is not None:123 bucket = bcc.get_bucket(environment, name, filename, source)124 code = bucket.code125126 # if we don't have code so far (not cached, no longer up to127 # date) etc. we compile the template128 if code is None:129 code = environment.compile(source, name, filename)130131 # if the bytecode cache is available and the bucket doesn't132 # have a code so far, we give the bucket the new code and put133 # it back to the bytecode cache.134 if bcc is not None and bucket.code is None:135 bucket.code = code136 bcc.set_bucket(bucket)137138 return environment.template_class.from_code(139 environment, code, globals, uptodate140 )141142143class FileSystemLoader(BaseLoader):144 """Loads templates from the file system. This loader can find templates145 in folders on the file system and is the preferred way to load them.146147 The loader takes the path to the templates as string, or if multiple148 locations are wanted a list of them which is then looked up in the149 given order::150151 >>> loader = FileSystemLoader('/path/to/templates')152 >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])153154 Per default the template encoding is ``'utf-8'`` which can be changed155 by setting the `encoding` parameter to something else.156157 To follow symbolic links, set the *followlinks* parameter to ``True``::158159 >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)160161 .. versionchanged:: 2.8162 The ``followlinks`` parameter was added.163 """164165 def __init__(self, searchpath, encoding="utf-8", followlinks=False):166 if not isinstance(searchpath, abc.Iterable) or isinstance(167 searchpath, string_types168 ):169 searchpath = [searchpath]170171 # In Python 3.5, os.path.join doesn't support Path. This can be172 # simplified to list(searchpath) when Python 3.5 is dropped.173 self.searchpath = [fspath(p) for p in searchpath]174175 self.encoding = encoding176 self.followlinks = followlinks177178 def get_source(self, environment, template):179 pieces = split_template_path(template)180 for searchpath in self.searchpath:181 filename = path.join(searchpath, *pieces)182 f = open_if_exists(filename)183 if f is None:184 continue185 try:186 contents = f.read().decode(self.encoding)187 finally:188 f.close()189190 mtime = path.getmtime(filename)191192 def uptodate():193 try:194 return path.getmtime(filename) == mtime195 except OSError:196 return False197198 return contents, filename, uptodate199 raise TemplateNotFound(template)200201 def list_templates(self):202 found = set()203 for searchpath in self.searchpath:204 walk_dir = os.walk(searchpath, followlinks=self.followlinks)205 for dirpath, _, filenames in walk_dir:206 for filename in filenames:207 template = (208 os.path.join(dirpath, filename)[len(searchpath) :]209 .strip(os.path.sep)210 .replace(os.path.sep, "/")211 )212 if template[:2] == "./":213 template = template[2:]214 if template not in found:215 found.add(template)216 return sorted(found)217218219class PackageLoader(BaseLoader):220 """Load templates from a directory in a Python package.221222 :param package_name: Import name of the package that contains the223 template directory.224 :param package_path: Directory within the imported package that225 contains the templates.226 :param encoding: Encoding of template files.227228 The following example looks up templates in the ``pages`` directory229 within the ``project.ui`` package.230231 .. code-block:: python232233 loader = PackageLoader("project.ui", "pages")234235 Only packages installed as directories (standard pip behavior) or236 zip/egg files (less common) are supported. The Python API for237 introspecting data in packages is too limited to support other238 installation methods the way this loader requires.239240 There is limited support for :pep:`420` namespace packages. The241 template directory is assumed to only be in one namespace242 contributor. Zip files contributing to a namespace are not243 supported.244245 .. versionchanged:: 2.11.0246 No longer uses ``setuptools`` as a dependency.247248 .. versionchanged:: 2.11.0249 Limited PEP 420 namespace package support.250 """251252 def __init__(self, package_name, package_path="templates", encoding="utf-8"):253 if package_path == os.path.curdir:254 package_path = ""255 elif package_path[:2] == os.path.curdir + os.path.sep:256 package_path = package_path[2:]257258 package_path = os.path.normpath(package_path).rstrip(os.path.sep)259 self.package_path = package_path260 self.package_name = package_name261 self.encoding = encoding262263 # Make sure the package exists. This also makes namespace264 # packages work, otherwise get_loader returns None.265 import_module(package_name)266 self._loader = loader = pkgutil.get_loader(package_name)267268 # Zip loader's archive attribute points at the zip.269 self._archive = getattr(loader, "archive", None)270 self._template_root = None271272 if hasattr(loader, "get_filename"):273 # A standard directory package, or a zip package.274 self._template_root = os.path.join(275 os.path.dirname(loader.get_filename(package_name)), package_path276 )277 elif hasattr(loader, "_path"):278 # A namespace package, limited support. Find the first279 # contributor with the template directory.280 for root in loader._path:281 root = os.path.join(root, package_path)282283 if os.path.isdir(root):284 self._template_root = root285 break286287 if self._template_root is None:288 raise ValueError(289 "The %r package was not installed in a way that"290 " PackageLoader understands." % package_name291 )292293 def get_source(self, environment, template):294 p = os.path.join(self._template_root, *split_template_path(template))295296 if self._archive is None:297 # Package is a directory.298 if not os.path.isfile(p):299 raise TemplateNotFound(template)300301 with open(p, "rb") as f:302 source = f.read()303304 mtime = os.path.getmtime(p)305306 def up_to_date():307 return os.path.isfile(p) and os.path.getmtime(p) == mtime308309 else:310 # Package is a zip file.311 try:312 source = self._loader.get_data(p)313 except OSError:314 raise TemplateNotFound(template)315316 # Could use the zip's mtime for all template mtimes, but317 # would need to safely reload the module if it's out of318 # date, so just report it as always current.319 up_to_date = None320321 return source.decode(self.encoding), p, up_to_date322323 def list_templates(self):324 results = []325326 if self._archive is None:327 # Package is a directory.328 offset = len(self._template_root)329330 for dirpath, _, filenames in os.walk(self._template_root):331 dirpath = dirpath[offset:].lstrip(os.path.sep)332 results.extend(333 os.path.join(dirpath, name).replace(os.path.sep, "/")334 for name in filenames335 )336 else:337 if not hasattr(self._loader, "_files"):338 raise TypeError(339 "This zip import does not have the required"340 " metadata to list templates."341 )342343 # Package is a zip file.344 prefix = (345 self._template_root[len(self._archive) :].lstrip(os.path.sep)346 + os.path.sep347 )348 offset = len(prefix)349350 for name in self._loader._files.keys():351 # Find names under the templates directory that aren't directories.352 if name.startswith(prefix) and name[-1] != os.path.sep:353 results.append(name[offset:].replace(os.path.sep, "/"))354355 results.sort()356 return results357358359class DictLoader(BaseLoader):360 """Loads a template from a python dict. It's passed a dict of unicode361 strings bound to template names. This loader is useful for unittesting:362363 >>> loader = DictLoader({'index.html': 'source here'})364365 Because auto reloading is rarely useful this is disabled per default.366 """367368 def __init__(self, mapping):369 self.mapping = mapping370371 def get_source(self, environment, template):372 if template in self.mapping:373 source = self.mapping[template]374 return source, None, lambda: source == self.mapping.get(template)375 raise TemplateNotFound(template)376377 def list_templates(self):378 return sorted(self.mapping)379380381class FunctionLoader(BaseLoader):382 """A loader that is passed a function which does the loading. The383 function receives the name of the template and has to return either384 an unicode string with the template source, a tuple in the form ``(source,385 filename, uptodatefunc)`` or `None` if the template does not exist.386387 >>> def load_template(name):388 ... if name == 'index.html':389 ... return '...'390 ...391 >>> loader = FunctionLoader(load_template)392393 The `uptodatefunc` is a function that is called if autoreload is enabled394 and has to return `True` if the template is still up to date. For more395 details have a look at :meth:`BaseLoader.get_source` which has the same396 return value.397 """398399 def __init__(self, load_func):400 self.load_func = load_func401402 def get_source(self, environment, template):403 rv = self.load_func(template)404 if rv is None:405 raise TemplateNotFound(template)406 elif isinstance(rv, string_types):407 return rv, None, None408 return rv409410411class PrefixLoader(BaseLoader):412 """A loader that is passed a dict of loaders where each loader is bound413 to a prefix. The prefix is delimited from the template by a slash per414 default, which can be changed by setting the `delimiter` argument to415 something else::416417 loader = PrefixLoader({418 'app1': PackageLoader('mypackage.app1'),419 'app2': PackageLoader('mypackage.app2')420 })421422 By loading ``'app1/index.html'`` the file from the app1 package is loaded,423 by loading ``'app2/index.html'`` the file from the second.424 """425426 def __init__(self, mapping, delimiter="/"):427 self.mapping = mapping428 self.delimiter = delimiter429430 def get_loader(self, template):431 try:432 prefix, name = template.split(self.delimiter, 1)433 loader = self.mapping[prefix]434 except (ValueError, KeyError):435 raise TemplateNotFound(template)436 return loader, name437438 def get_source(self, environment, template):439 loader, name = self.get_loader(template)440 try:441 return loader.get_source(environment, name)442 except TemplateNotFound:443 # re-raise the exception with the correct filename here.444 # (the one that includes the prefix)445 raise TemplateNotFound(template)446447 @internalcode448 def load(self, environment, name, globals=None):449 loader, local_name = self.get_loader(name)450 try:451 return loader.load(environment, local_name, globals)452 except TemplateNotFound:453 # re-raise the exception with the correct filename here.454 # (the one that includes the prefix)455 raise TemplateNotFound(name)456457 def list_templates(self):458 result = []459 for prefix, loader in iteritems(self.mapping):460 for template in loader.list_templates():461 result.append(prefix + self.delimiter + template)462 return result463464465class ChoiceLoader(BaseLoader):466 """This loader works like the `PrefixLoader` just that no prefix is467 specified. If a template could not be found by one loader the next one468 is tried.469470 >>> loader = ChoiceLoader([471 ... FileSystemLoader('/path/to/user/templates'),472 ... FileSystemLoader('/path/to/system/templates')473 ... ])474475 This is useful if you want to allow users to override builtin templates476 from a different location.477 """478479 def __init__(self, loaders):480 self.loaders = loaders481482 def get_source(self, environment, template):483 for loader in self.loaders:484 try:485 return loader.get_source(environment, template)486 except TemplateNotFound:487 pass488 raise TemplateNotFound(template)489490 @internalcode491 def load(self, environment, name, globals=None):492 for loader in self.loaders:493 try:494 return loader.load(environment, name, globals)495 except TemplateNotFound:496 pass497 raise TemplateNotFound(name)498499 def list_templates(self):500 found = set()501 for loader in self.loaders:502 found.update(loader.list_templates())503 return sorted(found)504505506class _TemplateModule(ModuleType):507 """Like a normal module but with support for weak references"""508509510class ModuleLoader(BaseLoader):511 """This loader loads templates from precompiled templates.512513 Example usage:514515 >>> loader = ChoiceLoader([516 ... ModuleLoader('/path/to/compiled/templates'),517 ... FileSystemLoader('/path/to/templates')518 ... ])519520 Templates can be precompiled with :meth:`Environment.compile_templates`.521 """522523 has_source_access = False524525 def __init__(self, path):526 package_name = "_jinja2_module_templates_%x" % id(self)527528 # create a fake module that looks for the templates in the529 # path given.530 mod = _TemplateModule(package_name)531532 if not isinstance(path, abc.Iterable) or isinstance(path, string_types):533 path = [path]534535 mod.__path__ = [fspath(p) for p in path]536537 sys.modules[package_name] = weakref.proxy(538 mod, lambda x: sys.modules.pop(package_name, None)539 )540541 # the only strong reference, the sys.modules entry is weak542 # so that the garbage collector can remove it once the543 # loader that created it goes out of business.544 self.module = mod545 self.package_name = package_name546547 @staticmethod548 def get_template_key(name):549 return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()550551 @staticmethod552 def get_module_filename(name):553 return ModuleLoader.get_template_key(name) + ".py"554555 @internalcode556 def load(self, environment, name, globals=None):557 key = self.get_template_key(name)558 module = "%s.%s" % (self.package_name, key)559 mod = getattr(self.module, module, None)560 if mod is None:561 try:562 mod = __import__(module, None, None, ["root"])563 except ImportError:564 raise TemplateNotFound(name)565566 # remove the entry from sys.modules, we only want the attribute567 # on the module object we have stored on the loader.568 sys.modules.pop(module, None)569570 return environment.template_class.from_module_dict(571 environment, mod.__dict__, globals572 )
deleted:src/jinja2/meta.py-101 removed
1# -*- coding: utf-8 -*-2"""Functions that expose information about templates that might be3interesting for introspection.4"""5from . import nodes6from ._compat import iteritems7from ._compat import string_types8from .compiler import CodeGenerator91011class TrackingCodeGenerator(CodeGenerator):12 """We abuse the code generator for introspection."""1314 def __init__(self, environment):15 CodeGenerator.__init__(self, environment, "<introspection>", "<introspection>")16 self.undeclared_identifiers = set()1718 def write(self, x):19 """Don't write."""2021 def enter_frame(self, frame):22 """Remember all undeclared identifiers."""23 CodeGenerator.enter_frame(self, frame)24 for _, (action, param) in iteritems(frame.symbols.loads):25 if action == "resolve" and param not in self.environment.globals:26 self.undeclared_identifiers.add(param)272829def find_undeclared_variables(ast):30 """Returns a set of all variables in the AST that will be looked up from31 the context at runtime. Because at compile time it's not known which32 variables will be used depending on the path the execution takes at33 runtime, all variables are returned.3435 >>> from jinja2 import Environment, meta36 >>> env = Environment()37 >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')38 >>> meta.find_undeclared_variables(ast) == set(['bar'])39 True4041 .. admonition:: Implementation4243 Internally the code generator is used for finding undeclared variables.44 This is good to know because the code generator might raise a45 :exc:`TemplateAssertionError` during compilation and as a matter of46 fact this function can currently raise that exception as well.47 """48 codegen = TrackingCodeGenerator(ast.environment)49 codegen.visit(ast)50 return codegen.undeclared_identifiers515253def find_referenced_templates(ast):54 """Finds all the referenced templates from the AST. This will return an55 iterator over all the hardcoded template extensions, inclusions and56 imports. If dynamic inheritance or inclusion is used, `None` will be57 yielded.5859 >>> from jinja2 import Environment, meta60 >>> env = Environment()61 >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')62 >>> list(meta.find_referenced_templates(ast))63 ['layout.html', None]6465 This function is useful for dependency tracking. For example if you want66 to rebuild parts of the website after a layout template has changed.67 """68 for node in ast.find_all(69 (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)70 ):71 if not isinstance(node.template, nodes.Const):72 # a tuple with some non consts in there73 if isinstance(node.template, (nodes.Tuple, nodes.List)):74 for template_name in node.template.items:75 # something const, only yield the strings and ignore76 # non-string consts that really just make no sense77 if isinstance(template_name, nodes.Const):78 if isinstance(template_name.value, string_types):79 yield template_name.value80 # something dynamic in there81 else:82 yield None83 # something dynamic we don't know about here84 else:85 yield None86 continue87 # constant is a basestring, direct template name88 if isinstance(node.template.value, string_types):89 yield node.template.value90 # a tuple or list (latter *should* not happen) made of consts,91 # yield the consts that are strings. We could warn here for92 # non string values93 elif isinstance(node, nodes.Include) and isinstance(94 node.template.value, (tuple, list)95 ):96 for template_name in node.template.value:97 if isinstance(template_name, string_types):98 yield template_name99 # something else we don't care about, we could warn here100 else:101 yield None
deleted:src/jinja2/nativetypes.py-111 removed
1import types2from ast import literal_eval3from itertools import chain4from itertools import islice56from . import nodes7from ._compat import text_type8from .compiler import CodeGenerator9from .compiler import has_safe_repr10from .environment import Environment11from .environment import Template121314def native_concat(nodes, preserve_quotes=True):15 """Return a native Python type from the list of compiled nodes. If16 the result is a single node, its value is returned. Otherwise, the17 nodes are concatenated as strings. If the result can be parsed with18 :func:`ast.literal_eval`, the parsed value is returned. Otherwise,19 the string is returned.2021 :param nodes: Iterable of nodes to concatenate.22 :param preserve_quotes: Whether to re-wrap literal strings with23 quotes, to preserve quotes around expressions for later parsing.24 Should be ``False`` in :meth:`NativeEnvironment.render`.25 """26 head = list(islice(nodes, 2))2728 if not head:29 return None3031 if len(head) == 1:32 raw = head[0]33 else:34 if isinstance(nodes, types.GeneratorType):35 nodes = chain(head, nodes)36 raw = u"".join([text_type(v) for v in nodes])3738 try:39 literal = literal_eval(raw)40 except (ValueError, SyntaxError, MemoryError):41 return raw4243 # If literal_eval returned a string, re-wrap with the original44 # quote character to avoid dropping quotes between expression nodes.45 # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should46 # be ('a', 'b').47 if preserve_quotes and isinstance(literal, str):48 return "{quote}{}{quote}".format(literal, quote=raw[0])4950 return literal515253class NativeCodeGenerator(CodeGenerator):54 """A code generator which renders Python types by not adding55 ``to_string()`` around output nodes, and using :func:`native_concat`56 to convert complex strings back to Python types if possible.57 """5859 @staticmethod60 def _default_finalize(value):61 return value6263 def _output_const_repr(self, group):64 return repr(native_concat(group))6566 def _output_child_to_const(self, node, frame, finalize):67 const = node.as_const(frame.eval_ctx)6869 if not has_safe_repr(const):70 raise nodes.Impossible()7172 if isinstance(node, nodes.TemplateData):73 return const7475 return finalize.const(const)7677 def _output_child_pre(self, node, frame, finalize):78 if finalize.src is not None:79 self.write(finalize.src)8081 def _output_child_post(self, node, frame, finalize):82 if finalize.src is not None:83 self.write(")")848586class NativeEnvironment(Environment):87 """An environment that renders templates to native Python types."""8889 code_generator_class = NativeCodeGenerator909192class NativeTemplate(Template):93 environment_class = NativeEnvironment9495 def render(self, *args, **kwargs):96 """Render the template to produce a native Python type. If the97 result is a single node, its value is returned. Otherwise, the98 nodes are concatenated as strings. If the result can be parsed99 with :func:`ast.literal_eval`, the parsed value is returned.100 Otherwise, the string is returned.101 """102 vars = dict(*args, **kwargs)103 try:104 return native_concat(105 self.root_render_func(self.new_context(vars)), preserve_quotes=False106 )107 except Exception:108 return self.environment.handle_exception()109110111NativeEnvironment.template_class = NativeTemplate
deleted:src/jinja2/nodes.py-1087 removed
1# -*- coding: utf-8 -*-2"""AST nodes generated by the parser for the compiler. Also provides3some node tree helper functions used by the parser and compiler in order4to normalize nodes.5"""6import operator7from collections import deque89from ._compat import izip10from ._compat import PY211from ._compat import text_type12from ._compat import with_metaclass13from .utils import Markup1415_binop_to_func = {16 "*": operator.mul,17 "/": operator.truediv,18 "//": operator.floordiv,19 "**": operator.pow,20 "%": operator.mod,21 "+": operator.add,22 "-": operator.sub,23}2425_uaop_to_func = {"not": operator.not_, "+": operator.pos, "-": operator.neg}2627_cmpop_to_func = {28 "eq": operator.eq,29 "ne": operator.ne,30 "gt": operator.gt,31 "gteq": operator.ge,32 "lt": operator.lt,33 "lteq": operator.le,34 "in": lambda a, b: a in b,35 "notin": lambda a, b: a not in b,36}373839class Impossible(Exception):40 """Raised if the node could not perform a requested action."""414243class NodeType(type):44 """A metaclass for nodes that handles the field and attribute45 inheritance. fields and attributes from the parent class are46 automatically forwarded to the child."""4748 def __new__(mcs, name, bases, d):49 for attr in "fields", "attributes":50 storage = []51 storage.extend(getattr(bases[0], attr, ()))52 storage.extend(d.get(attr, ()))53 assert len(bases) == 1, "multiple inheritance not allowed"54 assert len(storage) == len(set(storage)), "layout conflict"55 d[attr] = tuple(storage)56 d.setdefault("abstract", False)57 return type.__new__(mcs, name, bases, d)585960class EvalContext(object):61 """Holds evaluation time information. Custom attributes can be attached62 to it in extensions.63 """6465 def __init__(self, environment, template_name=None):66 self.environment = environment67 if callable(environment.autoescape):68 self.autoescape = environment.autoescape(template_name)69 else:70 self.autoescape = environment.autoescape71 self.volatile = False7273 def save(self):74 return self.__dict__.copy()7576 def revert(self, old):77 self.__dict__.clear()78 self.__dict__.update(old)798081def get_eval_context(node, ctx):82 if ctx is None:83 if node.environment is None:84 raise RuntimeError(85 "if no eval context is passed, the "86 "node must have an attached "87 "environment."88 )89 return EvalContext(node.environment)90 return ctx919293class Node(with_metaclass(NodeType, object)):94 """Baseclass for all Jinja nodes. There are a number of nodes available95 of different types. There are four major types:9697 - :class:`Stmt`: statements98 - :class:`Expr`: expressions99 - :class:`Helper`: helper nodes100 - :class:`Template`: the outermost wrapper node101102 All nodes have fields and attributes. Fields may be other nodes, lists,103 or arbitrary values. Fields are passed to the constructor as regular104 positional arguments, attributes as keyword arguments. Each node has105 two attributes: `lineno` (the line number of the node) and `environment`.106 The `environment` attribute is set at the end of the parsing process for107 all nodes automatically.108 """109110 fields = ()111 attributes = ("lineno", "environment")112 abstract = True113114 def __init__(self, *fields, **attributes):115 if self.abstract:116 raise TypeError("abstract nodes are not instantiable")117 if fields:118 if len(fields) != len(self.fields):119 if not self.fields:120 raise TypeError("%r takes 0 arguments" % self.__class__.__name__)121 raise TypeError(122 "%r takes 0 or %d argument%s"123 % (124 self.__class__.__name__,125 len(self.fields),126 len(self.fields) != 1 and "s" or "",127 )128 )129 for name, arg in izip(self.fields, fields):130 setattr(self, name, arg)131 for attr in self.attributes:132 setattr(self, attr, attributes.pop(attr, None))133 if attributes:134 raise TypeError("unknown attribute %r" % next(iter(attributes)))135136 def iter_fields(self, exclude=None, only=None):137 """This method iterates over all fields that are defined and yields138 ``(key, value)`` tuples. Per default all fields are returned, but139 it's possible to limit that to some fields by providing the `only`140 parameter or to exclude some using the `exclude` parameter. Both141 should be sets or tuples of field names.142 """143 for name in self.fields:144 if (145 (exclude is only is None)146 or (exclude is not None and name not in exclude)147 or (only is not None and name in only)148 ):149 try:150 yield name, getattr(self, name)151 except AttributeError:152 pass153154 def iter_child_nodes(self, exclude=None, only=None):155 """Iterates over all direct child nodes of the node. This iterates156 over all fields and yields the values of they are nodes. If the value157 of a field is a list all the nodes in that list are returned.158 """159 for _, item in self.iter_fields(exclude, only):160 if isinstance(item, list):161 for n in item:162 if isinstance(n, Node):163 yield n164 elif isinstance(item, Node):165 yield item166167 def find(self, node_type):168 """Find the first node of a given type. If no such node exists the169 return value is `None`.170 """171 for result in self.find_all(node_type):172 return result173174 def find_all(self, node_type):175 """Find all the nodes of a given type. If the type is a tuple,176 the check is performed for any of the tuple items.177 """178 for child in self.iter_child_nodes():179 if isinstance(child, node_type):180 yield child181 for result in child.find_all(node_type):182 yield result183184 def set_ctx(self, ctx):185 """Reset the context of a node and all child nodes. Per default the186 parser will all generate nodes that have a 'load' context as it's the187 most common one. This method is used in the parser to set assignment188 targets and other nodes to a store context.189 """190 todo = deque([self])191 while todo:192 node = todo.popleft()193 if "ctx" in node.fields:194 node.ctx = ctx195 todo.extend(node.iter_child_nodes())196 return self197198 def set_lineno(self, lineno, override=False):199 """Set the line numbers of the node and children."""200 todo = deque([self])201 while todo:202 node = todo.popleft()203 if "lineno" in node.attributes:204 if node.lineno is None or override:205 node.lineno = lineno206 todo.extend(node.iter_child_nodes())207 return self208209 def set_environment(self, environment):210 """Set the environment for all nodes."""211 todo = deque([self])212 while todo:213 node = todo.popleft()214 node.environment = environment215 todo.extend(node.iter_child_nodes())216 return self217218 def __eq__(self, other):219 return type(self) is type(other) and tuple(self.iter_fields()) == tuple(220 other.iter_fields()221 )222223 def __ne__(self, other):224 return not self.__eq__(other)225226 # Restore Python 2 hashing behavior on Python 3227 __hash__ = object.__hash__228229 def __repr__(self):230 return "%s(%s)" % (231 self.__class__.__name__,232 ", ".join("%s=%r" % (arg, getattr(self, arg, None)) for arg in self.fields),233 )234235 def dump(self):236 def _dump(node):237 if not isinstance(node, Node):238 buf.append(repr(node))239 return240241 buf.append("nodes.%s(" % node.__class__.__name__)242 if not node.fields:243 buf.append(")")244 return245 for idx, field in enumerate(node.fields):246 if idx:247 buf.append(", ")248 value = getattr(node, field)249 if isinstance(value, list):250 buf.append("[")251 for idx, item in enumerate(value):252 if idx:253 buf.append(", ")254 _dump(item)255 buf.append("]")256 else:257 _dump(value)258 buf.append(")")259260 buf = []261 _dump(self)262 return "".join(buf)263264265class Stmt(Node):266 """Base node for all statements."""267268 abstract = True269270271class Helper(Node):272 """Nodes that exist in a specific context only."""273274 abstract = True275276277class Template(Node):278 """Node that represents a template. This must be the outermost node that279 is passed to the compiler.280 """281282 fields = ("body",)283284285class Output(Stmt):286 """A node that holds multiple expressions which are then printed out.287 This is used both for the `print` statement and the regular template data.288 """289290 fields = ("nodes",)291292293class Extends(Stmt):294 """Represents an extends statement."""295296 fields = ("template",)297298299class For(Stmt):300 """The for loop. `target` is the target for the iteration (usually a301 :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list302 of nodes that are used as loop-body, and `else_` a list of nodes for the303 `else` block. If no else node exists it has to be an empty list.304305 For filtered nodes an expression can be stored as `test`, otherwise `None`.306 """307308 fields = ("target", "iter", "body", "else_", "test", "recursive")309310311class If(Stmt):312 """If `test` is true, `body` is rendered, else `else_`."""313314 fields = ("test", "body", "elif_", "else_")315316317class Macro(Stmt):318 """A macro definition. `name` is the name of the macro, `args` a list of319 arguments and `defaults` a list of defaults if there are any. `body` is320 a list of nodes for the macro body.321 """322323 fields = ("name", "args", "defaults", "body")324325326class CallBlock(Stmt):327 """Like a macro without a name but a call instead. `call` is called with328 the unnamed macro as `caller` argument this node holds.329 """330331 fields = ("call", "args", "defaults", "body")332333334class FilterBlock(Stmt):335 """Node for filter sections."""336337 fields = ("body", "filter")338339340class With(Stmt):341 """Specific node for with statements. In older versions of Jinja the342 with statement was implemented on the base of the `Scope` node instead.343344 .. versionadded:: 2.9.3345 """346347 fields = ("targets", "values", "body")348349350class Block(Stmt):351 """A node that represents a block."""352353 fields = ("name", "body", "scoped")354355356class Include(Stmt):357 """A node that represents the include tag."""358359 fields = ("template", "with_context", "ignore_missing")360361362class Import(Stmt):363 """A node that represents the import tag."""364365 fields = ("template", "target", "with_context")366367368class FromImport(Stmt):369 """A node that represents the from import tag. It's important to not370 pass unsafe names to the name attribute. The compiler translates the371 attribute lookups directly into getattr calls and does *not* use the372 subscript callback of the interface. As exported variables may not373 start with double underscores (which the parser asserts) this is not a374 problem for regular Jinja code, but if this node is used in an extension375 extra care must be taken.376377 The list of names may contain tuples if aliases are wanted.378 """379380 fields = ("template", "names", "with_context")381382383class ExprStmt(Stmt):384 """A statement that evaluates an expression and discards the result."""385386 fields = ("node",)387388389class Assign(Stmt):390 """Assigns an expression to a target."""391392 fields = ("target", "node")393394395class AssignBlock(Stmt):396 """Assigns a block to a target."""397398 fields = ("target", "filter", "body")399400401class Expr(Node):402 """Baseclass for all expressions."""403404 abstract = True405406 def as_const(self, eval_ctx=None):407 """Return the value of the expression as constant or raise408 :exc:`Impossible` if this was not possible.409410 An :class:`EvalContext` can be provided, if none is given411 a default context is created which requires the nodes to have412 an attached environment.413414 .. versionchanged:: 2.4415 the `eval_ctx` parameter was added.416 """417 raise Impossible()418419 def can_assign(self):420 """Check if it's possible to assign something to this node."""421 return False422423424class BinExpr(Expr):425 """Baseclass for all binary expressions."""426427 fields = ("left", "right")428 operator = None429 abstract = True430431 def as_const(self, eval_ctx=None):432 eval_ctx = get_eval_context(self, eval_ctx)433 # intercepted operators cannot be folded at compile time434 if (435 self.environment.sandboxed436 and self.operator in self.environment.intercepted_binops437 ):438 raise Impossible()439 f = _binop_to_func[self.operator]440 try:441 return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))442 except Exception:443 raise Impossible()444445446class UnaryExpr(Expr):447 """Baseclass for all unary expressions."""448449 fields = ("node",)450 operator = None451 abstract = True452453 def as_const(self, eval_ctx=None):454 eval_ctx = get_eval_context(self, eval_ctx)455 # intercepted operators cannot be folded at compile time456 if (457 self.environment.sandboxed458 and self.operator in self.environment.intercepted_unops459 ):460 raise Impossible()461 f = _uaop_to_func[self.operator]462 try:463 return f(self.node.as_const(eval_ctx))464 except Exception:465 raise Impossible()466467468class Name(Expr):469 """Looks up a name or stores a value in a name.470 The `ctx` of the node can be one of the following values:471472 - `store`: store a value in the name473 - `load`: load that name474 - `param`: like `store` but if the name was defined as function parameter.475 """476477 fields = ("name", "ctx")478479 def can_assign(self):480 return self.name not in ("true", "false", "none", "True", "False", "None")481482483class NSRef(Expr):484 """Reference to a namespace value assignment"""485486 fields = ("name", "attr")487488 def can_assign(self):489 # We don't need any special checks here; NSRef assignments have a490 # runtime check to ensure the target is a namespace object which will491 # have been checked already as it is created using a normal assignment492 # which goes through a `Name` node.493 return True494495496class Literal(Expr):497 """Baseclass for literals."""498499 abstract = True500501502class Const(Literal):503 """All constant values. The parser will return this node for simple504 constants such as ``42`` or ``"foo"`` but it can be used to store more505 complex values such as lists too. Only constants with a safe506 representation (objects where ``eval(repr(x)) == x`` is true).507 """508509 fields = ("value",)510511 def as_const(self, eval_ctx=None):512 rv = self.value513 if (514 PY2515 and type(rv) is text_type516 and self.environment.policies["compiler.ascii_str"]517 ):518 try:519 rv = rv.encode("ascii")520 except UnicodeError:521 pass522 return rv523524 @classmethod525 def from_untrusted(cls, value, lineno=None, environment=None):526 """Return a const object if the value is representable as527 constant value in the generated code, otherwise it will raise528 an `Impossible` exception.529 """530 from .compiler import has_safe_repr531532 if not has_safe_repr(value):533 raise Impossible()534 return cls(value, lineno=lineno, environment=environment)535536537class TemplateData(Literal):538 """A constant template string."""539540 fields = ("data",)541542 def as_const(self, eval_ctx=None):543 eval_ctx = get_eval_context(self, eval_ctx)544 if eval_ctx.volatile:545 raise Impossible()546 if eval_ctx.autoescape:547 return Markup(self.data)548 return self.data549550551class Tuple(Literal):552 """For loop unpacking and some other things like multiple arguments553 for subscripts. Like for :class:`Name` `ctx` specifies if the tuple554 is used for loading the names or storing.555 """556557 fields = ("items", "ctx")558559 def as_const(self, eval_ctx=None):560 eval_ctx = get_eval_context(self, eval_ctx)561 return tuple(x.as_const(eval_ctx) for x in self.items)562563 def can_assign(self):564 for item in self.items:565 if not item.can_assign():566 return False567 return True568569570class List(Literal):571 """Any list literal such as ``[1, 2, 3]``"""572573 fields = ("items",)574575 def as_const(self, eval_ctx=None):576 eval_ctx = get_eval_context(self, eval_ctx)577 return [x.as_const(eval_ctx) for x in self.items]578579580class Dict(Literal):581 """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of582 :class:`Pair` nodes.583 """584585 fields = ("items",)586587 def as_const(self, eval_ctx=None):588 eval_ctx = get_eval_context(self, eval_ctx)589 return dict(x.as_const(eval_ctx) for x in self.items)590591592class Pair(Helper):593 """A key, value pair for dicts."""594595 fields = ("key", "value")596597 def as_const(self, eval_ctx=None):598 eval_ctx = get_eval_context(self, eval_ctx)599 return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)600601602class Keyword(Helper):603 """A key, value pair for keyword arguments where key is a string."""604605 fields = ("key", "value")606607 def as_const(self, eval_ctx=None):608 eval_ctx = get_eval_context(self, eval_ctx)609 return self.key, self.value.as_const(eval_ctx)610611612class CondExpr(Expr):613 """A conditional expression (inline if expression). (``{{614 foo if bar else baz }}``)615 """616617 fields = ("test", "expr1", "expr2")618619 def as_const(self, eval_ctx=None):620 eval_ctx = get_eval_context(self, eval_ctx)621 if self.test.as_const(eval_ctx):622 return self.expr1.as_const(eval_ctx)623624 # if we evaluate to an undefined object, we better do that at runtime625 if self.expr2 is None:626 raise Impossible()627628 return self.expr2.as_const(eval_ctx)629630631def args_as_const(node, eval_ctx):632 args = [x.as_const(eval_ctx) for x in node.args]633 kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)634635 if node.dyn_args is not None:636 try:637 args.extend(node.dyn_args.as_const(eval_ctx))638 except Exception:639 raise Impossible()640641 if node.dyn_kwargs is not None:642 try:643 kwargs.update(node.dyn_kwargs.as_const(eval_ctx))644 except Exception:645 raise Impossible()646647 return args, kwargs648649650class Filter(Expr):651 """This node applies a filter on an expression. `name` is the name of652 the filter, the rest of the fields are the same as for :class:`Call`.653654 If the `node` of a filter is `None` the contents of the last buffer are655 filtered. Buffers are created by macros and filter blocks.656 """657658 fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")659660 def as_const(self, eval_ctx=None):661 eval_ctx = get_eval_context(self, eval_ctx)662663 if eval_ctx.volatile or self.node is None:664 raise Impossible()665666 # we have to be careful here because we call filter_ below.667 # if this variable would be called filter, 2to3 would wrap the668 # call in a list because it is assuming we are talking about the669 # builtin filter function here which no longer returns a list in670 # python 3. because of that, do not rename filter_ to filter!671 filter_ = self.environment.filters.get(self.name)672673 if filter_ is None or getattr(filter_, "contextfilter", False):674 raise Impossible()675676 # We cannot constant handle async filters, so we need to make sure677 # to not go down this path.678 if eval_ctx.environment.is_async and getattr(679 filter_, "asyncfiltervariant", False680 ):681 raise Impossible()682683 args, kwargs = args_as_const(self, eval_ctx)684 args.insert(0, self.node.as_const(eval_ctx))685686 if getattr(filter_, "evalcontextfilter", False):687 args.insert(0, eval_ctx)688 elif getattr(filter_, "environmentfilter", False):689 args.insert(0, self.environment)690691 try:692 return filter_(*args, **kwargs)693 except Exception:694 raise Impossible()695696697class Test(Expr):698 """Applies a test on an expression. `name` is the name of the test, the699 rest of the fields are the same as for :class:`Call`.700 """701702 fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")703704 def as_const(self, eval_ctx=None):705 test = self.environment.tests.get(self.name)706707 if test is None:708 raise Impossible()709710 eval_ctx = get_eval_context(self, eval_ctx)711 args, kwargs = args_as_const(self, eval_ctx)712 args.insert(0, self.node.as_const(eval_ctx))713714 try:715 return test(*args, **kwargs)716 except Exception:717 raise Impossible()718719720class Call(Expr):721 """Calls an expression. `args` is a list of arguments, `kwargs` a list722 of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`723 and `dyn_kwargs` has to be either `None` or a node that is used as724 node for dynamic positional (``*args``) or keyword (``**kwargs``)725 arguments.726 """727728 fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")729730731class Getitem(Expr):732 """Get an attribute or item from an expression and prefer the item."""733734 fields = ("node", "arg", "ctx")735736 def as_const(self, eval_ctx=None):737 eval_ctx = get_eval_context(self, eval_ctx)738 if self.ctx != "load":739 raise Impossible()740 try:741 return self.environment.getitem(742 self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)743 )744 except Exception:745 raise Impossible()746747 def can_assign(self):748 return False749750751class Getattr(Expr):752 """Get an attribute or item from an expression that is a ascii-only753 bytestring and prefer the attribute.754 """755756 fields = ("node", "attr", "ctx")757758 def as_const(self, eval_ctx=None):759 if self.ctx != "load":760 raise Impossible()761 try:762 eval_ctx = get_eval_context(self, eval_ctx)763 return self.environment.getattr(self.node.as_const(eval_ctx), self.attr)764 except Exception:765 raise Impossible()766767 def can_assign(self):768 return False769770771class Slice(Expr):772 """Represents a slice object. This must only be used as argument for773 :class:`Subscript`.774 """775776 fields = ("start", "stop", "step")777778 def as_const(self, eval_ctx=None):779 eval_ctx = get_eval_context(self, eval_ctx)780781 def const(obj):782 if obj is None:783 return None784 return obj.as_const(eval_ctx)785786 return slice(const(self.start), const(self.stop), const(self.step))787788789class Concat(Expr):790 """Concatenates the list of expressions provided after converting them to791 unicode.792 """793794 fields = ("nodes",)795796 def as_const(self, eval_ctx=None):797 eval_ctx = get_eval_context(self, eval_ctx)798 return "".join(text_type(x.as_const(eval_ctx)) for x in self.nodes)799800801class Compare(Expr):802 """Compares an expression with some other expressions. `ops` must be a803 list of :class:`Operand`\\s.804 """805806 fields = ("expr", "ops")807808 def as_const(self, eval_ctx=None):809 eval_ctx = get_eval_context(self, eval_ctx)810 result = value = self.expr.as_const(eval_ctx)811812 try:813 for op in self.ops:814 new_value = op.expr.as_const(eval_ctx)815 result = _cmpop_to_func[op.op](value, new_value)816817 if not result:818 return False819820 value = new_value821 except Exception:822 raise Impossible()823824 return result825826827class Operand(Helper):828 """Holds an operator and an expression."""829830 fields = ("op", "expr")831832833if __debug__:834 Operand.__doc__ += "\nThe following operators are available: " + ", ".join(835 sorted(836 "``%s``" % x837 for x in set(_binop_to_func) | set(_uaop_to_func) | set(_cmpop_to_func)838 )839 )840841842class Mul(BinExpr):843 """Multiplies the left with the right node."""844845 operator = "*"846847848class Div(BinExpr):849 """Divides the left by the right node."""850851 operator = "/"852853854class FloorDiv(BinExpr):855 """Divides the left by the right node and truncates conver the856 result into an integer by truncating.857 """858859 operator = "//"860861862class Add(BinExpr):863 """Add the left to the right node."""864865 operator = "+"866867868class Sub(BinExpr):869 """Subtract the right from the left node."""870871 operator = "-"872873874class Mod(BinExpr):875 """Left modulo right."""876877 operator = "%"878879880class Pow(BinExpr):881 """Left to the power of right."""882883 operator = "**"884885886class And(BinExpr):887 """Short circuited AND."""888889 operator = "and"890891 def as_const(self, eval_ctx=None):892 eval_ctx = get_eval_context(self, eval_ctx)893 return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)894895896class Or(BinExpr):897 """Short circuited OR."""898899 operator = "or"900901 def as_const(self, eval_ctx=None):902 eval_ctx = get_eval_context(self, eval_ctx)903 return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)904905906class Not(UnaryExpr):907 """Negate the expression."""908909 operator = "not"910911912class Neg(UnaryExpr):913 """Make the expression negative."""914915 operator = "-"916917918class Pos(UnaryExpr):919 """Make the expression positive (noop for most expressions)"""920921 operator = "+"922923924# Helpers for extensions925926927class EnvironmentAttribute(Expr):928 """Loads an attribute from the environment object. This is useful for929 extensions that want to call a callback stored on the environment.930 """931932 fields = ("name",)933934935class ExtensionAttribute(Expr):936 """Returns the attribute of an extension bound to the environment.937 The identifier is the identifier of the :class:`Extension`.938939 This node is usually constructed by calling the940 :meth:`~jinja2.ext.Extension.attr` method on an extension.941 """942943 fields = ("identifier", "name")944945946class ImportedName(Expr):947 """If created with an import name the import name is returned on node948 access. For example ``ImportedName('cgi.escape')`` returns the `escape`949 function from the cgi module on evaluation. Imports are optimized by the950 compiler so there is no need to assign them to local variables.951 """952953 fields = ("importname",)954955956class InternalName(Expr):957 """An internal name in the compiler. You cannot create these nodes958 yourself but the parser provides a959 :meth:`~jinja2.parser.Parser.free_identifier` method that creates960 a new identifier for you. This identifier is not available from the961 template and is not threated specially by the compiler.962 """963964 fields = ("name",)965966 def __init__(self):967 raise TypeError(968 "Can't create internal names. Use the "969 "`free_identifier` method on a parser."970 )971972973class MarkSafe(Expr):974 """Mark the wrapped expression as safe (wrap it as `Markup`)."""975976 fields = ("expr",)977978 def as_const(self, eval_ctx=None):979 eval_ctx = get_eval_context(self, eval_ctx)980 return Markup(self.expr.as_const(eval_ctx))981982983class MarkSafeIfAutoescape(Expr):984 """Mark the wrapped expression as safe (wrap it as `Markup`) but985 only if autoescaping is active.986987 .. versionadded:: 2.5988 """989990 fields = ("expr",)991992 def as_const(self, eval_ctx=None):993 eval_ctx = get_eval_context(self, eval_ctx)994 if eval_ctx.volatile:995 raise Impossible()996 expr = self.expr.as_const(eval_ctx)997 if eval_ctx.autoescape:998 return Markup(expr)999 return expr100010011002class ContextReference(Expr):1003 """Returns the current template context. It can be used like a1004 :class:`Name` node, with a ``'load'`` ctx and will return the1005 current :class:`~jinja2.runtime.Context` object.10061007 Here an example that assigns the current template name to a1008 variable named `foo`::10091010 Assign(Name('foo', ctx='store'),1011 Getattr(ContextReference(), 'name'))10121013 This is basically equivalent to using the1014 :func:`~jinja2.contextfunction` decorator when using the1015 high-level API, which causes a reference to the context to be passed1016 as the first argument to a function.1017 """101810191020class DerivedContextReference(Expr):1021 """Return the current template context including locals. Behaves1022 exactly like :class:`ContextReference`, but includes local1023 variables, such as from a ``for`` loop.10241025 .. versionadded:: 2.111026 """102710281029class Continue(Stmt):1030 """Continue a loop."""103110321033class Break(Stmt):1034 """Break a loop."""103510361037class Scope(Stmt):1038 """An artificial scope."""10391040 fields = ("body",)104110421043class OverlayScope(Stmt):1044 """An overlay scope for extensions. This is a largely unoptimized scope1045 that however can be used to introduce completely arbitrary variables into1046 a sub scope from a dictionary or dictionary like object. The `context`1047 field has to evaluate to a dictionary object.10481049 Example usage::10501051 OverlayScope(context=self.call_method('get_context'),1052 body=[...])10531054 .. versionadded:: 2.101055 """10561057 fields = ("context", "body")105810591060class EvalContextModifier(Stmt):1061 """Modifies the eval context. For each option that should be modified,1062 a :class:`Keyword` has to be added to the :attr:`options` list.10631064 Example to change the `autoescape` setting::10651066 EvalContextModifier(options=[Keyword('autoescape', Const(True))])1067 """10681069 fields = ("options",)107010711072class ScopedEvalContextModifier(EvalContextModifier):1073 """Modifies the eval context and reverts it later. Works exactly like1074 :class:`EvalContextModifier` but will only modify the1075 :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.1076 """10771078 fields = ("body",)107910801081# make sure nobody creates custom nodes1082def _failing_new(*args, **kwargs):1083 raise TypeError("can't create custom node types")108410851086NodeType.__new__ = staticmethod(_failing_new)1087del _failing_new
deleted:src/jinja2/optimizer.py-41 removed
1# -*- coding: utf-8 -*-2"""The optimizer tries to constant fold expressions and modify the AST3in place so that it should be faster to evaluate.45Because the AST does not contain all the scoping information and the6compiler has to find that out, we cannot do all the optimizations we7want. For example, loop unrolling doesn't work because unrolled loops8would have a different scope. The solution would be a second syntax tree9that stored the scoping rules.10"""11from . import nodes12from .visitor import NodeTransformer131415def optimize(node, environment):16 """The context hint can be used to perform an static optimization17 based on the context given."""18 optimizer = Optimizer(environment)19 return optimizer.visit(node)202122class Optimizer(NodeTransformer):23 def __init__(self, environment):24 self.environment = environment2526 def generic_visit(self, node, *args, **kwargs):27 node = super(Optimizer, self).generic_visit(node, *args, **kwargs)2829 # Do constant folding. Some other nodes besides Expr have30 # as_const, but folding them causes errors later on.31 if isinstance(node, nodes.Expr):32 try:33 return nodes.Const.from_untrusted(34 node.as_const(args[0] if args else None),35 lineno=node.lineno,36 environment=self.environment,37 )38 except nodes.Impossible:39 pass4041 return node
deleted:src/jinja2/parser.py-939 removed
1# -*- coding: utf-8 -*-2"""Parse tokens from the lexer into nodes for the compiler."""3from . import nodes4from ._compat import imap5from .exceptions import TemplateAssertionError6from .exceptions import TemplateSyntaxError7from .lexer import describe_token8from .lexer import describe_token_expr910_statement_keywords = frozenset(11 [12 "for",13 "if",14 "block",15 "extends",16 "print",17 "macro",18 "include",19 "from",20 "import",21 "set",22 "with",23 "autoescape",24 ]25)26_compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])2728_math_nodes = {29 "add": nodes.Add,30 "sub": nodes.Sub,31 "mul": nodes.Mul,32 "div": nodes.Div,33 "floordiv": nodes.FloorDiv,34 "mod": nodes.Mod,35}363738class Parser(object):39 """This is the central parsing class Jinja uses. It's passed to40 extensions and can be used to parse expressions or statements.41 """4243 def __init__(self, environment, source, name=None, filename=None, state=None):44 self.environment = environment45 self.stream = environment._tokenize(source, name, filename, state)46 self.name = name47 self.filename = filename48 self.closed = False49 self.extensions = {}50 for extension in environment.iter_extensions():51 for tag in extension.tags:52 self.extensions[tag] = extension.parse53 self._last_identifier = 054 self._tag_stack = []55 self._end_token_stack = []5657 def fail(self, msg, lineno=None, exc=TemplateSyntaxError):58 """Convenience method that raises `exc` with the message, passed59 line number or last line number as well as the current name and60 filename.61 """62 if lineno is None:63 lineno = self.stream.current.lineno64 raise exc(msg, lineno, self.name, self.filename)6566 def _fail_ut_eof(self, name, end_token_stack, lineno):67 expected = []68 for exprs in end_token_stack:69 expected.extend(imap(describe_token_expr, exprs))70 if end_token_stack:71 currently_looking = " or ".join(72 "'%s'" % describe_token_expr(expr) for expr in end_token_stack[-1]73 )74 else:75 currently_looking = None7677 if name is None:78 message = ["Unexpected end of template."]79 else:80 message = ["Encountered unknown tag '%s'." % name]8182 if currently_looking:83 if name is not None and name in expected:84 message.append(85 "You probably made a nesting mistake. Jinja "86 "is expecting this tag, but currently looking "87 "for %s." % currently_looking88 )89 else:90 message.append(91 "Jinja was looking for the following tags: "92 "%s." % currently_looking93 )9495 if self._tag_stack:96 message.append(97 "The innermost block that needs to be "98 "closed is '%s'." % self._tag_stack[-1]99 )100101 self.fail(" ".join(message), lineno)102103 def fail_unknown_tag(self, name, lineno=None):104 """Called if the parser encounters an unknown tag. Tries to fail105 with a human readable error message that could help to identify106 the problem.107 """108 return self._fail_ut_eof(name, self._end_token_stack, lineno)109110 def fail_eof(self, end_tokens=None, lineno=None):111 """Like fail_unknown_tag but for end of template situations."""112 stack = list(self._end_token_stack)113 if end_tokens is not None:114 stack.append(end_tokens)115 return self._fail_ut_eof(None, stack, lineno)116117 def is_tuple_end(self, extra_end_rules=None):118 """Are we at the end of a tuple?"""119 if self.stream.current.type in ("variable_end", "block_end", "rparen"):120 return True121 elif extra_end_rules is not None:122 return self.stream.current.test_any(extra_end_rules)123 return False124125 def free_identifier(self, lineno=None):126 """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""127 self._last_identifier += 1128 rv = object.__new__(nodes.InternalName)129 nodes.Node.__init__(rv, "fi%d" % self._last_identifier, lineno=lineno)130 return rv131132 def parse_statement(self):133 """Parse a single statement."""134 token = self.stream.current135 if token.type != "name":136 self.fail("tag name expected", token.lineno)137 self._tag_stack.append(token.value)138 pop_tag = True139 try:140 if token.value in _statement_keywords:141 return getattr(self, "parse_" + self.stream.current.value)()142 if token.value == "call":143 return self.parse_call_block()144 if token.value == "filter":145 return self.parse_filter_block()146 ext = self.extensions.get(token.value)147 if ext is not None:148 return ext(self)149150 # did not work out, remove the token we pushed by accident151 # from the stack so that the unknown tag fail function can152 # produce a proper error message.153 self._tag_stack.pop()154 pop_tag = False155 self.fail_unknown_tag(token.value, token.lineno)156 finally:157 if pop_tag:158 self._tag_stack.pop()159160 def parse_statements(self, end_tokens, drop_needle=False):161 """Parse multiple statements into a list until one of the end tokens162 is reached. This is used to parse the body of statements as it also163 parses template data if appropriate. The parser checks first if the164 current token is a colon and skips it if there is one. Then it checks165 for the block end and parses until if one of the `end_tokens` is166 reached. Per default the active token in the stream at the end of167 the call is the matched end token. If this is not wanted `drop_needle`168 can be set to `True` and the end token is removed.169 """170 # the first token may be a colon for python compatibility171 self.stream.skip_if("colon")172173 # in the future it would be possible to add whole code sections174 # by adding some sort of end of statement token and parsing those here.175 self.stream.expect("block_end")176 result = self.subparse(end_tokens)177178 # we reached the end of the template too early, the subparser179 # does not check for this, so we do that now180 if self.stream.current.type == "eof":181 self.fail_eof(end_tokens)182183 if drop_needle:184 next(self.stream)185 return result186187 def parse_set(self):188 """Parse an assign statement."""189 lineno = next(self.stream).lineno190 target = self.parse_assign_target(with_namespace=True)191 if self.stream.skip_if("assign"):192 expr = self.parse_tuple()193 return nodes.Assign(target, expr, lineno=lineno)194 filter_node = self.parse_filter(None)195 body = self.parse_statements(("name:endset",), drop_needle=True)196 return nodes.AssignBlock(target, filter_node, body, lineno=lineno)197198 def parse_for(self):199 """Parse a for loop."""200 lineno = self.stream.expect("name:for").lineno201 target = self.parse_assign_target(extra_end_rules=("name:in",))202 self.stream.expect("name:in")203 iter = self.parse_tuple(204 with_condexpr=False, extra_end_rules=("name:recursive",)205 )206 test = None207 if self.stream.skip_if("name:if"):208 test = self.parse_expression()209 recursive = self.stream.skip_if("name:recursive")210 body = self.parse_statements(("name:endfor", "name:else"))211 if next(self.stream).value == "endfor":212 else_ = []213 else:214 else_ = self.parse_statements(("name:endfor",), drop_needle=True)215 return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)216217 def parse_if(self):218 """Parse an if construct."""219 node = result = nodes.If(lineno=self.stream.expect("name:if").lineno)220 while 1:221 node.test = self.parse_tuple(with_condexpr=False)222 node.body = self.parse_statements(("name:elif", "name:else", "name:endif"))223 node.elif_ = []224 node.else_ = []225 token = next(self.stream)226 if token.test("name:elif"):227 node = nodes.If(lineno=self.stream.current.lineno)228 result.elif_.append(node)229 continue230 elif token.test("name:else"):231 result.else_ = self.parse_statements(("name:endif",), drop_needle=True)232 break233 return result234235 def parse_with(self):236 node = nodes.With(lineno=next(self.stream).lineno)237 targets = []238 values = []239 while self.stream.current.type != "block_end":240 if targets:241 self.stream.expect("comma")242 target = self.parse_assign_target()243 target.set_ctx("param")244 targets.append(target)245 self.stream.expect("assign")246 values.append(self.parse_expression())247 node.targets = targets248 node.values = values249 node.body = self.parse_statements(("name:endwith",), drop_needle=True)250 return node251252 def parse_autoescape(self):253 node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)254 node.options = [nodes.Keyword("autoescape", self.parse_expression())]255 node.body = self.parse_statements(("name:endautoescape",), drop_needle=True)256 return nodes.Scope([node])257258 def parse_block(self):259 node = nodes.Block(lineno=next(self.stream).lineno)260 node.name = self.stream.expect("name").value261 node.scoped = self.stream.skip_if("name:scoped")262263 # common problem people encounter when switching from django264 # to jinja. we do not support hyphens in block names, so let's265 # raise a nicer error message in that case.266 if self.stream.current.type == "sub":267 self.fail(268 "Block names in Jinja have to be valid Python "269 "identifiers and may not contain hyphens, use an "270 "underscore instead."271 )272273 node.body = self.parse_statements(("name:endblock",), drop_needle=True)274 self.stream.skip_if("name:" + node.name)275 return node276277 def parse_extends(self):278 node = nodes.Extends(lineno=next(self.stream).lineno)279 node.template = self.parse_expression()280 return node281282 def parse_import_context(self, node, default):283 if self.stream.current.test_any(284 "name:with", "name:without"285 ) and self.stream.look().test("name:context"):286 node.with_context = next(self.stream).value == "with"287 self.stream.skip()288 else:289 node.with_context = default290 return node291292 def parse_include(self):293 node = nodes.Include(lineno=next(self.stream).lineno)294 node.template = self.parse_expression()295 if self.stream.current.test("name:ignore") and self.stream.look().test(296 "name:missing"297 ):298 node.ignore_missing = True299 self.stream.skip(2)300 else:301 node.ignore_missing = False302 return self.parse_import_context(node, True)303304 def parse_import(self):305 node = nodes.Import(lineno=next(self.stream).lineno)306 node.template = self.parse_expression()307 self.stream.expect("name:as")308 node.target = self.parse_assign_target(name_only=True).name309 return self.parse_import_context(node, False)310311 def parse_from(self):312 node = nodes.FromImport(lineno=next(self.stream).lineno)313 node.template = self.parse_expression()314 self.stream.expect("name:import")315 node.names = []316317 def parse_context():318 if self.stream.current.value in (319 "with",320 "without",321 ) and self.stream.look().test("name:context"):322 node.with_context = next(self.stream).value == "with"323 self.stream.skip()324 return True325 return False326327 while 1:328 if node.names:329 self.stream.expect("comma")330 if self.stream.current.type == "name":331 if parse_context():332 break333 target = self.parse_assign_target(name_only=True)334 if target.name.startswith("_"):335 self.fail(336 "names starting with an underline can not be imported",337 target.lineno,338 exc=TemplateAssertionError,339 )340 if self.stream.skip_if("name:as"):341 alias = self.parse_assign_target(name_only=True)342 node.names.append((target.name, alias.name))343 else:344 node.names.append(target.name)345 if parse_context() or self.stream.current.type != "comma":346 break347 else:348 self.stream.expect("name")349 if not hasattr(node, "with_context"):350 node.with_context = False351 return node352353 def parse_signature(self, node):354 node.args = args = []355 node.defaults = defaults = []356 self.stream.expect("lparen")357 while self.stream.current.type != "rparen":358 if args:359 self.stream.expect("comma")360 arg = self.parse_assign_target(name_only=True)361 arg.set_ctx("param")362 if self.stream.skip_if("assign"):363 defaults.append(self.parse_expression())364 elif defaults:365 self.fail("non-default argument follows default argument")366 args.append(arg)367 self.stream.expect("rparen")368369 def parse_call_block(self):370 node = nodes.CallBlock(lineno=next(self.stream).lineno)371 if self.stream.current.type == "lparen":372 self.parse_signature(node)373 else:374 node.args = []375 node.defaults = []376377 node.call = self.parse_expression()378 if not isinstance(node.call, nodes.Call):379 self.fail("expected call", node.lineno)380 node.body = self.parse_statements(("name:endcall",), drop_needle=True)381 return node382383 def parse_filter_block(self):384 node = nodes.FilterBlock(lineno=next(self.stream).lineno)385 node.filter = self.parse_filter(None, start_inline=True)386 node.body = self.parse_statements(("name:endfilter",), drop_needle=True)387 return node388389 def parse_macro(self):390 node = nodes.Macro(lineno=next(self.stream).lineno)391 node.name = self.parse_assign_target(name_only=True).name392 self.parse_signature(node)393 node.body = self.parse_statements(("name:endmacro",), drop_needle=True)394 return node395396 def parse_print(self):397 node = nodes.Output(lineno=next(self.stream).lineno)398 node.nodes = []399 while self.stream.current.type != "block_end":400 if node.nodes:401 self.stream.expect("comma")402 node.nodes.append(self.parse_expression())403 return node404405 def parse_assign_target(406 self,407 with_tuple=True,408 name_only=False,409 extra_end_rules=None,410 with_namespace=False,411 ):412 """Parse an assignment target. As Jinja allows assignments to413 tuples, this function can parse all allowed assignment targets. Per414 default assignments to tuples are parsed, that can be disable however415 by setting `with_tuple` to `False`. If only assignments to names are416 wanted `name_only` can be set to `True`. The `extra_end_rules`417 parameter is forwarded to the tuple parsing function. If418 `with_namespace` is enabled, a namespace assignment may be parsed.419 """420 if with_namespace and self.stream.look().type == "dot":421 token = self.stream.expect("name")422 next(self.stream) # dot423 attr = self.stream.expect("name")424 target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)425 elif name_only:426 token = self.stream.expect("name")427 target = nodes.Name(token.value, "store", lineno=token.lineno)428 else:429 if with_tuple:430 target = self.parse_tuple(431 simplified=True, extra_end_rules=extra_end_rules432 )433 else:434 target = self.parse_primary()435 target.set_ctx("store")436 if not target.can_assign():437 self.fail(438 "can't assign to %r" % target.__class__.__name__.lower(), target.lineno439 )440 return target441442 def parse_expression(self, with_condexpr=True):443 """Parse an expression. Per default all expressions are parsed, if444 the optional `with_condexpr` parameter is set to `False` conditional445 expressions are not parsed.446 """447 if with_condexpr:448 return self.parse_condexpr()449 return self.parse_or()450451 def parse_condexpr(self):452 lineno = self.stream.current.lineno453 expr1 = self.parse_or()454 while self.stream.skip_if("name:if"):455 expr2 = self.parse_or()456 if self.stream.skip_if("name:else"):457 expr3 = self.parse_condexpr()458 else:459 expr3 = None460 expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)461 lineno = self.stream.current.lineno462 return expr1463464 def parse_or(self):465 lineno = self.stream.current.lineno466 left = self.parse_and()467 while self.stream.skip_if("name:or"):468 right = self.parse_and()469 left = nodes.Or(left, right, lineno=lineno)470 lineno = self.stream.current.lineno471 return left472473 def parse_and(self):474 lineno = self.stream.current.lineno475 left = self.parse_not()476 while self.stream.skip_if("name:and"):477 right = self.parse_not()478 left = nodes.And(left, right, lineno=lineno)479 lineno = self.stream.current.lineno480 return left481482 def parse_not(self):483 if self.stream.current.test("name:not"):484 lineno = next(self.stream).lineno485 return nodes.Not(self.parse_not(), lineno=lineno)486 return self.parse_compare()487488 def parse_compare(self):489 lineno = self.stream.current.lineno490 expr = self.parse_math1()491 ops = []492 while 1:493 token_type = self.stream.current.type494 if token_type in _compare_operators:495 next(self.stream)496 ops.append(nodes.Operand(token_type, self.parse_math1()))497 elif self.stream.skip_if("name:in"):498 ops.append(nodes.Operand("in", self.parse_math1()))499 elif self.stream.current.test("name:not") and self.stream.look().test(500 "name:in"501 ):502 self.stream.skip(2)503 ops.append(nodes.Operand("notin", self.parse_math1()))504 else:505 break506 lineno = self.stream.current.lineno507 if not ops:508 return expr509 return nodes.Compare(expr, ops, lineno=lineno)510511 def parse_math1(self):512 lineno = self.stream.current.lineno513 left = self.parse_concat()514 while self.stream.current.type in ("add", "sub"):515 cls = _math_nodes[self.stream.current.type]516 next(self.stream)517 right = self.parse_concat()518 left = cls(left, right, lineno=lineno)519 lineno = self.stream.current.lineno520 return left521522 def parse_concat(self):523 lineno = self.stream.current.lineno524 args = [self.parse_math2()]525 while self.stream.current.type == "tilde":526 next(self.stream)527 args.append(self.parse_math2())528 if len(args) == 1:529 return args[0]530 return nodes.Concat(args, lineno=lineno)531532 def parse_math2(self):533 lineno = self.stream.current.lineno534 left = self.parse_pow()535 while self.stream.current.type in ("mul", "div", "floordiv", "mod"):536 cls = _math_nodes[self.stream.current.type]537 next(self.stream)538 right = self.parse_pow()539 left = cls(left, right, lineno=lineno)540 lineno = self.stream.current.lineno541 return left542543 def parse_pow(self):544 lineno = self.stream.current.lineno545 left = self.parse_unary()546 while self.stream.current.type == "pow":547 next(self.stream)548 right = self.parse_unary()549 left = nodes.Pow(left, right, lineno=lineno)550 lineno = self.stream.current.lineno551 return left552553 def parse_unary(self, with_filter=True):554 token_type = self.stream.current.type555 lineno = self.stream.current.lineno556 if token_type == "sub":557 next(self.stream)558 node = nodes.Neg(self.parse_unary(False), lineno=lineno)559 elif token_type == "add":560 next(self.stream)561 node = nodes.Pos(self.parse_unary(False), lineno=lineno)562 else:563 node = self.parse_primary()564 node = self.parse_postfix(node)565 if with_filter:566 node = self.parse_filter_expr(node)567 return node568569 def parse_primary(self):570 token = self.stream.current571 if token.type == "name":572 if token.value in ("true", "false", "True", "False"):573 node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)574 elif token.value in ("none", "None"):575 node = nodes.Const(None, lineno=token.lineno)576 else:577 node = nodes.Name(token.value, "load", lineno=token.lineno)578 next(self.stream)579 elif token.type == "string":580 next(self.stream)581 buf = [token.value]582 lineno = token.lineno583 while self.stream.current.type == "string":584 buf.append(self.stream.current.value)585 next(self.stream)586 node = nodes.Const("".join(buf), lineno=lineno)587 elif token.type in ("integer", "float"):588 next(self.stream)589 node = nodes.Const(token.value, lineno=token.lineno)590 elif token.type == "lparen":591 next(self.stream)592 node = self.parse_tuple(explicit_parentheses=True)593 self.stream.expect("rparen")594 elif token.type == "lbracket":595 node = self.parse_list()596 elif token.type == "lbrace":597 node = self.parse_dict()598 else:599 self.fail("unexpected '%s'" % describe_token(token), token.lineno)600 return node601602 def parse_tuple(603 self,604 simplified=False,605 with_condexpr=True,606 extra_end_rules=None,607 explicit_parentheses=False,608 ):609 """Works like `parse_expression` but if multiple expressions are610 delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.611 This method could also return a regular expression instead of a tuple612 if no commas where found.613614 The default parsing mode is a full tuple. If `simplified` is `True`615 only names and literals are parsed. The `no_condexpr` parameter is616 forwarded to :meth:`parse_expression`.617618 Because tuples do not require delimiters and may end in a bogus comma619 an extra hint is needed that marks the end of a tuple. For example620 for loops support tuples between `for` and `in`. In that case the621 `extra_end_rules` is set to ``['name:in']``.622623 `explicit_parentheses` is true if the parsing was triggered by an624 expression in parentheses. This is used to figure out if an empty625 tuple is a valid expression or not.626 """627 lineno = self.stream.current.lineno628 if simplified:629 parse = self.parse_primary630 elif with_condexpr:631 parse = self.parse_expression632 else:633634 def parse():635 return self.parse_expression(with_condexpr=False)636637 args = []638 is_tuple = False639 while 1:640 if args:641 self.stream.expect("comma")642 if self.is_tuple_end(extra_end_rules):643 break644 args.append(parse())645 if self.stream.current.type == "comma":646 is_tuple = True647 else:648 break649 lineno = self.stream.current.lineno650651 if not is_tuple:652 if args:653 return args[0]654655 # if we don't have explicit parentheses, an empty tuple is656 # not a valid expression. This would mean nothing (literally657 # nothing) in the spot of an expression would be an empty658 # tuple.659 if not explicit_parentheses:660 self.fail(661 "Expected an expression, got '%s'"662 % describe_token(self.stream.current)663 )664665 return nodes.Tuple(args, "load", lineno=lineno)666667 def parse_list(self):668 token = self.stream.expect("lbracket")669 items = []670 while self.stream.current.type != "rbracket":671 if items:672 self.stream.expect("comma")673 if self.stream.current.type == "rbracket":674 break675 items.append(self.parse_expression())676 self.stream.expect("rbracket")677 return nodes.List(items, lineno=token.lineno)678679 def parse_dict(self):680 token = self.stream.expect("lbrace")681 items = []682 while self.stream.current.type != "rbrace":683 if items:684 self.stream.expect("comma")685 if self.stream.current.type == "rbrace":686 break687 key = self.parse_expression()688 self.stream.expect("colon")689 value = self.parse_expression()690 items.append(nodes.Pair(key, value, lineno=key.lineno))691 self.stream.expect("rbrace")692 return nodes.Dict(items, lineno=token.lineno)693694 def parse_postfix(self, node):695 while 1:696 token_type = self.stream.current.type697 if token_type == "dot" or token_type == "lbracket":698 node = self.parse_subscript(node)699 # calls are valid both after postfix expressions (getattr700 # and getitem) as well as filters and tests701 elif token_type == "lparen":702 node = self.parse_call(node)703 else:704 break705 return node706707 def parse_filter_expr(self, node):708 while 1:709 token_type = self.stream.current.type710 if token_type == "pipe":711 node = self.parse_filter(node)712 elif token_type == "name" and self.stream.current.value == "is":713 node = self.parse_test(node)714 # calls are valid both after postfix expressions (getattr715 # and getitem) as well as filters and tests716 elif token_type == "lparen":717 node = self.parse_call(node)718 else:719 break720 return node721722 def parse_subscript(self, node):723 token = next(self.stream)724 if token.type == "dot":725 attr_token = self.stream.current726 next(self.stream)727 if attr_token.type == "name":728 return nodes.Getattr(729 node, attr_token.value, "load", lineno=token.lineno730 )731 elif attr_token.type != "integer":732 self.fail("expected name or number", attr_token.lineno)733 arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)734 return nodes.Getitem(node, arg, "load", lineno=token.lineno)735 if token.type == "lbracket":736 args = []737 while self.stream.current.type != "rbracket":738 if args:739 self.stream.expect("comma")740 args.append(self.parse_subscribed())741 self.stream.expect("rbracket")742 if len(args) == 1:743 arg = args[0]744 else:745 arg = nodes.Tuple(args, "load", lineno=token.lineno)746 return nodes.Getitem(node, arg, "load", lineno=token.lineno)747 self.fail("expected subscript expression", token.lineno)748749 def parse_subscribed(self):750 lineno = self.stream.current.lineno751752 if self.stream.current.type == "colon":753 next(self.stream)754 args = [None]755 else:756 node = self.parse_expression()757 if self.stream.current.type != "colon":758 return node759 next(self.stream)760 args = [node]761762 if self.stream.current.type == "colon":763 args.append(None)764 elif self.stream.current.type not in ("rbracket", "comma"):765 args.append(self.parse_expression())766 else:767 args.append(None)768769 if self.stream.current.type == "colon":770 next(self.stream)771 if self.stream.current.type not in ("rbracket", "comma"):772 args.append(self.parse_expression())773 else:774 args.append(None)775 else:776 args.append(None)777778 return nodes.Slice(lineno=lineno, *args)779780 def parse_call(self, node):781 token = self.stream.expect("lparen")782 args = []783 kwargs = []784 dyn_args = dyn_kwargs = None785 require_comma = False786787 def ensure(expr):788 if not expr:789 self.fail("invalid syntax for function call expression", token.lineno)790791 while self.stream.current.type != "rparen":792 if require_comma:793 self.stream.expect("comma")794 # support for trailing comma795 if self.stream.current.type == "rparen":796 break797 if self.stream.current.type == "mul":798 ensure(dyn_args is None and dyn_kwargs is None)799 next(self.stream)800 dyn_args = self.parse_expression()801 elif self.stream.current.type == "pow":802 ensure(dyn_kwargs is None)803 next(self.stream)804 dyn_kwargs = self.parse_expression()805 else:806 if (807 self.stream.current.type == "name"808 and self.stream.look().type == "assign"809 ):810 # Parsing a kwarg811 ensure(dyn_kwargs is None)812 key = self.stream.current.value813 self.stream.skip(2)814 value = self.parse_expression()815 kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))816 else:817 # Parsing an arg818 ensure(dyn_args is None and dyn_kwargs is None and not kwargs)819 args.append(self.parse_expression())820821 require_comma = True822 self.stream.expect("rparen")823824 if node is None:825 return args, kwargs, dyn_args, dyn_kwargs826 return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)827828 def parse_filter(self, node, start_inline=False):829 while self.stream.current.type == "pipe" or start_inline:830 if not start_inline:831 next(self.stream)832 token = self.stream.expect("name")833 name = token.value834 while self.stream.current.type == "dot":835 next(self.stream)836 name += "." + self.stream.expect("name").value837 if self.stream.current.type == "lparen":838 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)839 else:840 args = []841 kwargs = []842 dyn_args = dyn_kwargs = None843 node = nodes.Filter(844 node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno845 )846 start_inline = False847 return node848849 def parse_test(self, node):850 token = next(self.stream)851 if self.stream.current.test("name:not"):852 next(self.stream)853 negated = True854 else:855 negated = False856 name = self.stream.expect("name").value857 while self.stream.current.type == "dot":858 next(self.stream)859 name += "." + self.stream.expect("name").value860 dyn_args = dyn_kwargs = None861 kwargs = []862 if self.stream.current.type == "lparen":863 args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)864 elif self.stream.current.type in (865 "name",866 "string",867 "integer",868 "float",869 "lparen",870 "lbracket",871 "lbrace",872 ) and not self.stream.current.test_any("name:else", "name:or", "name:and"):873 if self.stream.current.test("name:is"):874 self.fail("You cannot chain multiple tests with is")875 arg_node = self.parse_primary()876 arg_node = self.parse_postfix(arg_node)877 args = [arg_node]878 else:879 args = []880 node = nodes.Test(881 node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno882 )883 if negated:884 node = nodes.Not(node, lineno=token.lineno)885 return node886887 def subparse(self, end_tokens=None):888 body = []889 data_buffer = []890 add_data = data_buffer.append891892 if end_tokens is not None:893 self._end_token_stack.append(end_tokens)894895 def flush_data():896 if data_buffer:897 lineno = data_buffer[0].lineno898 body.append(nodes.Output(data_buffer[:], lineno=lineno))899 del data_buffer[:]900901 try:902 while self.stream:903 token = self.stream.current904 if token.type == "data":905 if token.value:906 add_data(nodes.TemplateData(token.value, lineno=token.lineno))907 next(self.stream)908 elif token.type == "variable_begin":909 next(self.stream)910 add_data(self.parse_tuple(with_condexpr=True))911 self.stream.expect("variable_end")912 elif token.type == "block_begin":913 flush_data()914 next(self.stream)915 if end_tokens is not None and self.stream.current.test_any(916 *end_tokens917 ):918 return body919 rv = self.parse_statement()920 if isinstance(rv, list):921 body.extend(rv)922 else:923 body.append(rv)924 self.stream.expect("block_end")925 else:926 raise AssertionError("internal parsing error")927928 flush_data()929 finally:930 if end_tokens is not None:931 self._end_token_stack.pop()932933 return body934935 def parse(self):936 """Parse the whole template into a `Template` node."""937 result = nodes.Template(self.subparse(), lineno=1)938 result.set_environment(self.environment)939 return result
deleted:src/jinja2/runtime.py-1011 removed
1# -*- coding: utf-8 -*-2"""The runtime functions and state used by compiled templates."""3import sys4from itertools import chain5from types import MethodType67from markupsafe import escape8from markupsafe import Markup9from markupsafe import soft_unicode1011from ._compat import abc12from ._compat import imap13from ._compat import implements_iterator14from ._compat import implements_to_string15from ._compat import iteritems16from ._compat import PY217from ._compat import string_types18from ._compat import text_type19from ._compat import with_metaclass20from .exceptions import TemplateNotFound21from .exceptions import TemplateRuntimeError22from .exceptions import UndefinedError23from .nodes import EvalContext24from .utils import concat25from .utils import evalcontextfunction26from .utils import internalcode27from .utils import missing28from .utils import Namespace29from .utils import object_type_repr3031# these variables are exported to the template runtime32__all__ = [33 "LoopContext",34 "TemplateReference",35 "Macro",36 "Markup",37 "TemplateRuntimeError",38 "missing",39 "concat",40 "escape",41 "markup_join",42 "unicode_join",43 "to_string",44 "identity",45 "TemplateNotFound",46 "Namespace",47 "Undefined",48]4950#: the name of the function that is used to convert something into51#: a string. We can just use the text type here.52to_string = text_type535455def identity(x):56 """Returns its argument. Useful for certain things in the57 environment.58 """59 return x606162def markup_join(seq):63 """Concatenation that escapes if necessary and converts to unicode."""64 buf = []65 iterator = imap(soft_unicode, seq)66 for arg in iterator:67 buf.append(arg)68 if hasattr(arg, "__html__"):69 return Markup(u"").join(chain(buf, iterator))70 return concat(buf)717273def unicode_join(seq):74 """Simple args to unicode conversion and concatenation."""75 return concat(imap(text_type, seq))767778def new_context(79 environment,80 template_name,81 blocks,82 vars=None,83 shared=None,84 globals=None,85 locals=None,86):87 """Internal helper for context creation."""88 if vars is None:89 vars = {}90 if shared:91 parent = vars92 else:93 parent = dict(globals or (), **vars)94 if locals:95 # if the parent is shared a copy should be created because96 # we don't want to modify the dict passed97 if shared:98 parent = dict(parent)99 for key, value in iteritems(locals):100 if value is not missing:101 parent[key] = value102 return environment.context_class(environment, parent, template_name, blocks)103104105class TemplateReference(object):106 """The `self` in templates."""107108 def __init__(self, context):109 self.__context = context110111 def __getitem__(self, name):112 blocks = self.__context.blocks[name]113 return BlockReference(name, self.__context, blocks, 0)114115 def __repr__(self):116 return "<%s %r>" % (self.__class__.__name__, self.__context.name)117118119def _get_func(x):120 return getattr(x, "__func__", x)121122123class ContextMeta(type):124 def __new__(mcs, name, bases, d):125 rv = type.__new__(mcs, name, bases, d)126 if bases == ():127 return rv128129 resolve = _get_func(rv.resolve)130 default_resolve = _get_func(Context.resolve)131 resolve_or_missing = _get_func(rv.resolve_or_missing)132 default_resolve_or_missing = _get_func(Context.resolve_or_missing)133134 # If we have a changed resolve but no changed default or missing135 # resolve we invert the call logic.136 if (137 resolve is not default_resolve138 and resolve_or_missing is default_resolve_or_missing139 ):140 rv._legacy_resolve_mode = True141 elif (142 resolve is default_resolve143 and resolve_or_missing is default_resolve_or_missing144 ):145 rv._fast_resolve_mode = True146147 return rv148149150def resolve_or_missing(context, key, missing=missing):151 if key in context.vars:152 return context.vars[key]153 if key in context.parent:154 return context.parent[key]155 return missing156157158class Context(with_metaclass(ContextMeta)):159 """The template context holds the variables of a template. It stores the160 values passed to the template and also the names the template exports.161 Creating instances is neither supported nor useful as it's created162 automatically at various stages of the template evaluation and should not163 be created by hand.164165 The context is immutable. Modifications on :attr:`parent` **must not**166 happen and modifications on :attr:`vars` are allowed from generated167 template code only. Template filters and global functions marked as168 :func:`contextfunction`\\s get the active context passed as first argument169 and are allowed to access the context read-only.170171 The template context supports read only dict operations (`get`,172 `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,173 `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`174 method that doesn't fail with a `KeyError` but returns an175 :class:`Undefined` object for missing variables.176 """177178 # XXX: we want to eventually make this be a deprecation warning and179 # remove it.180 _legacy_resolve_mode = False181 _fast_resolve_mode = False182183 def __init__(self, environment, parent, name, blocks):184 self.parent = parent185 self.vars = {}186 self.environment = environment187 self.eval_ctx = EvalContext(self.environment, name)188 self.exported_vars = set()189 self.name = name190191 # create the initial mapping of blocks. Whenever template inheritance192 # takes place the runtime will update this mapping with the new blocks193 # from the template.194 self.blocks = dict((k, [v]) for k, v in iteritems(blocks))195196 # In case we detect the fast resolve mode we can set up an alias197 # here that bypasses the legacy code logic.198 if self._fast_resolve_mode:199 self.resolve_or_missing = MethodType(resolve_or_missing, self)200201 def super(self, name, current):202 """Render a parent block."""203 try:204 blocks = self.blocks[name]205 index = blocks.index(current) + 1206 blocks[index]207 except LookupError:208 return self.environment.undefined(209 "there is no parent block called %r." % name, name="super"210 )211 return BlockReference(name, self, blocks, index)212213 def get(self, key, default=None):214 """Returns an item from the template context, if it doesn't exist215 `default` is returned.216 """217 try:218 return self[key]219 except KeyError:220 return default221222 def resolve(self, key):223 """Looks up a variable like `__getitem__` or `get` but returns an224 :class:`Undefined` object with the name of the name looked up.225 """226 if self._legacy_resolve_mode:227 rv = resolve_or_missing(self, key)228 else:229 rv = self.resolve_or_missing(key)230 if rv is missing:231 return self.environment.undefined(name=key)232 return rv233234 def resolve_or_missing(self, key):235 """Resolves a variable like :meth:`resolve` but returns the236 special `missing` value if it cannot be found.237 """238 if self._legacy_resolve_mode:239 rv = self.resolve(key)240 if isinstance(rv, Undefined):241 rv = missing242 return rv243 return resolve_or_missing(self, key)244245 def get_exported(self):246 """Get a new dict with the exported variables."""247 return dict((k, self.vars[k]) for k in self.exported_vars)248249 def get_all(self):250 """Return the complete context as dict including the exported251 variables. For optimizations reasons this might not return an252 actual copy so be careful with using it.253 """254 if not self.vars:255 return self.parent256 if not self.parent:257 return self.vars258 return dict(self.parent, **self.vars)259260 @internalcode261 def call(__self, __obj, *args, **kwargs): # noqa: B902262 """Call the callable with the arguments and keyword arguments263 provided but inject the active context or environment as first264 argument if the callable is a :func:`contextfunction` or265 :func:`environmentfunction`.266 """267 if __debug__:268 __traceback_hide__ = True # noqa269270 # Allow callable classes to take a context271 if hasattr(__obj, "__call__"): # noqa: B004272 fn = __obj.__call__273 for fn_type in (274 "contextfunction",275 "evalcontextfunction",276 "environmentfunction",277 ):278 if hasattr(fn, fn_type):279 __obj = fn280 break281282 if callable(__obj):283 if getattr(__obj, "contextfunction", 0):284 args = (__self,) + args285 elif getattr(__obj, "evalcontextfunction", 0):286 args = (__self.eval_ctx,) + args287 elif getattr(__obj, "environmentfunction", 0):288 args = (__self.environment,) + args289 try:290 return __obj(*args, **kwargs)291 except StopIteration:292 return __self.environment.undefined(293 "value was undefined because "294 "a callable raised a "295 "StopIteration exception"296 )297298 def derived(self, locals=None):299 """Internal helper function to create a derived context. This is300 used in situations where the system needs a new context in the same301 template that is independent.302 """303 context = new_context(304 self.environment, self.name, {}, self.get_all(), True, None, locals305 )306 context.eval_ctx = self.eval_ctx307 context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))308 return context309310 def _all(meth): # noqa: B902311 def proxy(self):312 return getattr(self.get_all(), meth)()313314 proxy.__doc__ = getattr(dict, meth).__doc__315 proxy.__name__ = meth316 return proxy317318 keys = _all("keys")319 values = _all("values")320 items = _all("items")321322 # not available on python 3323 if PY2:324 iterkeys = _all("iterkeys")325 itervalues = _all("itervalues")326 iteritems = _all("iteritems")327 del _all328329 def __contains__(self, name):330 return name in self.vars or name in self.parent331332 def __getitem__(self, key):333 """Lookup a variable or raise `KeyError` if the variable is334 undefined.335 """336 item = self.resolve_or_missing(key)337 if item is missing:338 raise KeyError(key)339 return item340341 def __repr__(self):342 return "<%s %s of %r>" % (343 self.__class__.__name__,344 repr(self.get_all()),345 self.name,346 )347348349abc.Mapping.register(Context)350351352class BlockReference(object):353 """One block on a template reference."""354355 def __init__(self, name, context, stack, depth):356 self.name = name357 self._context = context358 self._stack = stack359 self._depth = depth360361 @property362 def super(self):363 """Super the block."""364 if self._depth + 1 >= len(self._stack):365 return self._context.environment.undefined(366 "there is no parent block called %r." % self.name, name="super"367 )368 return BlockReference(self.name, self._context, self._stack, self._depth + 1)369370 @internalcode371 def __call__(self):372 rv = concat(self._stack[self._depth](self._context))373 if self._context.eval_ctx.autoescape:374 rv = Markup(rv)375 return rv376377378@implements_iterator379class LoopContext:380 """A wrapper iterable for dynamic ``for`` loops, with information381 about the loop and iteration.382 """383384 #: Current iteration of the loop, starting at 0.385 index0 = -1386387 _length = None388 _after = missing389 _current = missing390 _before = missing391 _last_changed_value = missing392393 def __init__(self, iterable, undefined, recurse=None, depth0=0):394 """395 :param iterable: Iterable to wrap.396 :param undefined: :class:`Undefined` class to use for next and397 previous items.398 :param recurse: The function to render the loop body when the399 loop is marked recursive.400 :param depth0: Incremented when looping recursively.401 """402 self._iterable = iterable403 self._iterator = self._to_iterator(iterable)404 self._undefined = undefined405 self._recurse = recurse406 #: How many levels deep a recursive loop currently is, starting at 0.407 self.depth0 = depth0408409 @staticmethod410 def _to_iterator(iterable):411 return iter(iterable)412413 @property414 def length(self):415 """Length of the iterable.416417 If the iterable is a generator or otherwise does not have a418 size, it is eagerly evaluated to get a size.419 """420 if self._length is not None:421 return self._length422423 try:424 self._length = len(self._iterable)425 except TypeError:426 iterable = list(self._iterator)427 self._iterator = self._to_iterator(iterable)428 self._length = len(iterable) + self.index + (self._after is not missing)429430 return self._length431432 def __len__(self):433 return self.length434435 @property436 def depth(self):437 """How many levels deep a recursive loop currently is, starting at 1."""438 return self.depth0 + 1439440 @property441 def index(self):442 """Current iteration of the loop, starting at 1."""443 return self.index0 + 1444445 @property446 def revindex0(self):447 """Number of iterations from the end of the loop, ending at 0.448449 Requires calculating :attr:`length`.450 """451 return self.length - self.index452453 @property454 def revindex(self):455 """Number of iterations from the end of the loop, ending at 1.456457 Requires calculating :attr:`length`.458 """459 return self.length - self.index0460461 @property462 def first(self):463 """Whether this is the first iteration of the loop."""464 return self.index0 == 0465466 def _peek_next(self):467 """Return the next element in the iterable, or :data:`missing`468 if the iterable is exhausted. Only peeks one item ahead, caching469 the result in :attr:`_last` for use in subsequent checks. The470 cache is reset when :meth:`__next__` is called.471 """472 if self._after is not missing:473 return self._after474475 self._after = next(self._iterator, missing)476 return self._after477478 @property479 def last(self):480 """Whether this is the last iteration of the loop.481482 Causes the iterable to advance early. See483 :func:`itertools.groupby` for issues this can cause.484 The :func:`groupby` filter avoids that issue.485 """486 return self._peek_next() is missing487488 @property489 def previtem(self):490 """The item in the previous iteration. Undefined during the491 first iteration.492 """493 if self.first:494 return self._undefined("there is no previous item")495496 return self._before497498 @property499 def nextitem(self):500 """The item in the next iteration. Undefined during the last501 iteration.502503 Causes the iterable to advance early. See504 :func:`itertools.groupby` for issues this can cause.505 The :func:`groupby` filter avoids that issue.506 """507 rv = self._peek_next()508509 if rv is missing:510 return self._undefined("there is no next item")511512 return rv513514 def cycle(self, *args):515 """Return a value from the given args, cycling through based on516 the current :attr:`index0`.517518 :param args: One or more values to cycle through.519 """520 if not args:521 raise TypeError("no items for cycling given")522523 return args[self.index0 % len(args)]524525 def changed(self, *value):526 """Return ``True`` if previously called with a different value527 (including when called for the first time).528529 :param value: One or more values to compare to the last call.530 """531 if self._last_changed_value != value:532 self._last_changed_value = value533 return True534535 return False536537 def __iter__(self):538 return self539540 def __next__(self):541 if self._after is not missing:542 rv = self._after543 self._after = missing544 else:545 rv = next(self._iterator)546547 self.index0 += 1548 self._before = self._current549 self._current = rv550 return rv, self551552 @internalcode553 def __call__(self, iterable):554 """When iterating over nested data, render the body of the loop555 recursively with the given inner iterable data.556557 The loop must have the ``recursive`` marker for this to work.558 """559 if self._recurse is None:560 raise TypeError(561 "The loop must have the 'recursive' marker to be called recursively."562 )563564 return self._recurse(iterable, self._recurse, depth=self.depth)565566 def __repr__(self):567 return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)568569570class Macro(object):571 """Wraps a macro function."""572573 def __init__(574 self,575 environment,576 func,577 name,578 arguments,579 catch_kwargs,580 catch_varargs,581 caller,582 default_autoescape=None,583 ):584 self._environment = environment585 self._func = func586 self._argument_count = len(arguments)587 self.name = name588 self.arguments = arguments589 self.catch_kwargs = catch_kwargs590 self.catch_varargs = catch_varargs591 self.caller = caller592 self.explicit_caller = "caller" in arguments593 if default_autoescape is None:594 default_autoescape = environment.autoescape595 self._default_autoescape = default_autoescape596597 @internalcode598 @evalcontextfunction599 def __call__(self, *args, **kwargs):600 # This requires a bit of explanation, In the past we used to601 # decide largely based on compile-time information if a macro is602 # safe or unsafe. While there was a volatile mode it was largely603 # unused for deciding on escaping. This turns out to be604 # problematic for macros because whether a macro is safe depends not605 # on the escape mode when it was defined, but rather when it was used.606 #607 # Because however we export macros from the module system and608 # there are historic callers that do not pass an eval context (and609 # will continue to not pass one), we need to perform an instance610 # check here.611 #612 # This is considered safe because an eval context is not a valid613 # argument to callables otherwise anyway. Worst case here is614 # that if no eval context is passed we fall back to the compile615 # time autoescape flag.616 if args and isinstance(args[0], EvalContext):617 autoescape = args[0].autoescape618 args = args[1:]619 else:620 autoescape = self._default_autoescape621622 # try to consume the positional arguments623 arguments = list(args[: self._argument_count])624 off = len(arguments)625626 # For information why this is necessary refer to the handling627 # of caller in the `macro_body` handler in the compiler.628 found_caller = False629630 # if the number of arguments consumed is not the number of631 # arguments expected we start filling in keyword arguments632 # and defaults.633 if off != self._argument_count:634 for name in self.arguments[len(arguments) :]:635 try:636 value = kwargs.pop(name)637 except KeyError:638 value = missing639 if name == "caller":640 found_caller = True641 arguments.append(value)642 else:643 found_caller = self.explicit_caller644645 # it's important that the order of these arguments does not change646 # if not also changed in the compiler's `function_scoping` method.647 # the order is caller, keyword arguments, positional arguments!648 if self.caller and not found_caller:649 caller = kwargs.pop("caller", None)650 if caller is None:651 caller = self._environment.undefined("No caller defined", name="caller")652 arguments.append(caller)653654 if self.catch_kwargs:655 arguments.append(kwargs)656 elif kwargs:657 if "caller" in kwargs:658 raise TypeError(659 "macro %r was invoked with two values for "660 "the special caller argument. This is "661 "most likely a bug." % self.name662 )663 raise TypeError(664 "macro %r takes no keyword argument %r"665 % (self.name, next(iter(kwargs)))666 )667 if self.catch_varargs:668 arguments.append(args[self._argument_count :])669 elif len(args) > self._argument_count:670 raise TypeError(671 "macro %r takes not more than %d argument(s)"672 % (self.name, len(self.arguments))673 )674675 return self._invoke(arguments, autoescape)676677 def _invoke(self, arguments, autoescape):678 """This method is being swapped out by the async implementation."""679 rv = self._func(*arguments)680 if autoescape:681 rv = Markup(rv)682 return rv683684 def __repr__(self):685 return "<%s %s>" % (686 self.__class__.__name__,687 self.name is None and "anonymous" or repr(self.name),688 )689690691@implements_to_string692class Undefined(object):693 """The default undefined type. This undefined type can be printed and694 iterated over, but every other access will raise an :exc:`UndefinedError`:695696 >>> foo = Undefined(name='foo')697 >>> str(foo)698 ''699 >>> not foo700 True701 >>> foo + 42702 Traceback (most recent call last):703 ...704 jinja2.exceptions.UndefinedError: 'foo' is undefined705 """706707 __slots__ = (708 "_undefined_hint",709 "_undefined_obj",710 "_undefined_name",711 "_undefined_exception",712 )713714 def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):715 self._undefined_hint = hint716 self._undefined_obj = obj717 self._undefined_name = name718 self._undefined_exception = exc719720 @property721 def _undefined_message(self):722 """Build a message about the undefined value based on how it was723 accessed.724 """725 if self._undefined_hint:726 return self._undefined_hint727728 if self._undefined_obj is missing:729 return "%r is undefined" % self._undefined_name730731 if not isinstance(self._undefined_name, string_types):732 return "%s has no element %r" % (733 object_type_repr(self._undefined_obj),734 self._undefined_name,735 )736737 return "%r has no attribute %r" % (738 object_type_repr(self._undefined_obj),739 self._undefined_name,740 )741742 @internalcode743 def _fail_with_undefined_error(self, *args, **kwargs):744 """Raise an :exc:`UndefinedError` when operations are performed745 on the undefined value.746 """747 raise self._undefined_exception(self._undefined_message)748749 @internalcode750 def __getattr__(self, name):751 if name[:2] == "__":752 raise AttributeError(name)753 return self._fail_with_undefined_error()754755 __add__ = (756 __radd__757 ) = (758 __mul__759 ) = (760 __rmul__761 ) = (762 __div__763 ) = (764 __rdiv__765 ) = (766 __truediv__767 ) = (768 __rtruediv__769 ) = (770 __floordiv__771 ) = (772 __rfloordiv__773 ) = (774 __mod__775 ) = (776 __rmod__777 ) = (778 __pos__779 ) = (780 __neg__781 ) = (782 __call__783 ) = (784 __getitem__785 ) = (786 __lt__787 ) = (788 __le__789 ) = (790 __gt__791 ) = (792 __ge__793 ) = (794 __int__795 ) = (796 __float__797 ) = (798 __complex__799 ) = __pow__ = __rpow__ = __sub__ = __rsub__ = _fail_with_undefined_error800801 def __eq__(self, other):802 return type(self) is type(other)803804 def __ne__(self, other):805 return not self.__eq__(other)806807 def __hash__(self):808 return id(type(self))809810 def __str__(self):811 return u""812813 def __len__(self):814 return 0815816 def __iter__(self):817 if 0:818 yield None819820 def __nonzero__(self):821 return False822823 __bool__ = __nonzero__824825 def __repr__(self):826 return "Undefined"827828829def make_logging_undefined(logger=None, base=None):830 """Given a logger object this returns a new undefined class that will831 log certain failures. It will log iterations and printing. If no832 logger is given a default logger is created.833834 Example::835836 logger = logging.getLogger(__name__)837 LoggingUndefined = make_logging_undefined(838 logger=logger,839 base=Undefined840 )841842 .. versionadded:: 2.8843844 :param logger: the logger to use. If not provided, a default logger845 is created.846 :param base: the base class to add logging functionality to. This847 defaults to :class:`Undefined`.848 """849 if logger is None:850 import logging851852 logger = logging.getLogger(__name__)853 logger.addHandler(logging.StreamHandler(sys.stderr))854 if base is None:855 base = Undefined856857 def _log_message(undef):858 if undef._undefined_hint is None:859 if undef._undefined_obj is missing:860 hint = "%s is undefined" % undef._undefined_name861 elif not isinstance(undef._undefined_name, string_types):862 hint = "%s has no element %s" % (863 object_type_repr(undef._undefined_obj),864 undef._undefined_name,865 )866 else:867 hint = "%s has no attribute %s" % (868 object_type_repr(undef._undefined_obj),869 undef._undefined_name,870 )871 else:872 hint = undef._undefined_hint873 logger.warning("Template variable warning: %s", hint)874875 class LoggingUndefined(base):876 def _fail_with_undefined_error(self, *args, **kwargs):877 try:878 return base._fail_with_undefined_error(self, *args, **kwargs)879 except self._undefined_exception as e:880 logger.error("Template variable error: %s", str(e))881 raise e882883 def __str__(self):884 rv = base.__str__(self)885 _log_message(self)886 return rv887888 def __iter__(self):889 rv = base.__iter__(self)890 _log_message(self)891 return rv892893 if PY2:894895 def __nonzero__(self):896 rv = base.__nonzero__(self)897 _log_message(self)898 return rv899900 def __unicode__(self):901 rv = base.__unicode__(self)902 _log_message(self)903 return rv904905 else:906907 def __bool__(self):908 rv = base.__bool__(self)909 _log_message(self)910 return rv911912 return LoggingUndefined913914915# No @implements_to_string decorator here because __str__916# is not overwritten from Undefined in this class.917# This would cause a recursion error in Python 2.918class ChainableUndefined(Undefined):919 """An undefined that is chainable, where both ``__getattr__`` and920 ``__getitem__`` return itself rather than raising an921 :exc:`UndefinedError`.922923 >>> foo = ChainableUndefined(name='foo')924 >>> str(foo.bar['baz'])925 ''926 >>> foo.bar['baz'] + 42927 Traceback (most recent call last):928 ...929 jinja2.exceptions.UndefinedError: 'foo' is undefined930931 .. versionadded:: 2.11.0932 """933934 __slots__ = ()935936 def __html__(self):937 return self.__str__()938939 def __getattr__(self, _):940 return self941942 __getitem__ = __getattr__943944945@implements_to_string946class DebugUndefined(Undefined):947 """An undefined that returns the debug info when printed.948949 >>> foo = DebugUndefined(name='foo')950 >>> str(foo)951 '{{ foo }}'952 >>> not foo953 True954 >>> foo + 42955 Traceback (most recent call last):956 ...957 jinja2.exceptions.UndefinedError: 'foo' is undefined958 """959960 __slots__ = ()961962 def __str__(self):963 if self._undefined_hint is None:964 if self._undefined_obj is missing:965 return u"{{ %s }}" % self._undefined_name966 return "{{ no such element: %s[%r] }}" % (967 object_type_repr(self._undefined_obj),968 self._undefined_name,969 )970 return u"{{ undefined value printed: %s }}" % self._undefined_hint971972973@implements_to_string974class StrictUndefined(Undefined):975 """An undefined that barks on print and iteration as well as boolean976 tests and all kinds of comparisons. In other words: you can do nothing977 with it except checking if it's defined using the `defined` test.978979 >>> foo = StrictUndefined(name='foo')980 >>> str(foo)981 Traceback (most recent call last):982 ...983 jinja2.exceptions.UndefinedError: 'foo' is undefined984 >>> not foo985 Traceback (most recent call last):986 ...987 jinja2.exceptions.UndefinedError: 'foo' is undefined988 >>> foo + 42989 Traceback (most recent call last):990 ...991 jinja2.exceptions.UndefinedError: 'foo' is undefined992 """993994 __slots__ = ()995 __iter__ = (996 __str__997 ) = (998 __len__999 ) = (1000 __nonzero__1001 ) = __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error100210031004# remove remaining slots attributes, after the metaclass did the magic they1005# are unneeded and irritating as they contain wrong data for the subclasses.1006del (1007 Undefined.__slots__,1008 ChainableUndefined.__slots__,1009 DebugUndefined.__slots__,1010 StrictUndefined.__slots__,1011)
deleted:src/jinja2/sandbox.py-510 removed
1# -*- coding: utf-8 -*-2"""A sandbox layer that ensures unsafe operations cannot be performed.3Useful when the template itself comes from an untrusted source.4"""5import operator6import types7import warnings8from collections import deque9from string import Formatter1011from markupsafe import EscapeFormatter1213from ._compat import abc14from ._compat import PY215from ._compat import range_type16from ._compat import string_types17from .environment import Environment18from .exceptions import SecurityError19from .utils import Markup2021#: maximum number of items a range may produce22MAX_RANGE = 1000002324#: attributes of function objects that are considered unsafe.25if PY2:26 UNSAFE_FUNCTION_ATTRIBUTES = {27 "func_closure",28 "func_code",29 "func_dict",30 "func_defaults",31 "func_globals",32 }33else:34 # On versions > python 2 the special attributes on functions are gone,35 # but they remain on methods and generators for whatever reason.36 UNSAFE_FUNCTION_ATTRIBUTES = set()3738#: unsafe method attributes. function attributes are unsafe for methods too39UNSAFE_METHOD_ATTRIBUTES = {"im_class", "im_func", "im_self"}4041#: unsafe generator attributes.42UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}4344#: unsafe attributes on coroutines45UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}4647#: unsafe attributes on async generators48UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}4950# make sure we don't warn in python 2.6 about stuff we don't care about51warnings.filterwarnings(52 "ignore", "the sets module", DeprecationWarning, module=__name__53)5455_mutable_set_types = (set,)56_mutable_mapping_types = (dict,)57_mutable_sequence_types = (list,)5859# on python 2.x we can register the user collection types60try:61 from UserDict import UserDict, DictMixin62 from UserList import UserList6364 _mutable_mapping_types += (UserDict, DictMixin)65 _mutable_set_types += (UserList,)66except ImportError:67 pass6869# if sets is still available, register the mutable set from there as well70try:71 from sets import Set7273 _mutable_set_types += (Set,)74except ImportError:75 pass7677#: register Python 2.6 abstract base classes78_mutable_set_types += (abc.MutableSet,)79_mutable_mapping_types += (abc.MutableMapping,)80_mutable_sequence_types += (abc.MutableSequence,)8182_mutable_spec = (83 (84 _mutable_set_types,85 frozenset(86 [87 "add",88 "clear",89 "difference_update",90 "discard",91 "pop",92 "remove",93 "symmetric_difference_update",94 "update",95 ]96 ),97 ),98 (99 _mutable_mapping_types,100 frozenset(["clear", "pop", "popitem", "setdefault", "update"]),101 ),102 (103 _mutable_sequence_types,104 frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),105 ),106 (107 deque,108 frozenset(109 [110 "append",111 "appendleft",112 "clear",113 "extend",114 "extendleft",115 "pop",116 "popleft",117 "remove",118 "rotate",119 ]120 ),121 ),122)123124125class _MagicFormatMapping(abc.Mapping):126 """This class implements a dummy wrapper to fix a bug in the Python127 standard library for string formatting.128129 See https://bugs.python.org/issue13598 for information about why130 this is necessary.131 """132133 def __init__(self, args, kwargs):134 self._args = args135 self._kwargs = kwargs136 self._last_index = 0137138 def __getitem__(self, key):139 if key == "":140 idx = self._last_index141 self._last_index += 1142 try:143 return self._args[idx]144 except LookupError:145 pass146 key = str(idx)147 return self._kwargs[key]148149 def __iter__(self):150 return iter(self._kwargs)151152 def __len__(self):153 return len(self._kwargs)154155156def inspect_format_method(callable):157 if not isinstance(158 callable, (types.MethodType, types.BuiltinMethodType)159 ) or callable.__name__ not in ("format", "format_map"):160 return None161 obj = callable.__self__162 if isinstance(obj, string_types):163 return obj164165166def safe_range(*args):167 """A range that can't generate ranges with a length of more than168 MAX_RANGE items.169 """170 rng = range_type(*args)171172 if len(rng) > MAX_RANGE:173 raise OverflowError(174 "Range too big. The sandbox blocks ranges larger than"175 " MAX_RANGE (%d)." % MAX_RANGE176 )177178 return rng179180181def unsafe(f):182 """Marks a function or method as unsafe.183184 ::185186 @unsafe187 def delete(self):188 pass189 """190 f.unsafe_callable = True191 return f192193194def is_internal_attribute(obj, attr):195 """Test if the attribute given is an internal python attribute. For196 example this function returns `True` for the `func_code` attribute of197 python objects. This is useful if the environment method198 :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.199200 >>> from jinja2.sandbox import is_internal_attribute201 >>> is_internal_attribute(str, "mro")202 True203 >>> is_internal_attribute(str, "upper")204 False205 """206 if isinstance(obj, types.FunctionType):207 if attr in UNSAFE_FUNCTION_ATTRIBUTES:208 return True209 elif isinstance(obj, types.MethodType):210 if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:211 return True212 elif isinstance(obj, type):213 if attr == "mro":214 return True215 elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):216 return True217 elif isinstance(obj, types.GeneratorType):218 if attr in UNSAFE_GENERATOR_ATTRIBUTES:219 return True220 elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):221 if attr in UNSAFE_COROUTINE_ATTRIBUTES:222 return True223 elif hasattr(types, "AsyncGeneratorType") and isinstance(224 obj, types.AsyncGeneratorType225 ):226 if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:227 return True228 return attr.startswith("__")229230231def modifies_known_mutable(obj, attr):232 """This function checks if an attribute on a builtin mutable object233 (list, dict, set or deque) would modify it if called. It also supports234 the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and235 with Python 2.6 onwards the abstract base classes `MutableSet`,236 `MutableMapping`, and `MutableSequence`.237238 >>> modifies_known_mutable({}, "clear")239 True240 >>> modifies_known_mutable({}, "keys")241 False242 >>> modifies_known_mutable([], "append")243 True244 >>> modifies_known_mutable([], "index")245 False246247 If called with an unsupported object (such as unicode) `False` is248 returned.249250 >>> modifies_known_mutable("foo", "upper")251 False252 """253 for typespec, unsafe in _mutable_spec:254 if isinstance(obj, typespec):255 return attr in unsafe256 return False257258259class SandboxedEnvironment(Environment):260 """The sandboxed environment. It works like the regular environment but261 tells the compiler to generate sandboxed code. Additionally subclasses of262 this environment may override the methods that tell the runtime what263 attributes or functions are safe to access.264265 If the template tries to access insecure code a :exc:`SecurityError` is266 raised. However also other exceptions may occur during the rendering so267 the caller has to ensure that all exceptions are caught.268 """269270 sandboxed = True271272 #: default callback table for the binary operators. A copy of this is273 #: available on each instance of a sandboxed environment as274 #: :attr:`binop_table`275 default_binop_table = {276 "+": operator.add,277 "-": operator.sub,278 "*": operator.mul,279 "/": operator.truediv,280 "//": operator.floordiv,281 "**": operator.pow,282 "%": operator.mod,283 }284285 #: default callback table for the unary operators. A copy of this is286 #: available on each instance of a sandboxed environment as287 #: :attr:`unop_table`288 default_unop_table = {"+": operator.pos, "-": operator.neg}289290 #: a set of binary operators that should be intercepted. Each operator291 #: that is added to this set (empty by default) is delegated to the292 #: :meth:`call_binop` method that will perform the operator. The default293 #: operator callback is specified by :attr:`binop_table`.294 #:295 #: The following binary operators are interceptable:296 #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``297 #:298 #: The default operation form the operator table corresponds to the299 #: builtin function. Intercepted calls are always slower than the native300 #: operator call, so make sure only to intercept the ones you are301 #: interested in.302 #:303 #: .. versionadded:: 2.6304 intercepted_binops = frozenset()305306 #: a set of unary operators that should be intercepted. Each operator307 #: that is added to this set (empty by default) is delegated to the308 #: :meth:`call_unop` method that will perform the operator. The default309 #: operator callback is specified by :attr:`unop_table`.310 #:311 #: The following unary operators are interceptable: ``+``, ``-``312 #:313 #: The default operation form the operator table corresponds to the314 #: builtin function. Intercepted calls are always slower than the native315 #: operator call, so make sure only to intercept the ones you are316 #: interested in.317 #:318 #: .. versionadded:: 2.6319 intercepted_unops = frozenset()320321 def intercept_unop(self, operator):322 """Called during template compilation with the name of a unary323 operator to check if it should be intercepted at runtime. If this324 method returns `True`, :meth:`call_unop` is executed for this unary325 operator. The default implementation of :meth:`call_unop` will use326 the :attr:`unop_table` dictionary to perform the operator with the327 same logic as the builtin one.328329 The following unary operators are interceptable: ``+`` and ``-``330331 Intercepted calls are always slower than the native operator call,332 so make sure only to intercept the ones you are interested in.333334 .. versionadded:: 2.6335 """336 return False337338 def __init__(self, *args, **kwargs):339 Environment.__init__(self, *args, **kwargs)340 self.globals["range"] = safe_range341 self.binop_table = self.default_binop_table.copy()342 self.unop_table = self.default_unop_table.copy()343344 def is_safe_attribute(self, obj, attr, value):345 """The sandboxed environment will call this method to check if the346 attribute of an object is safe to access. Per default all attributes347 starting with an underscore are considered private as well as the348 special attributes of internal python objects as returned by the349 :func:`is_internal_attribute` function.350 """351 return not (attr.startswith("_") or is_internal_attribute(obj, attr))352353 def is_safe_callable(self, obj):354 """Check if an object is safely callable. Per default a function is355 considered safe unless the `unsafe_callable` attribute exists and is356 True. Override this method to alter the behavior, but this won't357 affect the `unsafe` decorator from this module.358 """359 return not (360 getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)361 )362363 def call_binop(self, context, operator, left, right):364 """For intercepted binary operator calls (:meth:`intercepted_binops`)365 this function is executed instead of the builtin operator. This can366 be used to fine tune the behavior of certain operators.367368 .. versionadded:: 2.6369 """370 return self.binop_table[operator](left, right)371372 def call_unop(self, context, operator, arg):373 """For intercepted unary operator calls (:meth:`intercepted_unops`)374 this function is executed instead of the builtin operator. This can375 be used to fine tune the behavior of certain operators.376377 .. versionadded:: 2.6378 """379 return self.unop_table[operator](arg)380381 def getitem(self, obj, argument):382 """Subscribe an object from sandboxed code."""383 try:384 return obj[argument]385 except (TypeError, LookupError):386 if isinstance(argument, string_types):387 try:388 attr = str(argument)389 except Exception:390 pass391 else:392 try:393 value = getattr(obj, attr)394 except AttributeError:395 pass396 else:397 if self.is_safe_attribute(obj, argument, value):398 return value399 return self.unsafe_undefined(obj, argument)400 return self.undefined(obj=obj, name=argument)401402 def getattr(self, obj, attribute):403 """Subscribe an object from sandboxed code and prefer the404 attribute. The attribute passed *must* be a bytestring.405 """406 try:407 value = getattr(obj, attribute)408 except AttributeError:409 try:410 return obj[attribute]411 except (TypeError, LookupError):412 pass413 else:414 if self.is_safe_attribute(obj, attribute, value):415 return value416 return self.unsafe_undefined(obj, attribute)417 return self.undefined(obj=obj, name=attribute)418419 def unsafe_undefined(self, obj, attribute):420 """Return an undefined object for unsafe attributes."""421 return self.undefined(422 "access to attribute %r of %r "423 "object is unsafe." % (attribute, obj.__class__.__name__),424 name=attribute,425 obj=obj,426 exc=SecurityError,427 )428429 def format_string(self, s, args, kwargs, format_func=None):430 """If a format call is detected, then this is routed through this431 method so that our safety sandbox can be used for it.432 """433 if isinstance(s, Markup):434 formatter = SandboxedEscapeFormatter(self, s.escape)435 else:436 formatter = SandboxedFormatter(self)437438 if format_func is not None and format_func.__name__ == "format_map":439 if len(args) != 1 or kwargs:440 raise TypeError(441 "format_map() takes exactly one argument %d given"442 % (len(args) + (kwargs is not None))443 )444445 kwargs = args[0]446 args = None447448 kwargs = _MagicFormatMapping(args, kwargs)449 rv = formatter.vformat(s, args, kwargs)450 return type(s)(rv)451452 def call(__self, __context, __obj, *args, **kwargs): # noqa: B902453 """Call an object from sandboxed code."""454 fmt = inspect_format_method(__obj)455 if fmt is not None:456 return __self.format_string(fmt, args, kwargs, __obj)457458 # the double prefixes are to avoid double keyword argument459 # errors when proxying the call.460 if not __self.is_safe_callable(__obj):461 raise SecurityError("%r is not safely callable" % (__obj,))462 return __context.call(__obj, *args, **kwargs)463464465class ImmutableSandboxedEnvironment(SandboxedEnvironment):466 """Works exactly like the regular `SandboxedEnvironment` but does not467 permit modifications on the builtin mutable objects `list`, `set`, and468 `dict` by using the :func:`modifies_known_mutable` function.469 """470471 def is_safe_attribute(self, obj, attr, value):472 if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):473 return False474 return not modifies_known_mutable(obj, attr)475476477# This really is not a public API apparently.478try:479 from _string import formatter_field_name_split480except ImportError:481482 def formatter_field_name_split(field_name):483 return field_name._formatter_field_name_split()484485486class SandboxedFormatterMixin(object):487 def __init__(self, env):488 self._env = env489490 def get_field(self, field_name, args, kwargs):491 first, rest = formatter_field_name_split(field_name)492 obj = self.get_value(first, args, kwargs)493 for is_attr, i in rest:494 if is_attr:495 obj = self._env.getattr(obj, i)496 else:497 obj = self._env.getitem(obj, i)498 return obj, first499500501class SandboxedFormatter(SandboxedFormatterMixin, Formatter):502 def __init__(self, env):503 SandboxedFormatterMixin.__init__(self, env)504 Formatter.__init__(self)505506507class SandboxedEscapeFormatter(SandboxedFormatterMixin, EscapeFormatter):508 def __init__(self, env, escape):509 SandboxedFormatterMixin.__init__(self, env)510 EscapeFormatter.__init__(self, escape)
deleted:src/jinja2/tests.py-215 removed
1# -*- coding: utf-8 -*-2"""Built-in template tests used with the ``is`` operator."""3import decimal4import operator5import re67from ._compat import abc8from ._compat import integer_types9from ._compat import string_types10from ._compat import text_type11from .runtime import Undefined1213number_re = re.compile(r"^-?\d+(\.\d+)?$")14regex_type = type(number_re)15test_callable = callable161718def test_odd(value):19 """Return true if the variable is odd."""20 return value % 2 == 1212223def test_even(value):24 """Return true if the variable is even."""25 return value % 2 == 0262728def test_divisibleby(value, num):29 """Check if a variable is divisible by a number."""30 return value % num == 0313233def test_defined(value):34 """Return true if the variable is defined:3536 .. sourcecode:: jinja3738 {% if variable is defined %}39 value of variable: {{ variable }}40 {% else %}41 variable is not defined42 {% endif %}4344 See the :func:`default` filter for a simple way to set undefined45 variables.46 """47 return not isinstance(value, Undefined)484950def test_undefined(value):51 """Like :func:`defined` but the other way round."""52 return isinstance(value, Undefined)535455def test_none(value):56 """Return true if the variable is none."""57 return value is None585960def test_boolean(value):61 """Return true if the object is a boolean value.6263 .. versionadded:: 2.1164 """65 return value is True or value is False666768def test_false(value):69 """Return true if the object is False.7071 .. versionadded:: 2.1172 """73 return value is False747576def test_true(value):77 """Return true if the object is True.7879 .. versionadded:: 2.1180 """81 return value is True828384# NOTE: The existing 'number' test matches booleans and floats85def test_integer(value):86 """Return true if the object is an integer.8788 .. versionadded:: 2.1189 """90 return isinstance(value, integer_types) and value is not True and value is not False919293# NOTE: The existing 'number' test matches booleans and integers94def test_float(value):95 """Return true if the object is a float.9697 .. versionadded:: 2.1198 """99 return isinstance(value, float)100101102def test_lower(value):103 """Return true if the variable is lowercased."""104 return text_type(value).islower()105106107def test_upper(value):108 """Return true if the variable is uppercased."""109 return text_type(value).isupper()110111112def test_string(value):113 """Return true if the object is a string."""114 return isinstance(value, string_types)115116117def test_mapping(value):118 """Return true if the object is a mapping (dict etc.).119120 .. versionadded:: 2.6121 """122 return isinstance(value, abc.Mapping)123124125def test_number(value):126 """Return true if the variable is a number."""127 return isinstance(value, integer_types + (float, complex, decimal.Decimal))128129130def test_sequence(value):131 """Return true if the variable is a sequence. Sequences are variables132 that are iterable.133 """134 try:135 len(value)136 value.__getitem__137 except Exception:138 return False139 return True140141142def test_sameas(value, other):143 """Check if an object points to the same memory address than another144 object:145146 .. sourcecode:: jinja147148 {% if foo.attribute is sameas false %}149 the foo attribute really is the `False` singleton150 {% endif %}151 """152 return value is other153154155def test_iterable(value):156 """Check if it's possible to iterate over an object."""157 try:158 iter(value)159 except TypeError:160 return False161 return True162163164def test_escaped(value):165 """Check if the value is escaped."""166 return hasattr(value, "__html__")167168169def test_in(value, seq):170 """Check if value is in seq.171172 .. versionadded:: 2.10173 """174 return value in seq175176177TESTS = {178 "odd": test_odd,179 "even": test_even,180 "divisibleby": test_divisibleby,181 "defined": test_defined,182 "undefined": test_undefined,183 "none": test_none,184 "boolean": test_boolean,185 "false": test_false,186 "true": test_true,187 "integer": test_integer,188 "float": test_float,189 "lower": test_lower,190 "upper": test_upper,191 "string": test_string,192 "mapping": test_mapping,193 "number": test_number,194 "sequence": test_sequence,195 "iterable": test_iterable,196 "callable": test_callable,197 "sameas": test_sameas,198 "escaped": test_escaped,199 "in": test_in,200 "==": operator.eq,201 "eq": operator.eq,202 "equalto": operator.eq,203 "!=": operator.ne,204 "ne": operator.ne,205 ">": operator.gt,206 "gt": operator.gt,207 "greaterthan": operator.gt,208 "ge": operator.ge,209 ">=": operator.ge,210 "<": operator.lt,211 "lt": operator.lt,212 "lessthan": operator.lt,213 "<=": operator.le,214 "le": operator.le,215}
deleted:src/jinja2/utils.py-727 removed
1# -*- coding: utf-8 -*-2import json3import os4import re5import warnings6from collections import deque7from random import choice8from random import randrange9from threading import Lock1011from markupsafe import escape12from markupsafe import Markup1314from ._compat import abc15from ._compat import string_types16from ._compat import text_type17from ._compat import url_quote1819_word_split_re = re.compile(r"(\s+)")20_punctuation_re = re.compile(21 "^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$"22 % (23 "|".join(map(re.escape, ("(", "<", "&lt;"))),24 "|".join(map(re.escape, (".", ",", ")", ">", "\n", "&gt;"))),25 )26)27_simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")28_striptags_re = re.compile(r"(<!--.*?-->|<[^>]*>)")29_entity_re = re.compile(r"&([^;]+);")30_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"31_digits = "0123456789"3233# special singleton representing missing values for the runtime34missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()3536# internal code37internal_code = set()3839concat = u"".join4041_slash_escape = "\\/" not in json.dumps("/")424344def contextfunction(f):45 """This decorator can be used to mark a function or method context callable.46 A context callable is passed the active :class:`Context` as first argument when47 called from the template. This is useful if a function wants to get access48 to the context or functions provided on the context object. For example49 a function that returns a sorted list of template variables the current50 template exports could look like this::5152 @contextfunction53 def get_exported_names(context):54 return sorted(context.exported_vars)55 """56 f.contextfunction = True57 return f585960def evalcontextfunction(f):61 """This decorator can be used to mark a function or method as an eval62 context callable. This is similar to the :func:`contextfunction`63 but instead of passing the context, an evaluation context object is64 passed. For more information about the eval context, see65 :ref:`eval-context`.6667 .. versionadded:: 2.468 """69 f.evalcontextfunction = True70 return f717273def environmentfunction(f):74 """This decorator can be used to mark a function or method as environment75 callable. This decorator works exactly like the :func:`contextfunction`76 decorator just that the first argument is the active :class:`Environment`77 and not context.78 """79 f.environmentfunction = True80 return f818283def internalcode(f):84 """Marks the function as internally used"""85 internal_code.add(f.__code__)86 return f878889def is_undefined(obj):90 """Check if the object passed is undefined. This does nothing more than91 performing an instance check against :class:`Undefined` but looks nicer.92 This can be used for custom filters or tests that want to react to93 undefined variables. For example a custom default filter can look like94 this::9596 def default(var, default=''):97 if is_undefined(var):98 return default99 return var100 """101 from .runtime import Undefined102103 return isinstance(obj, Undefined)104105106def consume(iterable):107 """Consumes an iterable without doing anything with it."""108 for _ in iterable:109 pass110111112def clear_caches():113 """Jinja keeps internal caches for environments and lexers. These are114 used so that Jinja doesn't have to recreate environments and lexers all115 the time. Normally you don't have to care about that but if you are116 measuring memory consumption you may want to clean the caches.117 """118 from .environment import _spontaneous_environments119 from .lexer import _lexer_cache120121 _spontaneous_environments.clear()122 _lexer_cache.clear()123124125def import_string(import_name, silent=False):126 """Imports an object based on a string. This is useful if you want to127 use import paths as endpoints or something similar. An import path can128 be specified either in dotted notation (``xml.sax.saxutils.escape``)129 or with a colon as object delimiter (``xml.sax.saxutils:escape``).130131 If the `silent` is True the return value will be `None` if the import132 fails.133134 :return: imported object135 """136 try:137 if ":" in import_name:138 module, obj = import_name.split(":", 1)139 elif "." in import_name:140 module, _, obj = import_name.rpartition(".")141 else:142 return __import__(import_name)143 return getattr(__import__(module, None, None, [obj]), obj)144 except (ImportError, AttributeError):145 if not silent:146 raise147148149def open_if_exists(filename, mode="rb"):150 """Returns a file descriptor for the filename if that file exists,151 otherwise ``None``.152 """153 if not os.path.isfile(filename):154 return None155156 return open(filename, mode)157158159def object_type_repr(obj):160 """Returns the name of the object's type. For some recognized161 singletons the name of the object is returned instead. (For162 example for `None` and `Ellipsis`).163 """164 if obj is None:165 return "None"166 elif obj is Ellipsis:167 return "Ellipsis"168 # __builtin__ in 2.x, builtins in 3.x169 if obj.__class__.__module__ in ("__builtin__", "builtins"):170 name = obj.__class__.__name__171 else:172 name = obj.__class__.__module__ + "." + obj.__class__.__name__173 return "%s object" % name174175176def pformat(obj, verbose=False):177 """Prettyprint an object. Either use the `pretty` library or the178 builtin `pprint`.179 """180 try:181 from pretty import pretty182183 return pretty(obj, verbose=verbose)184 except ImportError:185 from pprint import pformat186187 return pformat(obj)188189190def urlize(text, trim_url_limit=None, rel=None, target=None):191 """Converts any URLs in text into clickable links. Works on http://,192 https:// and www. links. Links can have trailing punctuation (periods,193 commas, close-parens) and leading punctuation (opening parens) and194 it'll still do the right thing.195196 If trim_url_limit is not None, the URLs in link text will be limited197 to trim_url_limit characters.198199 If nofollow is True, the URLs in link text will get a rel="nofollow"200 attribute.201202 If target is not None, a target attribute will be added to the link.203 """204 trim_url = (205 lambda x, limit=trim_url_limit: limit is not None206 and (x[:limit] + (len(x) >= limit and "..." or ""))207 or x208 )209 words = _word_split_re.split(text_type(escape(text)))210 rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ""211 target_attr = target and ' target="%s"' % escape(target) or ""212213 for i, word in enumerate(words):214 match = _punctuation_re.match(word)215 if match:216 lead, middle, trail = match.groups()217 if middle.startswith("www.") or (218 "@" not in middle219 and not middle.startswith("http://")220 and not middle.startswith("https://")221 and len(middle) > 0222 and middle[0] in _letters + _digits223 and (224 middle.endswith(".org")225 or middle.endswith(".net")226 or middle.endswith(".com")227 )228 ):229 middle = '<a href="http://%s"%s%s>%s</a>' % (230 middle,231 rel_attr,232 target_attr,233 trim_url(middle),234 )235 if middle.startswith("http://") or middle.startswith("https://"):236 middle = '<a href="%s"%s%s>%s</a>' % (237 middle,238 rel_attr,239 target_attr,240 trim_url(middle),241 )242 if (243 "@" in middle244 and not middle.startswith("www.")245 and ":" not in middle246 and _simple_email_re.match(middle)247 ):248 middle = '<a href="mailto:%s">%s</a>' % (middle, middle)249 if lead + middle + trail != word:250 words[i] = lead + middle + trail251 return u"".join(words)252253254def generate_lorem_ipsum(n=5, html=True, min=20, max=100):255 """Generate some lorem ipsum for the template."""256 from .constants import LOREM_IPSUM_WORDS257258 words = LOREM_IPSUM_WORDS.split()259 result = []260261 for _ in range(n):262 next_capitalized = True263 last_comma = last_fullstop = 0264 word = None265 last = None266 p = []267268 # each paragraph contains out of 20 to 100 words.269 for idx, _ in enumerate(range(randrange(min, max))):270 while True:271 word = choice(words)272 if word != last:273 last = word274 break275 if next_capitalized:276 word = word.capitalize()277 next_capitalized = False278 # add commas279 if idx - randrange(3, 8) > last_comma:280 last_comma = idx281 last_fullstop += 2282 word += ","283 # add end of sentences284 if idx - randrange(10, 20) > last_fullstop:285 last_comma = last_fullstop = idx286 word += "."287 next_capitalized = True288 p.append(word)289290 # ensure that the paragraph ends with a dot.291 p = u" ".join(p)292 if p.endswith(","):293 p = p[:-1] + "."294 elif not p.endswith("."):295 p += "."296 result.append(p)297298 if not html:299 return u"\n\n".join(result)300 return Markup(u"\n".join(u"<p>%s</p>" % escape(x) for x in result))301302303def unicode_urlencode(obj, charset="utf-8", for_qs=False):304 """Quote a string for use in a URL using the given charset.305306 This function is misnamed, it is a wrapper around307 :func:`urllib.parse.quote`.308309 :param obj: String or bytes to quote. Other types are converted to310 string then encoded to bytes using the given charset.311 :param charset: Encode text to bytes using this charset.312 :param for_qs: Quote "/" and use "+" for spaces.313 """314 if not isinstance(obj, string_types):315 obj = text_type(obj)316317 if isinstance(obj, text_type):318 obj = obj.encode(charset)319320 safe = b"" if for_qs else b"/"321 rv = url_quote(obj, safe)322323 if not isinstance(rv, text_type):324 rv = rv.decode("utf-8")325326 if for_qs:327 rv = rv.replace("%20", "+")328329 return rv330331332class LRUCache(object):333 """A simple LRU Cache implementation."""334335 # this is fast for small capacities (something below 1000) but doesn't336 # scale. But as long as it's only used as storage for templates this337 # won't do any harm.338339 def __init__(self, capacity):340 self.capacity = capacity341 self._mapping = {}342 self._queue = deque()343 self._postinit()344345 def _postinit(self):346 # alias all queue methods for faster lookup347 self._popleft = self._queue.popleft348 self._pop = self._queue.pop349 self._remove = self._queue.remove350 self._wlock = Lock()351 self._append = self._queue.append352353 def __getstate__(self):354 return {355 "capacity": self.capacity,356 "_mapping": self._mapping,357 "_queue": self._queue,358 }359360 def __setstate__(self, d):361 self.__dict__.update(d)362 self._postinit()363364 def __getnewargs__(self):365 return (self.capacity,)366367 def copy(self):368 """Return a shallow copy of the instance."""369 rv = self.__class__(self.capacity)370 rv._mapping.update(self._mapping)371 rv._queue.extend(self._queue)372 return rv373374 def get(self, key, default=None):375 """Return an item from the cache dict or `default`"""376 try:377 return self[key]378 except KeyError:379 return default380381 def setdefault(self, key, default=None):382 """Set `default` if the key is not in the cache otherwise383 leave unchanged. Return the value of this key.384 """385 try:386 return self[key]387 except KeyError:388 self[key] = default389 return default390391 def clear(self):392 """Clear the cache."""393 self._wlock.acquire()394 try:395 self._mapping.clear()396 self._queue.clear()397 finally:398 self._wlock.release()399400 def __contains__(self, key):401 """Check if a key exists in this cache."""402 return key in self._mapping403404 def __len__(self):405 """Return the current size of the cache."""406 return len(self._mapping)407408 def __repr__(self):409 return "<%s %r>" % (self.__class__.__name__, self._mapping)410411 def __getitem__(self, key):412 """Get an item from the cache. Moves the item up so that it has the413 highest priority then.414415 Raise a `KeyError` if it does not exist.416 """417 self._wlock.acquire()418 try:419 rv = self._mapping[key]420 if self._queue[-1] != key:421 try:422 self._remove(key)423 except ValueError:424 # if something removed the key from the container425 # when we read, ignore the ValueError that we would426 # get otherwise.427 pass428 self._append(key)429 return rv430 finally:431 self._wlock.release()432433 def __setitem__(self, key, value):434 """Sets the value for an item. Moves the item up so that it435 has the highest priority then.436 """437 self._wlock.acquire()438 try:439 if key in self._mapping:440 self._remove(key)441 elif len(self._mapping) == self.capacity:442 del self._mapping[self._popleft()]443 self._append(key)444 self._mapping[key] = value445 finally:446 self._wlock.release()447448 def __delitem__(self, key):449 """Remove an item from the cache dict.450 Raise a `KeyError` if it does not exist.451 """452 self._wlock.acquire()453 try:454 del self._mapping[key]455 try:456 self._remove(key)457 except ValueError:458 pass459 finally:460 self._wlock.release()461462 def items(self):463 """Return a list of items."""464 result = [(key, self._mapping[key]) for key in list(self._queue)]465 result.reverse()466 return result467468 def iteritems(self):469 """Iterate over all items."""470 warnings.warn(471 "'iteritems()' will be removed in version 3.0. Use"472 " 'iter(cache.items())' instead.",473 DeprecationWarning,474 stacklevel=2,475 )476 return iter(self.items())477478 def values(self):479 """Return a list of all values."""480 return [x[1] for x in self.items()]481482 def itervalue(self):483 """Iterate over all values."""484 warnings.warn(485 "'itervalue()' will be removed in version 3.0. Use"486 " 'iter(cache.values())' instead.",487 DeprecationWarning,488 stacklevel=2,489 )490 return iter(self.values())491492 def itervalues(self):493 """Iterate over all values."""494 warnings.warn(495 "'itervalues()' will be removed in version 3.0. Use"496 " 'iter(cache.values())' instead.",497 DeprecationWarning,498 stacklevel=2,499 )500 return iter(self.values())501502 def keys(self):503 """Return a list of all keys ordered by most recent usage."""504 return list(self)505506 def iterkeys(self):507 """Iterate over all keys in the cache dict, ordered by508 the most recent usage.509 """510 warnings.warn(511 "'iterkeys()' will be removed in version 3.0. Use"512 " 'iter(cache.keys())' instead.",513 DeprecationWarning,514 stacklevel=2,515 )516 return iter(self)517518 def __iter__(self):519 return reversed(tuple(self._queue))520521 def __reversed__(self):522 """Iterate over the keys in the cache dict, oldest items523 coming first.524 """525 return iter(tuple(self._queue))526527 __copy__ = copy528529530abc.MutableMapping.register(LRUCache)531532533def select_autoescape(534 enabled_extensions=("html", "htm", "xml"),535 disabled_extensions=(),536 default_for_string=True,537 default=False,538):539 """Intelligently sets the initial value of autoescaping based on the540 filename of the template. This is the recommended way to configure541 autoescaping if you do not want to write a custom function yourself.542543 If you want to enable it for all templates created from strings or544 for all templates with `.html` and `.xml` extensions::545546 from jinja2 import Environment, select_autoescape547 env = Environment(autoescape=select_autoescape(548 enabled_extensions=('html', 'xml'),549 default_for_string=True,550 ))551552 Example configuration to turn it on at all times except if the template553 ends with `.txt`::554555 from jinja2 import Environment, select_autoescape556 env = Environment(autoescape=select_autoescape(557 disabled_extensions=('txt',),558 default_for_string=True,559 default=True,560 ))561562 The `enabled_extensions` is an iterable of all the extensions that563 autoescaping should be enabled for. Likewise `disabled_extensions` is564 a list of all templates it should be disabled for. If a template is565 loaded from a string then the default from `default_for_string` is used.566 If nothing matches then the initial value of autoescaping is set to the567 value of `default`.568569 For security reasons this function operates case insensitive.570571 .. versionadded:: 2.9572 """573 enabled_patterns = tuple("." + x.lstrip(".").lower() for x in enabled_extensions)574 disabled_patterns = tuple("." + x.lstrip(".").lower() for x in disabled_extensions)575576 def autoescape(template_name):577 if template_name is None:578 return default_for_string579 template_name = template_name.lower()580 if template_name.endswith(enabled_patterns):581 return True582 if template_name.endswith(disabled_patterns):583 return False584 return default585586 return autoescape587588589def htmlsafe_json_dumps(obj, dumper=None, **kwargs):590 """Works exactly like :func:`dumps` but is safe for use in ``<script>``591 tags. It accepts the same arguments and returns a JSON string. Note that592 this is available in templates through the ``|tojson`` filter which will593 also mark the result as safe. Due to how this function escapes certain594 characters this is safe even if used outside of ``<script>`` tags.595596 The following characters are escaped in strings:597598 - ``<``599 - ``>``600 - ``&``601 - ``'``602603 This makes it safe to embed such strings in any place in HTML with the604 notable exception of double quoted attributes. In that case single605 quote your attributes or HTML escape it in addition.606 """607 if dumper is None:608 dumper = json.dumps609 rv = (610 dumper(obj, **kwargs)611 .replace(u"<", u"\\u003c")612 .replace(u">", u"\\u003e")613 .replace(u"&", u"\\u0026")614 .replace(u"'", u"\\u0027")615 )616 return Markup(rv)617618619class Cycler(object):620 """Cycle through values by yield them one at a time, then restarting621 once the end is reached. Available as ``cycler`` in templates.622623 Similar to ``loop.cycle``, but can be used outside loops or across624 multiple loops. For example, render a list of folders and files in a625 list, alternating giving them "odd" and "even" classes.626627 .. code-block:: html+jinja628629 {% set row_class = cycler("odd", "even") %}630 <ul class="browser">631 {% for folder in folders %}632 <li class="folder {{ row_class.next() }}">{{ folder }}633 {% endfor %}634 {% for file in files %}635 <li class="file {{ row_class.next() }}">{{ file }}636 {% endfor %}637 </ul>638639 :param items: Each positional argument will be yielded in the order640 given for each cycle.641642 .. versionadded:: 2.1643 """644645 def __init__(self, *items):646 if not items:647 raise RuntimeError("at least one item has to be provided")648 self.items = items649 self.pos = 0650651 def reset(self):652 """Resets the current item to the first item."""653 self.pos = 0654655 @property656 def current(self):657 """Return the current item. Equivalent to the item that will be658 returned next time :meth:`next` is called.659 """660 return self.items[self.pos]661662 def next(self):663 """Return the current item, then advance :attr:`current` to the664 next item.665 """666 rv = self.current667 self.pos = (self.pos + 1) % len(self.items)668 return rv669670 __next__ = next671672673class Joiner(object):674 """A joining helper for templates."""675676 def __init__(self, sep=u", "):677 self.sep = sep678 self.used = False679680 def __call__(self):681 if not self.used:682 self.used = True683 return u""684 return self.sep685686687class Namespace(object):688 """A namespace object that can hold arbitrary attributes. It may be689 initialized from a dictionary or with keyword arguments."""690691 def __init__(*args, **kwargs): # noqa: B902692 self, args = args[0], args[1:]693 self.__attrs = dict(*args, **kwargs)694695 def __getattribute__(self, name):696 if name == "_Namespace__attrs":697 return object.__getattribute__(self, name)698 try:699 return self.__attrs[name]700 except KeyError:701 raise AttributeError(name)702703 def __setitem__(self, name, value):704 self.__attrs[name] = value705706 def __repr__(self):707 return "<Namespace %r>" % self.__attrs708709710# does this python version support async for in and async generators?711try:712 exec("async def _():\n async for _ in ():\n yield _")713 have_async_gen = True714except SyntaxError:715 have_async_gen = False716717718def soft_unicode(s):719 from markupsafe import soft_unicode720721 warnings.warn(722 "'jinja2.utils.soft_unicode' will be removed in version 3.0."723 " Use 'markupsafe.soft_unicode' instead.",724 DeprecationWarning,725 stacklevel=2,726 )727 return soft_unicode(s)
deleted:src/jinja2/visitor.py-81 removed
1# -*- coding: utf-8 -*-2"""API for traversing the AST nodes. Implemented by the compiler and3meta introspection.4"""5from .nodes import Node678class NodeVisitor(object):9 """Walks the abstract syntax tree and call visitor functions for every10 node found. The visitor functions may return values which will be11 forwarded by the `visit` method.1213 Per default the visitor functions for the nodes are ``'visit_'`` +14 class name of the node. So a `TryFinally` node visit function would15 be `visit_TryFinally`. This behavior can be changed by overriding16 the `get_visitor` function. If no visitor function exists for a node17 (return value `None`) the `generic_visit` visitor is used instead.18 """1920 def get_visitor(self, node):21 """Return the visitor function for this node or `None` if no visitor22 exists for this node. In that case the generic visit function is23 used instead.24 """25 method = "visit_" + node.__class__.__name__26 return getattr(self, method, None)2728 def visit(self, node, *args, **kwargs):29 """Visit a node."""30 f = self.get_visitor(node)31 if f is not None:32 return f(node, *args, **kwargs)33 return self.generic_visit(node, *args, **kwargs)3435 def generic_visit(self, node, *args, **kwargs):36 """Called if no explicit visitor function exists for a node."""37 for node in node.iter_child_nodes():38 self.visit(node, *args, **kwargs)394041class NodeTransformer(NodeVisitor):42 """Walks the abstract syntax tree and allows modifications of nodes.4344 The `NodeTransformer` will walk the AST and use the return value of the45 visitor functions to replace or remove the old node. If the return46 value of the visitor function is `None` the node will be removed47 from the previous location otherwise it's replaced with the return48 value. The return value may be the original node in which case no49 replacement takes place.50 """5152 def generic_visit(self, node, *args, **kwargs):53 for field, old_value in node.iter_fields():54 if isinstance(old_value, list):55 new_values = []56 for value in old_value:57 if isinstance(value, Node):58 value = self.visit(value, *args, **kwargs)59 if value is None:60 continue61 elif not isinstance(value, Node):62 new_values.extend(value)63 continue64 new_values.append(value)65 old_value[:] = new_values66 elif isinstance(old_value, Node):67 new_node = self.visit(old_value, *args, **kwargs)68 if new_node is None:69 delattr(node, field)70 else:71 setattr(node, field, new_node)72 return node7374 def visit_list(self, node, *args, **kwargs):75 """As transformers may return lists in some places this method76 can be used to enforce a list as return value.77 """78 rv = self.visit(node, *args, **kwargs)79 if not isinstance(rv, list):80 rv = [rv]81 return rv
modified:tests/conftest.py+3 added-3 removed
1 unmodified line
2import os34import pytest56from jinja2 import Environment7from jinja2 import loaders8from jinja2.utils import have_async_gen6from jinja import Environment7from jinja import loaders8from jinja.utils import have_async_gen91011def pytest_ignore_collect(path):12 if "async" in path.basename and not have_async_gen:
89 unmodified lines
modified:tests/test_api.py+20 added-20 removed
3 unmodified lines
4import tempfile56import pytest78from jinja2 import ChainableUndefined9from jinja2 import DebugUndefined10from jinja2 import DictLoader11from jinja2 import Environment12from jinja2 import is_undefined13from jinja2 import make_logging_undefined14from jinja2 import meta15from jinja2 import StrictUndefined16from jinja2 import Template17from jinja2 import TemplatesNotFound18from jinja2 import Undefined19from jinja2 import UndefinedError20from jinja2.compiler import CodeGenerator21from jinja2.runtime import Context22from jinja2.utils import contextfunction23from jinja2.utils import Cycler24from jinja2.utils import environmentfunction25from jinja2.utils import evalcontextfunction8from jinja import ChainableUndefined9from jinja import DebugUndefined10from jinja import DictLoader11from jinja import Environment12from jinja import is_undefined13from jinja import make_logging_undefined14from jinja import meta15from jinja import StrictUndefined16from jinja import Template17from jinja import TemplatesNotFound18from jinja import Undefined19from jinja import UndefinedError20from jinja.compiler import CodeGenerator21from jinja.runtime import Context22from jinja.utils import contextfunction23from jinja.utils import Cycler24from jinja.utils import environmentfunction25from jinja.utils import evalcontextfunction262728@pytest.mark.api29@pytest.mark.extended30class TestExtendedAPI(object):31 def test_item_and_attribute(self, env):32 from jinja2.sandbox import SandboxedEnvironment32 from jinja.sandbox import SandboxedEnvironment3334 for env in Environment(), SandboxedEnvironment():35 # the |list is necessary for python336 tmpl = env.from_string("{{ foo.items()|list }}")
116 unmodified lines
153 t = env.from_string("{{ foo }}")154 assert t.render(foo="<foo>") == "<foo>"155156 def test_sandbox_max_range(self, env):157 from jinja2.sandbox import SandboxedEnvironment, MAX_RANGE157 from jinja.sandbox import SandboxedEnvironment, MAX_RANGE158159 env = SandboxedEnvironment()160 t = env.from_string("{% for item in range(total) %}{{ item }}{% endfor %}")161
271 unmodified lines
modified:tests/test_async.py+7 added-7 removed
1import asyncio23import pytest45from jinja2 import DictLoader6from jinja2 import Environment7from jinja2 import Template8from jinja2.asyncsupport import auto_aiter9from jinja2.exceptions import TemplateNotFound10from jinja2.exceptions import TemplatesNotFound11from jinja2.exceptions import UndefinedError5from jinja import DictLoader6from jinja import Environment7from jinja import Template8from jinja.asyncsupport import auto_aiter9from jinja.exceptions import TemplateNotFound10from jinja.exceptions import TemplatesNotFound11from jinja.exceptions import UndefinedError121314def run(coro):15 loop = asyncio.get_event_loop()
566 unmodified lines
modified:tests/test_asyncfilters.py+2 added-2 removed
1from collections import namedtuple23import pytest45from jinja2 import Environment6from jinja2.utils import Markup5from jinja import Environment6from jinja.utils import Markup789async def make_aiter(iter):10 for item in iter:
214 unmodified lines
modified:tests/test_bytecode_cache.py+9 added-9 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import Environment5from jinja2.bccache import Bucket6from jinja2.bccache import FileSystemBytecodeCache7from jinja2.bccache import MemcachedBytecodeCache8from jinja2.exceptions import TemplateNotFound4from jinja import Environment5from jinja.bccache import Bucket6from jinja.bccache import FileSystemBytecodeCache7from jinja.bccache import MemcachedBytecodeCache8from jinja.exceptions import TemplateNotFound91011@pytest.fixture12def env(package_loader):13 bytecode_cache = FileSystemBytecodeCache()14 return Environment(loader=package_loader, bytecode_cache=bytecode_cache,)12def env(package_loader, tmp_path):13 bytecode_cache = FileSystemBytecodeCache(str(tmp_path))14 return Environment(loader=package_loader, bytecode_cache=bytecode_cache)151617@pytest.mark.byte_code_cache18class TestByteCodeCache(object):
33 unmodified lines
5253 b = Bucket(None, "key", "")54 b.code = "code"55 m.dump_bytecode(b)56 assert memcached.key == "jinja2/bytecode/key"56 assert memcached.key == "jinja/bytecode/key"5758 b = Bucket(None, "key", "")59 m.load_bytecode(b)60 assert b.code == "code"
19 unmodified lines
modified:tests/test_core_tags.py+5 added-5 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import DictLoader5from jinja2 import Environment6from jinja2 import TemplateRuntimeError7from jinja2 import TemplateSyntaxError8from jinja2 import UndefinedError4from jinja import DictLoader5from jinja import Environment6from jinja import TemplateRuntimeError7from jinja import TemplateSyntaxError8from jinja import UndefinedError91011@pytest.fixture12def env_trim():
600 unmodified lines
modified:tests/test_debug.py+8 added-8 removed
3 unmodified lines
4from traceback import format_exception56import pytest78from jinja2 import ChoiceLoader9from jinja2 import DictLoader10from jinja2 import Environment11from jinja2 import TemplateSyntaxError8from jinja import ChoiceLoader9from jinja import DictLoader10from jinja import Environment11from jinja import TemplateSyntaxError121314@pytest.fixture15def fs_env(filesystem_loader):
38 unmodified lines
54 lambda: fs_env.get_template("syntaxerror.html"),55 """(?sm)56 File ".*?syntaxerror.html", line 4, in (template|<module>)57 \\{% endif %\\}.*?58(jinja2\\.exceptions\\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja \58(jinja\\.exceptions\\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja \59was looking for the following tags: 'endfor' or 'else'. The innermost block that needs \60to be closed is 'for'.61 """,62 )
6 unmodified lines
69 test,70 r"""71 File ".*debug.pyc?", line \d+, in test72 raise TemplateSyntaxError\("wtf", 42\)73(jinja2\.exceptions\.)?TemplateSyntaxError: wtf73(jinja\.exceptions\.)?TemplateSyntaxError: wtf74 line 42""",75 )7677 def test_pickleable_syntax_error(self, fs_env):
18 unmodified lines
9697 assert exc_info.value.source is not None9899 def test_local_extraction(self):100 from jinja2.debug import get_template_locals101 from jinja2.runtime import missing100 from jinja.debug import get_template_locals101 from jinja.runtime import missing102103 locals = get_template_locals(104 {105 "l_0_foo": 42,
12 unmodified lines
modified:tests/test_ext.py+32 added-34 removed
1 unmodified line
2import re34import pytest56from jinja2 import contextfunction7from jinja2 import DictLoader8from jinja2 import Environment9from jinja2 import nodes10from jinja2._compat import BytesIO11from jinja2._compat import itervalues12from jinja2._compat import text_type13from jinja2.exceptions import TemplateAssertionError14from jinja2.ext import Extension15from jinja2.lexer import count_newlines16from jinja2.lexer import Token6from jinja import contextfunction7from jinja import DictLoader8from jinja import Environment9from jinja import nodes10from jinja._compat import BytesIO11from jinja._compat import itervalues12from jinja._compat import text_type13from jinja.exceptions import TemplateAssertionError14from jinja.ext import Extension15from jinja.lexer import count_newlines16from jinja.lexer import Token1718importable_object = 231920_gettext_re = re.compile(r"_\((.*?)\)", re.DOTALL)
58 unmodified lines
79 return languages.get(language, {}).get(p, p)80 return languages.get(language, {}).get(s, s)818283i18n_env = Environment(84 loader=DictLoader(i18n_templates), extensions=["jinja2.ext.i18n"]85)83i18n_env = Environment(loader=DictLoader(i18n_templates), extensions=["jinja.ext.i18n"])84i18n_env.globals.update({"_": gettext, "gettext": gettext, "ngettext": ngettext})87i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"])85i18n_env_trimmed = Environment(extensions=["jinja.ext.i18n"])86i18n_env_trimmed.policies["ext.i18n.trimmed"] = True87i18n_env_trimmed.globals.update(88 {"_": gettext, "gettext": gettext, "ngettext": ngettext}89)9091newstyle_i18n_env = Environment(94 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"]92 loader=DictLoader(newstyle_i18n_templates), extensions=["jinja.ext.i18n"]93)94newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)9596
71 unmodified lines
168@pytest.mark.ext169class TestExtensions(object):170 def test_extend_late(self):171 env = Environment()174 env.add_extension("jinja2.ext.autoescape")172 env.add_extension("jinja.ext.autoescape")173 t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')174 assert t.render() == "&lt;test&gt;"175176 def test_loop_controls(self):179 env = Environment(extensions=["jinja2.ext.loopcontrols"])177 env = Environment(extensions=["jinja.ext.loopcontrols"])178179 tmpl = env.from_string(180 """181 {%- for item in [1, 2, 3, 4] %}
12 unmodified lines
194 )195 assert tmpl.render() == "12"196197 def test_do(self):200 env = Environment(extensions=["jinja2.ext.do"])198 env = Environment(extensions=["jinja.ext.do"])199 tmpl = env.from_string(200 """201 {%- set items = [] %}202 {%- for char in "foo" %}
53 unmodified lines
256 assert ext[0].__class__ is T1257 assert ext[1].__class__ is T2258259 def test_debug(self):262 env = Environment(extensions=["jinja2.ext.debug"])260 env = Environment(extensions=["jinja.ext.debug"])261 t = env.from_string("Hello\n{% debug %}\nGoodbye")262 out = t.render()263264 for value in ("context", "cycler", "filters", "abs", "tests", "!="):
71 unmodified lines
336 )337 assert tmpl.render() == " hello\n world "338339 def test_extract(self):342 from jinja2.ext import babel_extract340 from jinja.ext import babel_extract341342 source = BytesIO(343 """344 {{ gettext('Hello World') }}
9 unmodified lines
354 (4, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),355 ]356357 def test_extract_trimmed(self):360 from jinja2.ext import babel_extract358 from jinja.ext import babel_extract359360 source = BytesIO(361 """362 {{ gettext(' Hello \n World') }}
10 unmodified lines
373 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),374 ]375376 def test_extract_trimmed_option(self):379 from jinja2.ext import babel_extract377 from jinja.ext import babel_extract378379 source = BytesIO(380 """381 {{ gettext(' Hello \n World') }}
11 unmodified lines
393 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),394 ]395396 def test_comment_extract(self):399 from jinja2.ext import babel_extract397 from jinja.ext import babel_extract398399 source = BytesIO(400 """401 {# trans first #}
80 unmodified lines
482 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apfel"483 assert tmpl.render(LANGUAGE="de", apples=5) == u"5 Äpfel"484485 def test_autoescape_support(self):488 env = Environment(extensions=["jinja2.ext.autoescape", "jinja2.ext.i18n"])486 env = Environment(extensions=["jinja.ext.autoescape", "jinja.ext.i18n"])487 env.install_gettext_callables(488 lambda x: u"<strong>Wert: %(name)s</strong>",489 lambda s, p, n: s,490 newstyle=True,
5 unmodified lines
496 assert t.render(ae=True) == "<strong>Wert: &lt;test&gt;</strong>"497 assert t.render(ae=False) == "<strong>Wert: <test></strong>"498499 def test_autoescape_macros(self):502 env = Environment(autoescape=False, extensions=["jinja2.ext.autoescape"])500 env = Environment(autoescape=False, extensions=["jinja.ext.autoescape"])501 template = (502 "{% macro m() %}<html>{% endmacro %}"503 "{% autoescape true %}{{ m() }}{% endautoescape %}"504 )
39 unmodified lines
544545@pytest.mark.ext546class TestAutoEscape(object):547 def test_scoped_setting(self):550 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)548 env = Environment(extensions=["jinja.ext.autoescape"], autoescape=True)549 tmpl = env.from_string(550 """551 {{ "<HelloWorld>" }}552 {% autoescape false %}
7 unmodified lines
560 u"<HelloWorld>",561 u"&lt;HelloWorld&gt;",562 ]563566 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=False)564 env = Environment(extensions=["jinja.ext.autoescape"], autoescape=False)565 tmpl = env.from_string(566 """567 {{ "<HelloWorld>" }}568 {% autoescape true %}
8 unmodified lines
577 u"<HelloWorld>",578 ]579580 def test_nonvolatile(self):583 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)581 env = Environment(extensions=["jinja.ext.autoescape"], autoescape=True)582 tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}')583 assert tmpl.render() == ' foo="&lt;test&gt;"'584 tmpl = env.from_string(585 '{% autoescape false %}{{ {"foo": "<test>"}'
1 unmodified line
587 )588 assert tmpl.render() == " foo=&#34;&amp;lt;test&amp;gt;&#34;"589590 def test_volatile(self):593 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)591 env = Environment(extensions=["jinja.ext.autoescape"], autoescape=True)592 tmpl = env.from_string(593 '{% autoescape foo %}{{ {"foo": "<test>"}'594 "|xmlattr|escape }}{% endautoescape %}"595 )596 assert tmpl.render(foo=False) == " foo=&#34;&amp;lt;test&amp;gt;&#34;"597 assert tmpl.render(foo=True) == ' foo="&lt;test&gt;"'598599 def test_scoping(self):602 env = Environment(extensions=["jinja2.ext.autoescape"])600 env = Environment(extensions=["jinja.ext.autoescape"])601 tmpl = env.from_string(602 '{% autoescape true %}{% set x = "<x>" %}{{ x }}'603 '{% endautoescape %}{{ x }}{{ "<y>" }}'604 )605 assert tmpl.render(x=1) == "&lt;x&gt;1<y>"606607 def test_volatile_scoping(self):610 env = Environment(extensions=["jinja2.ext.autoescape"])608 env = Environment(extensions=["jinja.ext.autoescape"])609 tmplsource = """610 {% autoescape val %}611 {% macro foo(x) %}612 [{{ x }}]
7 unmodified lines
620 assert tmpl.render(val=False).split()[0] == text_type.__name__621622 # looking at the source we should see <testing> there in raw623 # (and then escaped as well)626 env = Environment(extensions=["jinja2.ext.autoescape"])624 env = Environment(extensions=["jinja.ext.autoescape"])625 pysource = env.compile(tmplsource, raw=True)626 assert "<testing>\\n" in pysource627630 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)628 env = Environment(extensions=["jinja.ext.autoescape"], autoescape=True)629 pysource = env.compile(tmplsource, raw=True)630 assert "&lt;testing&gt;\\n" in pysource631632 def test_overlay_scopes(self):
26 unmodified lines
modified:tests/test_features.py+4 added-4 removed
1import sys23import pytest45from jinja2 import contextfilter6from jinja2 import Environment7from jinja2 import Template8from jinja2._compat import text_type5from jinja import contextfilter6from jinja import Environment7from jinja import Template8from jinja._compat import text_type91011@pytest.mark.skipif(sys.version_info < (3, 5), reason="Requires 3.5 or later")12def test_generator_stop():
30 unmodified lines
modified:tests/test_filters.py+4 added-4 removed
2 unmodified lines
3from collections import namedtuple45import pytest67from jinja2 import Environment8from jinja2 import Markup9from jinja2._compat import implements_to_string10from jinja2._compat import text_type7from jinja import Environment8from jinja import Markup9from jinja._compat import implements_to_string10from jinja._compat import text_type111213@implements_to_string14class Magic(object):
731 unmodified lines
modified:tests/test_idtracking.py+2 added-2 removed
1from jinja2 import nodes2from jinja2.idtracking import symbols_for_node1from jinja import nodes2from jinja.idtracking import symbols_for_node345def test_basics():6 for_loop = nodes.For(
283 unmodified lines
modified:tests/test_imports.py+5 added-5 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import DictLoader5from jinja2 import Environment6from jinja2.exceptions import TemplateNotFound7from jinja2.exceptions import TemplatesNotFound8from jinja2.exceptions import TemplateSyntaxError4from jinja import DictLoader5from jinja import Environment6from jinja.exceptions import TemplateNotFound7from jinja.exceptions import TemplatesNotFound8from jinja.exceptions import TemplateSyntaxError91011@pytest.fixture12def test_env():
167 unmodified lines
modified:tests/test_inheritance.py+3 added-3 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import DictLoader5from jinja2 import Environment6from jinja2 import TemplateRuntimeError4from jinja import DictLoader5from jinja import Environment6from jinja import TemplateRuntimeError78LAYOUTTEMPLATE = """\9|{% block block1 %}block 1 from layout{% endblock %}10|{% block block2 %}block 2 from layout{% endblock %}
277 unmodified lines
modified:tests/test_lexnparse.py+14 added-14 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import Environment5from jinja2 import nodes6from jinja2 import Template7from jinja2 import TemplateSyntaxError8from jinja2 import UndefinedError9from jinja2._compat import iteritems10from jinja2._compat import PY211from jinja2._compat import text_type12from jinja2.lexer import Token13from jinja2.lexer import TOKEN_BLOCK_BEGIN14from jinja2.lexer import TOKEN_BLOCK_END15from jinja2.lexer import TOKEN_EOF16from jinja2.lexer import TokenStream4from jinja import Environment5from jinja import nodes6from jinja import Template7from jinja import TemplateSyntaxError8from jinja import UndefinedError9from jinja._compat import iteritems10from jinja._compat import PY211from jinja._compat import text_type12from jinja.lexer import Token13from jinja.lexer import TOKEN_BLOCK_BEGIN14from jinja.lexer import TOKEN_BLOCK_END15from jinja.lexer import TOKEN_EOF16from jinja.lexer import TokenStream171819# how does a string look like in jinja syntax?20if PY2:
100 unmodified lines
121 tmpl = env.from_string(u"""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")122 assert tmpl.render() == pformat("foo") + "|" + pformat(u"bär")123124 def test_operators(self, env):125 from jinja2.lexer import operators125 from jinja.lexer import operators126127 for test, expect in iteritems(operators):128 if test in "([{}])":129 continue
701 unmodified lines
modified:tests/test_loader.py+7 added-7 removed
6 unmodified lines
7import weakref89import pytest1011from jinja2 import Environment12from jinja2 import loaders13from jinja2 import PackageLoader14from jinja2._compat import PY215from jinja2._compat import PYPY16from jinja2.exceptions import TemplateNotFound17from jinja2.loaders import split_template_path11from jinja import Environment12from jinja import loaders13from jinja import PackageLoader14from jinja._compat import PY215from jinja._compat import PYPY16from jinja.exceptions import TemplateNotFound17from jinja.loaders import split_template_path181920@pytest.mark.loaders21class TestLoaders(object):
356 unmodified lines
modified:tests/test_nativetypes.py+5 added-5 removed
1import pytest23from jinja2._compat import text_type4from jinja2.exceptions import UndefinedError5from jinja2.nativetypes import NativeEnvironment6from jinja2.nativetypes import NativeTemplate7from jinja2.runtime import Undefined3from jinja._compat import text_type4from jinja.exceptions import UndefinedError5from jinja.nativetypes import NativeEnvironment6from jinja.nativetypes import NativeTemplate7from jinja.runtime import Undefined8910@pytest.fixture11def env():
128 unmodified lines
modified:tests/test_regression.py+15 added-15 removed
1 unmodified line
2import sys34import pytest56from jinja2 import DictLoader7from jinja2 import Environment8from jinja2 import PrefixLoader9from jinja2 import Template10from jinja2 import TemplateAssertionError11from jinja2 import TemplateNotFound12from jinja2 import TemplateSyntaxError13from jinja2._compat import text_type6from jinja import DictLoader7from jinja import Environment8from jinja import PrefixLoader9from jinja import Template10from jinja import TemplateAssertionError11from jinja import TemplateNotFound12from jinja import TemplateSyntaxError13from jinja._compat import text_type141516@pytest.mark.regression17class TestCorner(object):
276 unmodified lines
294295 assert e.value.name == "foo/bar.html"296297 def test_contextfunction_callable_classes(self, env):298 from jinja2.utils import contextfunction298 from jinja.utils import contextfunction299300 class CallableClass(object):301 @contextfunction302 def __call__(self, ctx):
65 unmodified lines
368 assert t.render().strip() == "45|6"369370 def test_macro_escaping(self):371 env = Environment(372 autoescape=lambda x: False, extensions=["jinja2.ext.autoescape"]372 autoescape=lambda x: False, extensions=["jinja.ext.autoescape"]373 )374 template = "{% macro m() %}<html>{% endmacro %}"375 template += "{% autoescape true %}{{ m() }}{% endautoescape %}"376 assert env.from_string(template).render()
199 unmodified lines
576 )577 assert env.get_template("main").render() == "123"578579 def test_grouper_repr(self):580 from jinja2.filters import _GroupTuple580 from jinja.filters import _GroupTuple581582 t = _GroupTuple("foo", [1, 2])583 assert t.grouper == "foo"584 assert t.list == [1, 2]585 assert repr(t) == "('foo', [1, 2])"586 assert str(t) == "('foo', [1, 2])"587588 def test_custom_context(self, env):589 from jinja2.runtime import Context589 from jinja.runtime import Context590591 class MyContext(Context):592 pass593
4 unmodified lines
598 env = MyEnvironment(loader=loader)599 assert env.get_template("test").render(foobar="test") == "test"600601 def test_legacy_custom_context(self, env):602 from jinja2.runtime import Context, missing602 from jinja.runtime import Context, missing603604 class MyContext(Context):605 def resolve(self, name):606 if name == "foo":
12 unmodified lines
619 )620 assert tmpl.render(values=[]) == "0"621622 def test_markup_and_chainable_undefined(self):623 from jinja2 import Markup624 from jinja2.runtime import ChainableUndefined623 from jinja import Markup624 from jinja.runtime import ChainableUndefined625626 assert str(Markup(ChainableUndefined())) == ""
modified:tests/test_runtime.py+2 added-2 removed
1import itertools23from jinja2 import Template4from jinja2.runtime import LoopContext3from jinja import Template4from jinja.runtime import LoopContext56TEST_IDX_TEMPLATE_STR_1 = (7 "[{% for i in lst|reverse %}(len={{ loop.length }},"8 " revindex={{ loop.revindex }}, index={{ loop.index }}, val={{ i }}){% endfor %}]"
48 unmodified lines
modified:tests/test_security.py+11 added-11 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import Environment5from jinja2 import escape6from jinja2 import Markup7from jinja2._compat import text_type8from jinja2.exceptions import SecurityError9from jinja2.exceptions import TemplateRuntimeError10from jinja2.exceptions import TemplateSyntaxError11from jinja2.nodes import EvalContext12from jinja2.sandbox import ImmutableSandboxedEnvironment13from jinja2.sandbox import SandboxedEnvironment14from jinja2.sandbox import unsafe4from jinja import Environment5from jinja import escape6from jinja import Markup7from jinja._compat import text_type8from jinja.exceptions import SecurityError9from jinja.exceptions import TemplateRuntimeError10from jinja.exceptions import TemplateSyntaxError11from jinja.nodes import EvalContext12from jinja.sandbox import ImmutableSandboxedEnvironment13from jinja.sandbox import SandboxedEnvironment14from jinja.sandbox import unsafe151617class PrivateStuff(object):18 def bar(self):
195 unmodified lines
modified:tests/test_tests.py+2 added-2 removed
1# -*- coding: utf-8 -*-2import pytest34from jinja2 import Environment5from jinja2 import Markup4from jinja import Environment5from jinja import Markup678class MyDict(dict):9 pass
201 unmodified lines
modified:tests/test_utils.py+9 added-9 removed
5 unmodified lines
67import pytest8from markupsafe import Markup910from jinja2._compat import range_type11from jinja2._compat import string_types12from jinja2.utils import consume13from jinja2.utils import generate_lorem_ipsum14from jinja2.utils import LRUCache15from jinja2.utils import missing16from jinja2.utils import object_type_repr17from jinja2.utils import select_autoescape18from jinja2.utils import urlize10from jinja._compat import range_type11from jinja._compat import string_types12from jinja.utils import consume13from jinja.utils import generate_lorem_ipsum14from jinja.utils import LRUCache15from jinja.utils import missing16from jinja.utils import object_type_repr17from jinja.utils import select_autoescape18from jinja.utils import urlize192021@pytest.mark.utils22@pytest.mark.lrucache
186 unmodified lines
modified:CHANGES.rst+8 added-13 removed
18 unmodified lines
19 legibility, like 12_345. :pr:`923`20- Fix a bug causing deadlocks in ``LRUCache.setdefault``. :pr:`1000`21- The ``trim`` filter takes an optional string of characters to trim.22 :pr:`828`23- A new ``jinja2.ext.debug`` extension adds a ``{% debug %}`` tag to23- A new ``jinja.ext.debug`` extension adds a ``{% debug %}`` tag to24 quickly dump the current context and available filters and tests.25 :issue:`174`, :pr:`798, 983`26- Lexing templates with large amounts of whitespace is much faster.27 :issue:`857`, :pr:`858`
335 unmodified lines
363- Added a check for default arguments followed by non-default364 arguments. This change makes ``{% macro m(x, y=1, z) %}`` a syntax365 error. The previous behavior for this code was broken anyway366 (resulting in the default value being applied to ``y``).367- Add ability to use custom subclasses of368 ``jinja2.compiler.CodeGenerator`` and ``jinja2.runtime.Context`` by369 adding two new attributes to the environment370 (``code_generator_class`` and ``context_class``) (pull request371 ``:issue:`404```).367- Add ability to use custom subclasses of ``CodeGenerator`` and368 ``Context`` by adding two new attributes to the environment369 (``code_generator_class`` and ``context_class``). :pr:`404`370- Added support for context/environment/evalctx decorator functions on371 the finalize callback of the environment.372- Escape query strings for urlencode properly. Previously slashes were373 not escaped in that place.
182 unmodified lines
556 time) by adding support for case insensitive searches.557- Fixed a bug for getattribute constant folding.558- Support for newstyle gettext translations which result in a nicer559 in-template user interface and more consistent catalogs.562 (:ref:`newstyle-gettext`)560- It's now possible to register extensions after an environment was561 created.562563
19 unmodified lines
583 compile the templates from a configured loader into a zip file or584 folder.585- The _speedups C extension now supports Python 3.586- Added support for autoescaping toggling sections and support for590 evaluation contexts (:ref:`eval-context`).587 evaluation contexts.588- Extensions have a priority now.589590591Version 2.3.1
93 unmodified lines
685 part of a visible area.686- Added ``sort`` filter that works like ``dictsort`` but for arbitrary687 sequences.688- Fixed a bug with empty statements in macros.692- Implemented a bytecode cache system. (:ref:`bytecode-cache`)689- Implemented a bytecode cache system.690- The template context is now weakref-able691- Inclusions and imports "with context" forward all variables now, not692 only the initial context.693- Added a cycle helper called ``cycler``.
11 unmodified lines
705- The subscribing of objects (looking up attributes and items) changed706 from slightly. It's now possible to give attributes or items a707 higher priority by either using dot-notation lookup or the bracket708 syntax. This also changed the AST slightly. ``Subscript`` is gone712 and was replaced with :class:`~jinja2.nodes.Getitem` and713 :class:`~jinja2.nodes.Getattr`. For more information see :ref:`the714 implementation details <notes-on-subscriptions>`.709 and was replaced with ``Getitem`` and ``Getattr``.710- Added support for preprocessing and token stream filtering for711 extensions. This would allow extensions to allow simplified gettext712 calls in template data and something similar.718- Added :meth:`jinja2.environment.TemplateStream.dump`.713- Added ``TemplateStream.dump``.714- Added missing support for implicit string literal concatenation.715 ``{{ "foo" "bar" }}`` is equivalent to ``{{ "foobar" }}``716- ``else`` is optional for conditional expressions. If not given it717 evaluates to ``false``.
13 unmodified lines
modified:MANIFEST.in+1 added
3 unmodified lines
4prune docs/_build5graft examples6graft ext7graft tests8global-exclude *.pyc
modified:README.rst+2 added-2 removed
31 unmodified lines
32Install and update using `pip`_:3334.. code-block:: text3536 $ pip install -U Jinja236 $ pip install -U Jinja3738.. _pip: https://pip.pypa.io/en/stable/quickstart/3940
17 unmodified lines
58-----5960- Website: https://palletsprojects.com/p/jinja/61- Documentation: https://jinja.palletsprojects.com/62- Releases: https://pypi.org/project/Jinja2/62- Releases: https://pypi.org/project/Jinja/63- Code: https://github.com/pallets/jinja64- Issue tracker: https://github.com/pallets/jinja/issues65- Test status: https://dev.azure.com/pallets/jinja/_build66- Official chat: https://discord.gg/t6rrQZH
modified:setup.cfg+6 added-6 removed
6 unmodified lines
7[tool:pytest]8testpaths = tests9filterwarnings =10 error11 ignore:the sets module:DeprecationWarning:jinja2.sandbox11 ignore:the sets module:DeprecationWarning:jinja.sandbox1213[coverage:run]14branch = True15source =16 jinja216 jinja17 tests1819[coverage:paths]20source =21 src/jinja222 .tox/*/lib/python*/site-packages/jinja223 .tox/*/site-packages/jinja221 src/jinja22 .tox/*/lib/python*/site-packages/jinja23 .tox/*/site-packages/jinja2425[flake8]26# B = bugbear27# E = pycodestyle errors
13 unmodified lines
41# up to 88 allowed by bugbear B95042max-line-length = 8043per-file-ignores =44 # __init__ module exports names45 src/jinja2/__init__.py: F40145 src/jinja/__init__.py: F401
modified:setup.py+4 added-5 removed
5 unmodified lines
67with io.open("README.rst", "rt", encoding="utf8") as f:8 readme = f.read()910with io.open("src/jinja2/__init__.py", "rt", encoding="utf8") as f:10with io.open("src/jinja/__init__.py", "rt", encoding="utf8") as f:11 version = re.search(r'__version__ = "(.*?)"', f.read(), re.M).group(1)1213setup(14 name="Jinja2",14 name="Jinja",15 version=version,16 url="https://palletsprojects.com/p/jinja/",17 project_urls={18 "Documentation": "https://jinja.palletsprojects.com/",19 "Code": "https://github.com/pallets/jinja",20 "Issue tracker": "https://github.com/pallets/jinja/issues",21 },22 license="BSD-3-Clause",23 author="Armin Ronacher",24 author_email="armin.ronacher@active-4.com",23 maintainer="Pallets",24 maintainer_email="contact@palletsprojects.com",25 description="A very fast and expressive template engine.",26 long_description=readme,
9 unmodified lines
36 "Programming Language :: Python :: 3",37 "Programming Language :: Python :: 3.5",38 "Programming Language :: Python :: 3.6",39 "Programming Language :: Python :: 3.7",40 "Programming Language :: Python :: 3.8",41 "Programming Language :: Python :: Implementation :: CPython",42 "Programming Language :: Python :: Implementation :: PyPy",43 "Topic :: Internet :: WWW/HTTP :: Dynamic Content",44 "Topic :: Software Development :: Libraries :: Python Modules",
4 unmodified lines
49 include_package_data=True,50 python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",51 install_requires=["MarkupSafe>=0.23"],52 extras_require={"i18n": ["Babel>=0.8"]},54 entry_points={"babel.extractors": ["jinja2 = jinja2.ext:babel_extract[i18n]"]},53 entry_points={"babel.extractors": ["jinja = jinja.ext:babel_extract[i18n]"]},54)