Skip to content
Myr

Merge pull request #1136 from pallets/drop-python2

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

Drop Python 2

authored by David Lord · committed by GitHub · parents 0c75d48, 27a5c4e · Browse files · 68 files+1066 added−2077 removed
This commit

State

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

Diff stats

68 files+1066 added−2077 removed

  • tests:+279 added−454 removed
  • other:+787 added−1623 removed

68 files+1066 added−2077 removed

modified:docs/examples/cache_extension.py+1 added-1 removed
5 unmodified lines
6 # a set of names that trigger the extension.7 tags = {"cache"}89 def __init__(self, environment):10 super(FragmentCacheExtension, self).__init__(environment)10 super().__init__(environment)1112 # add the defaults to the environment13 environment.extend(fragment_cache_prefix="", fragment_cache=None)14
40 unmodified lines
modified:docs/examples/inline_gettext_extension.py+1 added-2 removed
1# -*- coding: utf-8 -*-1import re23from jinja2.exceptions import TemplateSyntaxError4from jinja2.ext import Extension
47 unmodified lines
52 paren_stack = 153 else:54 if gtok == "(" or paren_stack > 1:55 yield Token(lineno, "data", gtok)57 paren_stack += gtok == ")" and -1 or 156 paren_stack += -1 if gtok == ")" else 157 if not paren_stack:58 yield Token(lineno, "block_begin", None)59 yield Token(lineno, "name", "endtrans")60 yield Token(lineno, "block_end", None)
12 unmodified lines
modified:docs/api.rst+32 added-96 removed
58 unmodified lines
59 for security reasons. As such you are encouraged to explicitly60 configure autoescaping now instead of relying on the default.616263Unicode64-------6566Jinja is using Unicode internally which means that you have to pass Unicode67objects to the render function or bytestrings that only consist of ASCII68characters. Additionally newlines are normalized to one end of line69sequence which is per default UNIX style (``\n``).7071Python 2.x supports two ways of representing string objects. One is the72`str` type and the other is the `unicode` type, both of which extend a type73called `basestring`. Unfortunately the default is `str` which should not74be used to store text based information unless only ASCII characters are75used. With Python 2.6 it is possible to make `unicode` the default on a per76module level and with Python 3 it will be the default.7778To explicitly use a Unicode string you have to prefix the string literal79with a `u`: ``u'Hänsel und Gretel sagen Hallo'``. That way Python will80store the string as Unicode by decoding the string with the character81encoding from the current Python module. If no encoding is specified this82defaults to 'ASCII' which means that you can't use any non ASCII identifier.8384To set a better module encoding add the following comment to the first or85second line of the Python module using the Unicode literal::8687 # -*- coding: utf-8 -*-8889We recommend utf-8 as Encoding for Python modules and templates as it's90possible to represent every Unicode character in utf-8 and because it's91backwards compatible to ASCII. For Jinja the default encoding of templates92is assumed to be utf-8.9394It is not possible to use Jinja to process non-Unicode data. The reason95for this is that Jinja uses Unicode already on the language level. For96example Jinja treats the non-breaking space as valid whitespace inside97expressions which requires knowledge of the encoding or operating on an98Unicode string.99100For more details about Unicode in Python have a look at the excellent101`Unicode documentation`_.102103Another important thing is how Jinja is handling string literals in104templates. A naive implementation would be using Unicode strings for105all string literals but it turned out in the past that this is problematic106as some libraries are typechecking against `str` explicitly. For example107`datetime.strftime` does not accept Unicode arguments. To not break it108completely Jinja is returning `str` for strings that fit into ASCII and109for everything else `unicode`:110111>>> m = Template(u"{% set a, b = 'foo', 'föö' %}").module112>>> m.a113'foo'114>>> m.b115u'f\xf6\xf6'116117118.. _Unicode documentation: https://docs.python.org/3/howto/unicode.html11963High Level API64--------------6566The high-level API is the API you will use in the application to load and
176 unmodified lines
243Notes on Identifiers244--------------------245246Jinja uses Python naming rules. Valid identifiers can be any combination304of Unicode characters accepted by Python.247of characters accepted by Python.248249Filters and tests are looked up in separate namespaces and have slightly250modified identifier syntax. Filters and tests may contain dots to group251filters and tests by topic. For example it's perfectly valid to add a309function into the filter dict and call it `to.unicode`. The regular252function into the filter dict and call it `to.str`. The regular253expression for filter and test identifiers is254``[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*)*```.255256
13 unmodified lines
270.. autoclass:: jinja2.Undefined()271272 .. attribute:: _undefined_hint273331 Either `None` or an unicode string with the error message for332 the undefined object.274 Either `None` or a string with the error message for the275 undefined object.276277 .. attribute:: _undefined_obj278279 Either `None` or the owner object that caused the undefined object
29 unmodified lines
309Undefined objects are created by calling :attr:`undefined`.310311.. admonition:: Implementation312370 :class:`Undefined` objects are implemented by overriding the special371 `__underscore__` methods. For example the default :class:`Undefined`372 class implements `__unicode__` in a way that it returns an empty373 string, however `__int__` and others still fail with an exception. To374 allow conversion to int by returning ``0`` you can implement your own::313 :class:`Undefined` is implemented by overriding the special314 ``__underscore__`` methods. For example the default315 :class:`Undefined` class implements ``__str__`` to returns an empty316 string, while ``__int__`` and others fail with an exception. To317 allow conversion to int by returning ``0`` you can implement your318 own subclass.319320 .. code-block:: python321322 class NullUndefined(Undefined):323 def __int__(self):324 return 0325326 def __float__(self):327 return 0.0328382 To disallow a method, just override it and raise383 :attr:`~Undefined._undefined_exception`. Because this is a very common384 idiom in undefined objects there is the helper method385 :meth:`~Undefined._fail_with_undefined_error` that does the error raising386 automatically. Here a class that works like the regular :class:`Undefined`387 but chokes on iteration::329 To disallow a method, override it and raise330 :attr:`~Undefined._undefined_exception`. Because this is very331 common there is the helper method332 :meth:`~Undefined._fail_with_undefined_error` that raises the error333 with the correct information. Here's a class that works like the334 regular :class:`Undefined` but fails on iteration::335336 class NonIterableUndefined(Undefined):390 __iter__ = Undefined._fail_with_undefined_error337 def __iter__(self):338 self._fail_with_undefined_error()339340341The Context342-----------
179 unmodified lines
522Example::523524 env.policies['urlize.rel'] = 'nofollow noopener'525578``compiler.ascii_str``:579 This boolean controls on Python 2 if Jinja should store ASCII only580 literals as bytestring instead of unicode strings. This used to be581 always enabled for Jinja versions below 2.9 and now can be changed.582 Traditionally it was done this way since some APIs in Python 2 failed583 badly for unicode strings (for instance the datetime strftime API).584 Now however sometimes the inverse is true (for instance str.format).585 If this is set to False then all strings are stored as unicode586 internally.587526``truncate.leeway``:527 Configures the leeway default for the `truncate` filter. Leeway as528 introduced in 2.9 but to restore compatibility with older templates529 it can be configured to `0` to get the old behavior back. The default
83 unmodified lines
613.. autoexception:: jinja2.TemplateSyntaxError614615 .. attribute:: message616679 The error message as utf-8 bytestring.617 The error message.618619 .. attribute:: lineno620683 The line number where the error occurred621 The line number where the error occurred.622623 .. attribute:: name624687 The load name for the template as unicode string.625 The load name for the template.626627 .. attribute:: filename628691 The filename that loaded the template as bytestring in the encoding692 of the file system (most likely utf-8 or mbcs on Windows systems).629 The filename that loaded the template in the encoding of the630 file system (most likely utf-8, or mbcs on Windows systems).631694 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.697632.. autoexception:: jinja2.TemplateRuntimeError633634.. autoexception:: jinja2.TemplateAssertionError635
38 unmodified lines
674675 import re676 from jinja2 import evalcontextfilter, Markup, escape677744 _paragraph_re = re.compile(r'(?:\r\n|\r(?!\n)|\n){2,}')678 _paragraph_re = re.compile(r"(?:\r\n|\r(?!\n)|\n){2,}")679680 @evalcontextfilter681 def nl2br(eval_ctx, value):748 result = u'\n\n'.join(u'<p>%s</p>' % p.replace('\n', Markup('<br>\n'))749 for p in _paragraph_re.split(escape(value)))682 result = "\n\n".join(683 f"<p>{p.replace('\n', Markup('<br>\n'))}</p>"684 for p in _paragraph_re.split(escape(value))685 )686 if eval_ctx.autoescape:687 result = Markup(result)688 return result689
139 unmodified lines
829 This is the low level render function. It's passed a :class:`Context`830 that has to be created by :meth:`new_context` of the same template or831 a compatible template. This render function is generated by the832 compiler from the template code and returns a generator that yields897 unicode strings.833 strings.834835 If an exception in the template code happens the template engine will836 not rewrite the exception but pass through the original one. As a837 matter of fact this function should only be called from within a
32 unmodified lines
modified:docs/conf.py+2 added-4 removed
40 unmodified lines
41singlehtml_sidebars = {"index": ["project.html", "localtoc.html"]}42html_static_path = ["_static"]43html_favicon = "_static/jinja-logo-sidebar.png"44html_logo = "_static/jinja-logo-sidebar.png"45html_title = "Jinja Documentation ({})".format(version)45html_title = f"Jinja Documentation ({version})"46html_show_sourcelink = False4748# LaTeX ----------------------------------------------------------------4950latex_documents = [51 (master_doc, "Jinja-{}.tex".format(version), html_title, author, "manual")52]50latex_documents = [(master_doc, f"Jinja-{version}.tex", html_title, author, "manual")]
modified:docs/extensions.rst+4 added-6 removed
42 unmodified lines
4344.. method:: jinja2.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).47 ``translations`` object must implement ``gettext`` and ``ngettext``.48 :class:`gettext.NullTranslations`, :class:`gettext.GNUTranslations`,49 and `Babel`_\s ``Translations`` are supported.5051 .. versionchanged:: 2.5 Added new-style gettext support.
9 unmodified lines
61.. method:: jinja2.Environment.install_gettext_callables(gettext, ngettext, newstyle=False)6263 Install the given ``gettext`` and ``ngettext`` callables into the64 environment. They should behave exactly like66 :func:`gettext.gettext` and :func:`gettext.ngettext` (or67 ``ugettext`` and ``ungettext`` for Python 2).65 :func:`gettext.gettext` and :func:`gettext.ngettext`.6667 If ``newstyle`` is activated, the callables are wrapped to work like68 newstyle callables. See :ref:`newstyle-gettext` for more information.69
13 unmodified lines
83 - ``lineno`` is the number of the line on which the string was84 found.85 - ``function`` is the name of the ``gettext`` function used (if86 the string was extracted from embedded Python code).89 - ``message`` is the string itself (``unicode`` on Python 2), or a90 tuple of strings for functions with multiple arguments.87 - ``message`` is the string itself, or a tuple of strings for88 functions with multiple arguments.8990 If `Babel`_ is installed, see :ref:`babel-integration` to extract91 the strings.92
310 unmodified lines
modified:docs/faq.rst+10 added-30 removed
123 unmodified lines
124instead that one can assign to a variable by using set::125126 {% set comments = get_latest_comments() %}127128My tracebacks look weird. What's happening?129--------------------------------------------128My tracebacks look weird. What's happening?129-------------------------------------------130131If the debugsupport module is not compiled and you are using a Python132installation without ctypes (Python 2.4 without ctypes, Jython or Google's133AppEngine) Jinja is unable to provide correct debugging information and134the traceback may be incomplete. There is currently no good workaround135for Jython or the AppEngine as ctypes is unavailable there and it's not136possible to use the debugsupport extension.131Jinja can rewrite tracebacks so they show the template lines numbers and132source rather than the underlying compiled code, but this requires133special Python support. CPython <3.7 requires ``ctypes``, and PyPy134requires transparent proxy support.135138If you are working in the Google AppEngine development server you can139whitelist the ctypes module to restore the tracebacks. This however won't140work in production environments::136If you are using Google App Engine, ``ctypes`` is not available. You can137make it available in development, but not in production.138139.. code-block:: python140141 import os142 if os.environ.get('SERVER_SOFTWARE', '').startswith('Dev'):143 from google.appengine.tools.devappserver2.python import sandbox144 sandbox._WHITE_LIST_C_MODULES += ['_ctypes', 'gestalt']145146Credit for this snippet goes to `Thomas Johansson147<https://stackoverflow.com/questions/3086091/debug-jinja2-in-google-app-engine/3694434#3694434>`_148150Why is there no Python 2.3/2.4/2.5/2.6/3.1/3.2/3.3 support?151-----------------------------------------------------------152153Python 2.3 is missing a lot of features that are used heavily in Jinja. This154decision was made as with the upcoming Python 2.6 and 3.0 versions it becomes155harder to maintain the code for older Python versions. If you really need156Python 2.3 support you either have to use Jinja 1 or other templating157engines that still support 2.3.158159Python 2.4/2.5/3.1/3.2 support was removed when we switched to supporting160Python 2 and 3 by the same sourcecode (without using 2to3). It was required to161drop support because only Python 2.6/2.7 and >=3.3 support byte and unicode162literals in a way compatible to each other version. If you really need support163for older Python 2 (or 3) versions, you can just use Jinja 2.6.164165Python 2.6/3.3 support was dropped because it got dropped in various upstream166projects (such as wheel or pytest), which would make it difficult to continue167supporting it. Jinja 2.10 was the last version supporting Python 2.6/3.3.168149My Macros are overridden by something150-------------------------------------151152In some situations the Jinja scoping appears arbitrary:
23 unmodified lines
modified:docs/index.rst+3 added-26 removed
5 unmodified lines
6.. image:: _static/jinja-logo.png7 :align: center8 :target: https://palletsprojects.com/p/jinja/910Jinja is a modern and designer-friendly templating language for Python,11modelled after Django's templates. It is fast, widely used and secure12with the optional sandboxed template execution environment:10Jinja is a fast, expressive, extensible templating engine. Special11placeholders in the template allow writing code similar to Python12syntax. Then the template is passed data to render the final document.1314.. sourcecode:: html+jinja1516 <title>{% block title %}{% endblock %}</title>17 <ul>18 {% for user in users %}19 <li><a href="{{ user.url }}">{{ user.username }}</a></li>20 {% endfor %}21 </ul>2223Features:2425- sandboxed execution26- powerful automatic HTML escaping system for XSS prevention27- template inheritance28- compiles down to the optimal python code just in time29- optional ahead-of-time template compilation30- easy to debug. Line numbers of exceptions directly point to31 the correct line in the template.32- configurable syntax3314.. toctree::15 :maxdepth: 216 :caption: Contents:17
7 unmodified lines
25 switching26 tricks27 faq28 changelog4950* :ref:`genindex`51* :ref:`search`
modified:docs/intro.rst+37 added-56 removed
1Introduction2============34This is the documentation for the Jinja general purpose templating language.5Jinja is a library for Python that is designed to be flexible, fast and secure.4Jinja is a fast, expressive, extensible templating engine. Special5placeholders in the template allow writing code similar to Python6syntax. Then the template is passed data to render the final document.77If you have any exposure to other text-based template languages, such as Smarty or8Django, 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.8It includes:912Prerequisites13-------------10- Template inheritance and inclusion.11- Define and import macros within templates.12- HTML templates can use autoescaping to prevent XSS from untrusted13 user input.14- A sandboxed environment can safely render untrusted templates.15- AsyncIO support for generating templates and calling async16 functions.17- I18N support with Babel.18- Templates are compiled to optimized Python code just-in-time and19 cached, or can be compiled ahead-of-time.20- Exceptions point to the correct line in templates to make debugging21 easier.22- Extensible filters, tests, functions, and even syntax.2315Jinja 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.24Jinja's philosophy is that while application logic belongs in Python if25possible, it shouldn't make the template designer's job difficult by26restricting functionality too much.2720If you wish to use the :class:`~jinja2.PackageLoader` class, you will also21need `setuptools`_ or `distribute`_ installed at runtime.2829Installation30------------3126You can install the most recent Jinja version using `pip`_::32We recommend using the latest version of Python. Jinja supports Python333.6 and newer. We also recommend using a `virtual environment`_ in order34to isolate your project dependencies from other projects and the system.3528 pip install Jinja236.. _virtual environment: https://packaging.python.org/tutorials/installing-packages/#creating-virtual-environments3730This will install Jinja in your Python installation's site-packages directory.38Install the most recent Jinja version using pip:3932Installing the development version33~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~40.. code-block:: text41351. Install `git`_362. ``git clone git://github.com/pallets/jinja.git``373. ``cd jinja2``384. ``ln -s jinja2 /usr/lib/python2.X/site-packages``42 $ pip install Jinja24340As 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.4444.. _distribute: https://pypi.org/project/distribute/45.. _setuptools: https://pypi.org/project/setuptools/46.. _pip: https://pypi.org/project/pip/47.. _git: https://git-scm.com/45Dependencies46~~~~~~~~~~~~4748These will be installed automatically when installing Jinja.4950MarkupSafe Dependency51~~~~~~~~~~~~~~~~~~~~~50- `MarkupSafe`_ escapes untrusted input when rendering templates to51 avoid injection attacks.5253As of version 2.7 Jinja depends on the `MarkupSafe`_ module. If you install54Jinja via ``pip`` it will be installed automatically for you.5553.. _MarkupSafe: https://markupsafe.palletsprojects.com/5458Basic API Usage59---------------5561This section gives you a brief introduction to the Python API for Jinja62templates.56Optional Dependencies57~~~~~~~~~~~~~~~~~~~~~5864The most basic way to create a template and render it is through65:class:`~jinja2.Template`. This however is not the recommended way to66work with it if your templates are not loaded from strings but the file67system or another data source:59These distributions will not be installed automatically.6069>>> from jinja2 import Template70>>> template = Template('Hello {{ name }}!')71>>> template.render(name='John Doe')72u'Hello John Doe!'61- `Babel`_ provides translation support in templates.6274By creating an instance of :class:`~jinja2.Template` you get back a new template75object that provides a method called :meth:`~jinja2.Template.render` which when76called with a dict or keyword arguments expands the template. The dict77or keywords arguments passed to the template are the so-called "context"78of the template.7980What you can see here is that Jinja is using unicode internally and the81return value is an unicode string. So make sure that your application is82indeed using unicode internally.63.. _Babel: http://babel.pocoo.org/
modified:docs/switching.rst+6 added-6 removed
30 unmodified lines
31 provides a :class:`Template` class that can be used to do the same, but32 with optional additional configuration.3334Automatic unicode conversion35 Jinja 1 performed automatic conversion of bytestrings in a given encoding36 into unicode objects. This conversion is no longer implemented as it37 was inconsistent as most libraries are using the regular Python ASCII38 bytestring to Unicode conversion. An application powered by Jinja 239 *has to* use unicode internally everywhere or make sure that Jinja 2 only40 gets unicode strings passed.35 Jinja 1 performed automatic conversion of bytes in a given encoding36 into unicode objects. This conversion is no longer implemented as it37 was inconsistent as most libraries are using the regular Python38 ASCII bytes to Unicode conversion. An application powered by Jinja 239 *has to* use unicode internally everywhere or make sure that Jinja 240 only gets unicode strings passed.4142i18n43 Jinja 1 used custom translators for internationalization. i18n is now44 available as Jinja 2 extension and uses a simpler, more gettext friendly
182 unmodified lines
modified:docs/templates.rst+2 added-3 removed
600 unmodified lines
601602Jinja functions (macros, `super`, `self.BLOCKNAME`) always return template603data that is marked as safe.604605String literals in templates with automatic escaping are considered unsafe606because native Python strings (``str``, ``unicode``, ``basestring``) are not607`MarkupSafe.Markup` strings with an ``__html__`` attribute.605String literals in templates with automatic escaping are considered606unsafe because native Python strings are not safe.607608.. _list-of-control-structures:609610List of Control Structures
1209 unmodified lines
modified:examples/basic/cycle.py-2 removed
1from __future__ import print_function21from jinja2 import Environment23env = Environment(4 line_statement_prefix="#", variable_start_string="${", variable_end_string="}"
12 unmodified lines
modified:examples/basic/debugger.py-2 removed
1from __future__ import print_function21from jinja2 import Environment2from jinja2.loaders import FileSystemLoader34env = Environment(loader=FileSystemLoader("templates"))
2 unmodified lines
modified:examples/basic/inheritance.py-2 removed
1from __future__ import print_function21from jinja2 import Environment2from jinja2.loaders import DictLoader34env = Environment(
9 unmodified lines
modified:examples/basic/test_filter_and_linestatements.py-2 removed
1from __future__ import print_function21from jinja2 import Environment23env = Environment(4 line_statement_prefix="%", variable_start_string="${", variable_end_string="}"
23 unmodified lines
modified:examples/basic/test_loop_filter.py-2 removed
1from __future__ import print_function21from jinja2 import Environment23tmpl = Environment().from_string(4 """\
9 unmodified lines
modified:examples/basic/test.py+3 added-5 removed
1from __future__ import print_function21from jinja2 import Environment2from jinja2.loaders import DictLoader34env = Environment(5 loader=DictLoader(6 {9 "child.html": u"""\7 "child.html": """\8{% extends master_layout or 'master.html' %}9{% include helpers = 'helpers.html' %}10{% macro get_the_answer() %}42{% endmacro %}11{% title = 'Hello World' %}
1 unmodified line
13 {{ get_the_answer() }}14 {{ helpers.conspirate() }}15{% endblock %}16""",19 "master.html": u"""\17 "master.html": """\18<!doctype html>19<title>{{ title }}</title>20{% block body %}{% endblock %}21""",24 "helpers.html": u"""\22 "helpers.html": """\23{% macro conspirate() %}23{% endmacro %}24""",25 }26 )
3 unmodified lines
modified:examples/basic/translate.py+1 added-3 removed
1from __future__ import print_function21from jinja2 import Environment23env = Environment(extensions=["jinja2.ext.i18n"])4env.globals["gettext"] = {"Hello %(user)s!": "Hallo %(user)s!"}.__getitem__5env.globals["ngettext"] = lambda s, p, n: {6 "%(count)s user": "%(count)d Benutzer",7 "%(count)s users": "%(count)d Benutzer",10}[n == 1 and s or p]8}[s if n == 1 else p]9print(10 env.from_string(11 """\12{% trans %}Hello {{ user }}!{% endtrans %}
6 unmodified lines
modified:scripts/generate_identifier_pattern.py+2 added-6 removed
1#!/usr/bin/env python31import itertools2import os3import re4import sys57if sys.version_info[0] < 3:8 raise RuntimeError("This needs to run on Python 3.")6107def get_characters():8 """Find every Unicode character that is valid in a Python `identifier`_ but9 is not matched by the regex ``\\w`` group.10
36 unmodified lines
47 elif ord(b) - ord(a) == 1: # two chars, range is redundant48 out.append(a)49 out.append(b)50 else:55 out.append("{}-{}".format(a, b))51 out.append(f"{a}-{b}")5253 return "".join(out)5455
9 unmodified lines
65 with open(filename, "w", encoding="utf8") as f:66 f.write("import re\n\n")67 f.write("# generated by scripts/generate_identifier_pattern.py\n")68 f.write("pattern = re.compile(\n")73 f.write(' r"[\\w{}]+" # noqa: B950\n'.format(pattern))69 f.write(f' r"[\\w{pattern}]+" # noqa: B950\n')70 f.write(")\n")717273if __name__ == "__main__":
1 unmodified line
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
modified:src/jinja2/asyncfilters.py+2 added-3 removed
82 unmodified lines
83 ]848586@asyncfiltervariant(filters.do_join)87async def do_join(eval_ctx, value, d=u"", attribute=None):87async def do_join(eval_ctx, value, d="", attribute=None):88 return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)899091@asyncfiltervariant(filters.do_list)
53 unmodified lines
145 "first": do_first,146 "groupby": do_groupby,147 "join": do_join,148 "list": do_list,149 # we intentionally do not support do_last because that would be150 # ridiculous149 # we intentionally do not support do_last because it may not be safe in async150 "reject": do_reject,151 "rejectattr": do_rejectattr,152 "map": do_map,153 "select": do_select,
4 unmodified lines
modified:src/jinja2/asyncsupport.py+1 added-16 removed
1# -*- coding: utf-8 -*-2"""The code for async support. Importing this patches Jinja on supported1"""The code for async support. Importing this patches Jinja."""3Python versions.4"""2import asyncio3import inspect4from functools import update_wrapper5
239 unmodified lines
245 self._current = rv246 return rv, self247248252async def make_async_loop_context(iterable, undefined, recurse=None, depth0=0):253 import warnings254255 warnings.warn(256 "This template must be recompiled with at least Jinja 2.11, or"257 " it will fail in 3.0.",258 DeprecationWarning,259 stacklevel=2,260 )261 return AsyncLoopContext(iterable, undefined, recurse, depth0)262263249patch_all()
modified:src/jinja2/bccache.py+14 added-19 removed
1# -*- coding: utf-8 -*-1"""The optional bytecode cache system. This is useful if you have very2complex template situations and the compilation of all those templates3slows down your application too much.4
1 unmodified line
6are initialized on the first request.7"""8import errno9import fnmatch10import marshal11import os12import pickle13import stat14import sys15import tempfile16from hashlib import sha116from os import listdir17from os import path17from io import BytesIO1819from ._compat import BytesIO20from ._compat import marshal_dump21from ._compat import marshal_load22from ._compat import pickle23from ._compat import text_type19from .utils import open_if_exists2026bc_version = 421bc_version = 522# Magic bytes to identify Jinja bytecode cache files. Contains the23# Python major and minor version to avoid loading incompatible bytecode24# if a project upgrades its Python version.25bc_magic = (
2 unmodified lines
28 + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1], 2)29)303137class Bucket(object):32class Bucket:33 """Buckets are used to store the bytecode for one template. It's created34 and initialized by the bytecode cache and passed to the loading functions.3536 The buckets get an internal checksum from the cache assigned and use this
24 unmodified lines
61 self.reset()62 return63 # if marshal_load fails then we need to reload64 try:70 self.code = marshal_load(f)65 self.code = marshal.load(f)66 except (EOFError, ValueError, TypeError):67 self.reset()68 return69
2 unmodified lines
72 if self.code is None:73 raise TypeError("can't write empty bucket")74 f.write(bc_magic)75 pickle.dump(self.checksum, f, 2)81 marshal_dump(self.code, f)76 marshal.dump(self.code, f)7778 def bytecode_from_string(self, string):79 """Load bytecode from a string."""80 self.load_bytecode(BytesIO(string))
4 unmodified lines
85 self.write_bytecode(out)86 return out.getvalue()878894class BytecodeCache(object):89class BytecodeCache:90 """To implement your own bytecode cache you have to subclass this class91 and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of92 these methods are passed a :class:`~jinja2.bccache.Bucket`.93
45 unmodified lines
139 """Returns the unique hash key for this template name."""140 hash = sha1(name.encode("utf-8"))141 if filename is not None:142 filename = "|" + filename148 if isinstance(filename, text_type):143 if isinstance(filename, str):144 filename = filename.encode("utf-8")145 hash.update(filename)146 return hash.hexdigest()147
55 unmodified lines
203 return tmpdir204 if not hasattr(os, "getuid"):205 _unsafe_dir()206212 dirname = "_jinja2-cache-%d" % os.getuid()207 dirname = f"_jinja2-cache-{os.getuid()}"208 actual_dir = os.path.join(tmpdir, dirname)209210 try:211 os.mkdir(actual_dir, stat.S_IRWXU)
23 unmodified lines
235236 return actual_dir237238 def _get_cache_filename(self, bucket):244 return path.join(self.directory, self.pattern % bucket.key)239 return os.path.join(self.directory, self.pattern % (bucket.key,))240241 def load_bytecode(self, bucket):242 f = open_if_exists(self._get_cache_filename(bucket), "rb")243 if f is not None:
14 unmodified lines
258 # write access on the file system and the function does not exist259 # normally.260 from os import remove261267 files = fnmatch.filter(listdir(self.directory), self.pattern % "*")262 files = fnmatch.filter(os.listdir(self.directory), self.pattern % ("*",))263 for filename in files:264 try:270 remove(path.join(self.directory, filename))265 remove(os.path.join(self.directory, filename))266 except OSError:267 pass268269
8 unmodified lines
278 - `cachelib <https://github.com/pallets/cachelib>`_279 - `python-memcached <https://pypi.org/project/python-memcached/>`_280281 (Unfortunately the django cache interface is not compatible because it287 does not support storing binary data, only unicode. You can however pass282 does not support storing binary data, only text. You can however pass283 the underlying cache client to the bytecode cache which is available284 as `django.core.cache.cache._client`.)285286 The minimal interface for the client passed to the constructor is this:
59 unmodified lines
modified:src/jinja2/compiler.py+176 added-265 removed
1# -*- coding: utf-8 -*-1"""Compiles nodes from the parser into Python code."""2from collections import namedtuple3from functools import update_wrapper4from io import StringIO5from itertools import chain6from keyword import iskeyword as is_python_keyword78from markupsafe import escape9from markupsafe import Markup1011from . import nodes12from ._compat import imap13from ._compat import iteritems14from ._compat import izip15from ._compat import NativeStringIO16from ._compat import range_type17from ._compat import string_types18from ._compat import text_type12from .exceptions import TemplateAssertionError13from .idtracking import Symbols14from .idtracking import VAR_LOAD_ALIAS15from .idtracking import VAR_LOAD_PARAMETER
14 unmodified lines
30 "in": "in",31 "notin": "not in",32}3341# what method to iterate over items do we want to use for dict iteration42# in generated code? on 2.x let's go with iteritems, on 3.x with items43if hasattr(dict, "iteritems"):44 dict_item_iter = "iteritems"45else:46 dict_item_iter = "items"3448code_features = ["division"]4950# does this python version support generator stops? (PEP 0479)51try:52 exec("from __future__ import generator_stop")53 code_features.append("generator_stop")54except SyntaxError:55 pass5657# does this python version support yield from?58try:59 exec("def f(): yield from x()")60except SyntaxError:61 supports_yield_from = False62else:63 supports_yield_from = True646535def optimizeconst(f):36 def new_func(self, node, frame, **kwargs):37 # Only optimize if the frame is not volatile38 if self.optimized and not frame.eval_ctx.volatile:
22 unmodified lines
61def has_safe_repr(value):62 """Does the node have a safe representation?"""63 if value is None or value is NotImplemented or value is Ellipsis:64 return True96 if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:6566 if type(value) in {bool, int, float, complex, range, str, Markup}:67 return True98 if type(value) in (tuple, list, set, frozenset):99 for item in value:100 if not has_safe_repr(item):101 return False102 return True103 elif type(value) is dict:104 for key, value in iteritems(value):105 if not has_safe_repr(key):106 return False107 if not has_safe_repr(value):108 return False109 return True6869 if type(value) in {tuple, list, set, frozenset}:70 return all(has_safe_repr(v) for v in value)7172 if type(value) is dict:73 return all(has_safe_repr(k) and has_safe_repr(v) for k, v in value.items())7475 return False767778def find_undeclared(nodes, names):
8 unmodified lines
87 pass88 return visitor.undeclared8990126class MacroRef(object):91class MacroRef:92 def __init__(self, node):93 self.node = node94 self.accesses_caller = False95 self.accesses_kwargs = False96 self.accesses_varargs = False9798134class Frame(object):99class Frame:100 """Holds compile time information for us."""101102 def __init__(self, eval_ctx, parent=None, level=None):103 self.eval_ctx = eval_ctx139 self.symbols = Symbols(parent and parent.symbols or None, level=level)104 self.symbols = Symbols(parent.symbols if parent else None, level=level)105106 # a toplevel frame is the root + soft frames such as if conditions.107 self.toplevel = False108
12 unmodified lines
121 # buffer.122 self.buffer = None123124 # the name of the block we're in, otherwise None.160 self.block = parent and parent.block or None125 self.block = parent.block if parent else None126127 # the parent of this frame128 self.parent = parent129
83 unmodified lines
213 def __init__(214 self, environment, name, filename, stream=None, defer_init=False, optimized=True215 ):216 if stream is None:252 stream = NativeStringIO()217 stream = StringIO()218 self.environment = environment219 self.name = name220 self.filename = filename221 self.stream = stream
62 unmodified lines
284285 def temporary_identifier(self):286 """Get a new unique identifier."""287 self._last_identifier += 1323 return "t_%d" % self._last_identifier288 return f"t_{self._last_identifier}"289290 def buffer(self, frame):291 """Enable buffering for the frame from that point onwards."""292 frame.buffer = self.temporary_identifier()328 self.writeline("%s = []" % frame.buffer)293 self.writeline(f"{frame.buffer} = []")294295 def return_buffer_contents(self, frame, force_unescaped=False):296 """Return the buffer contents of the frame."""297 if not force_unescaped:298 if frame.eval_ctx.volatile:299 self.writeline("if context.eval_ctx.autoescape:")300 self.indent()336 self.writeline("return Markup(concat(%s))" % frame.buffer)301 self.writeline(f"return Markup(concat({frame.buffer}))")302 self.outdent()303 self.writeline("else:")304 self.indent()340 self.writeline("return concat(%s)" % frame.buffer)305 self.writeline(f"return concat({frame.buffer})")306 self.outdent()307 return308 elif frame.eval_ctx.autoescape:344 self.writeline("return Markup(concat(%s))" % frame.buffer)309 self.writeline(f"return Markup(concat({frame.buffer}))")310 return346 self.writeline("return concat(%s)" % frame.buffer)311 self.writeline(f"return concat({frame.buffer})")312313 def indent(self):314 """Indent by one."""315 self._indentation += 1
6 unmodified lines
322 """Yield or write into the frame buffer."""323 if frame.buffer is None:324 self.writeline("yield ", node)325 else:361 self.writeline("%s.append(" % frame.buffer, node)326 self.writeline(f"{frame.buffer}.append(", node)327328 def end_write(self, frame):329 """End the writing process started by `start_write`."""330 if frame.buffer is not None:
65 unmodified lines
396 for kwarg in node.kwargs:397 self.write(", ")398 self.visit(kwarg, frame)399 if extra_kwargs is not None:435 for key, value in iteritems(extra_kwargs):436 self.write(", %s=%s" % (key, value))400 for key, value in extra_kwargs.items():401 self.write(f", {key}={value}")402 if node.dyn_args:403 self.write(", *")404 self.visit(node.dyn_args, frame)405
2 unmodified lines
408 self.write(", **dict({")409 else:410 self.write(", **{")411 for kwarg in node.kwargs:447 self.write("%r: " % kwarg.key)412 self.write(f"{kwarg.key!r}: ")413 self.visit(kwarg.value, frame)414 self.write(", ")415 if extra_kwargs is not None:451 for key, value in iteritems(extra_kwargs):452 self.write("%r: %s, " % (key, value))416 for key, value in extra_kwargs.items():417 self.write(f"{key!r}: {value}, ")418 if node.dyn_kwargs is not None:419 self.write("}, **")420 self.visit(node.dyn_kwargs, frame)421 self.write(")")
13 unmodified lines
435 mapping = getattr(self, dependency)436 for name in getattr(visitor, dependency):437 if name not in mapping:438 mapping[name] = self.temporary_identifier()474 self.writeline(475 "%s = environment.%s[%r]" % (mapping[name], dependency, name)476 )439 self.writeline(f"{mapping[name]} = environment.{dependency}[{name!r}]")440441 def enter_frame(self, frame):442 undefs = []480 for target, (action, param) in iteritems(frame.symbols.loads):443 for target, (action, param) in frame.symbols.loads.items():444 if action == VAR_LOAD_PARAMETER:445 pass446 elif action == VAR_LOAD_RESOLVE:484 self.writeline("%s = %s(%r)" % (target, self.get_resolve_func(), param))447 self.writeline(f"{target} = {self.get_resolve_func()}({param!r})")448 elif action == VAR_LOAD_ALIAS:486 self.writeline("%s = %s" % (target, param))449 self.writeline(f"{target} = {param}")450 elif action == VAR_LOAD_UNDEFINED:451 undefs.append(target)452 else:453 raise NotImplementedError("unknown load instruction")454 if undefs:492 self.writeline("%s = missing" % " = ".join(undefs))455 self.writeline(f"{' = '.join(undefs)} = missing")456457 def leave_frame(self, frame, with_python_scope=False):458 if not with_python_scope:459 undefs = []497 for target, _ in iteritems(frame.symbols.loads):460 for target in frame.symbols.loads:461 undefs.append(target)462 if undefs:500 self.writeline("%s = missing" % " = ".join(undefs))463 self.writeline(f"{' = '.join(undefs)} = missing")464465 def func(self, name):466 if self.environment.is_async:504 return "async def %s" % name505 return "def %s" % name467 return f"async def {name}"468 return f"def {name}"469470 def macro_body(self, node, frame):471 """Dump the function def of a macro or call block."""472 frame = frame.inner()
41 unmodified lines
514515 # macros are delayed, they never require output checks516 frame.require_output_check = False517 frame.symbols.analyze_node(node)555 self.writeline("%s(%s):" % (self.func("macro"), ", ".join(args)), node)518 self.writeline(f"{self.func('macro')}({', '.join(args)}):", node)519 self.indent()520521 self.buffer(frame)522 self.enter_frame(frame)523524 self.push_parameter_definitions(frame)525 for idx, arg in enumerate(node.args):526 ref = frame.symbols.ref(arg.name)564 self.writeline("if %s is missing:" % ref)527 self.writeline(f"if {ref} is missing:")528 self.indent()529 try:530 default = node.defaults[idx - len(node.args)]531 except IndexError:532 self.writeline(570 "%s = undefined(%r, name=%r)"571 % (ref, "parameter %r was not provided" % arg.name, arg.name)533 f'{ref} = undefined("parameter {arg.name!r} was not provided",'534 f" name={arg.name!r})"535 )536 else:574 self.writeline("%s = " % ref)537 self.writeline(f"{ref} = ")538 self.visit(default, frame)539 self.mark_parameter_stored(ref)540 self.outdent()541 self.pop_parameter_definitions()
11 unmodified lines
553 name = getattr(macro_ref.node, "name", None)554 if len(macro_ref.node.args) == 1:555 arg_tuple += ","556 self.write(594 "Macro(environment, macro, %r, (%s), %r, %r, %r, "595 "context.eval_ctx.autoescape)"596 % (597 name,598 arg_tuple,599 macro_ref.accesses_kwargs,600 macro_ref.accesses_varargs,601 macro_ref.accesses_caller,602 )557 f"Macro(environment, macro, {name!r}, ({arg_tuple}),"558 f" {macro_ref.accesses_kwargs!r}, {macro_ref.accesses_varargs!r},"559 f" {macro_ref.accesses_caller!r}, context.eval_ctx.autoescape)"560 )561562 def position(self, node):563 """Return a human readable position for the node."""607 rv = "line %d" % node.lineno564 rv = f"line {node.lineno}"565 if self.name is not None:609 rv += " in " + repr(self.name)566 rv = f"{rv} in {self.name!r}"567 return rv568569 def dump_local_context(self, frame):613 return "{%s}" % ", ".join(614 "%r: %s" % (name, target)615 for name, target in iteritems(frame.symbols.dump_stores())570 items_kv = ", ".join(571 f"{name!r}: {target}"572 for name, target in frame.symbols.dump_stores().items()573 )574 return f"{{{items_kv}}}"575576 def write_commons(self):577 """Writes a common preamble that is used by root and block functions.578 Primarily this sets up common local helpers and enforces a generator
38 unmodified lines
617 def get_resolve_func(self):618 target = self._context_reference_stack[-1]619 if target == "context":620 return "resolve"663 return "%s.resolve" % target621 return f"{target}.resolve"622623 def derive_context(self, frame):666 return "%s.derived(%s)" % (667 self.get_context_ref(),668 self.dump_local_context(frame),669 )624 return f"{self.get_context_ref()}.derived({self.dump_local_context(frame)})"625626 def parameter_is_undeclared(self, target):627 """Checks if a given target is an undeclared parameter."""628 if not self._param_def_block:
14 unmodified lines
643 public_names = [x for x in vars if x[:1] != "_"]644 if len(vars) == 1:645 name = next(iter(vars))646 ref = frame.symbols.ref(name)692 self.writeline("context.vars[%r] = %s" % (name, ref))647 self.writeline(f"context.vars[{name!r}] = {ref}")648 else:649 self.writeline("context.vars.update({")650 for idx, name in enumerate(vars):651 if idx:652 self.write(", ")653 ref = frame.symbols.ref(name)699 self.write("%r: %s" % (name, ref))654 self.write(f"{name!r}: {ref}")655 self.write("})")656 if public_names:657 if len(public_names) == 1:703 self.writeline("context.exported_vars.add(%r)" % public_names[0])658 self.writeline(f"context.exported_vars.add({public_names[0]!r})")659 else:705 self.writeline(706 "context.exported_vars.update((%s))"707 % ", ".join(imap(repr, public_names))708 )660 names_str = ", ".join(map(repr, public_names))661 self.writeline(f"context.exported_vars.update(({names_str}))")662663 # -- Statement Visitors664665 def visit_Template(self, node, frame=None):
1 unmodified line
667 eval_ctx = EvalContext(self.environment, self.name)668669 from .runtime import exported670718 self.writeline("from __future__ import %s" % ", ".join(code_features))671 self.writeline("from __future__ import generator_stop") # Python < 3.7672 self.writeline("from jinja2.runtime import " + ", ".join(exported))673674 if self.environment.is_async:675 self.writeline(
2 unmodified lines
678 )679680 # if we want a deferred initialization we cannot move the681 # environment into a local name729 envenv = not self.defer_init and ", environment=environment" or ""682 envenv = "" if self.defer_init else ", environment=environment"683684 # do we have an extends tag at all? If not, we can save some685 # overhead by just not processing any inheritance code.686 have_extends = node.find(nodes.Extends) is not None687688 # find all blocks689 for block in node.find_all(nodes.Block):690 if block.name in self.blocks:738 self.fail("block %r defined twice" % block.name, block.lineno)691 self.fail(f"block {block.name!r} defined twice", block.lineno)692 self.blocks[block.name] = block693694 # find all imports and import them695 for import_ in node.find_all(nodes.ImportedName):
1 unmodified line
697 imp = import_.importname698 self.import_aliases[imp] = alias = self.temporary_identifier()699 if "." in imp:700 module, obj = imp.rsplit(".", 1)748 self.writeline("from %s import %s as %s" % (module, obj, alias))701 self.writeline(f"from {module} import {obj} as {alias}")702 else:750 self.writeline("import %s as %s" % (imp, alias))703 self.writeline(f"import {imp} as {alias}")704705 # add the load name753 self.writeline("name = %r" % self.name)706 self.writeline(f"name = {self.name!r}")707708 # generate the root render function.709 self.writeline(757 "%s(context, missing=missing%s):" % (self.func("root"), envenv), extra=1710 f"{self.func('root')}(context, missing=missing{envenv}):", extra=1711 )712 self.indent()713 self.write_commons()714715 # process the root716 frame = Frame(eval_ctx)717 if "self" in find_undeclared(node.body, ("self",)):718 ref = frame.symbols.declare_parameter("self")766 self.writeline("%s = TemplateReference(context)" % ref)719 self.writeline(f"{ref} = TemplateReference(context)")720 frame.symbols.analyze_node(node)721 frame.toplevel = frame.rootlevel = True722 frame.require_output_check = have_extends and not self.has_known_extends723 if have_extends:
9 unmodified lines
733 if not self.has_known_extends:734 self.indent()735 self.writeline("if parent_template is not None:")736 self.indent()784 if supports_yield_from and not self.environment.is_async:737 if not self.environment.is_async:738 self.writeline("yield from parent_template.root_render_func(context)")739 else:740 loop = "async for" if self.environment.is_async else "for"741 self.writeline(788 "%sfor event in parent_template."789 "root_render_func(context):"790 % (self.environment.is_async and "async " or "")742 f"{loop} event in parent_template.root_render_func(context):"743 )744 self.indent()745 self.writeline("yield event")746 self.outdent()747 self.outdent(1 + (not self.has_known_extends))748749 # at this point we now have the blocks collected and can visit them too.798 for name, block in iteritems(self.blocks):750 for name, block in self.blocks.items():751 self.writeline(800 "%s(context, missing=missing%s):"801 % (self.func("block_" + name), envenv),752 f"{self.func('block_' + name)}(context, missing=missing{envenv}):",753 block,754 1,755 )756 self.indent()
4 unmodified lines
761 block_frame = Frame(eval_ctx)762 undeclared = find_undeclared(block.body, ("self", "super"))763 if "self" in undeclared:764 ref = block_frame.symbols.declare_parameter("self")814 self.writeline("%s = TemplateReference(context)" % ref)765 self.writeline(f"{ref} = TemplateReference(context)")766 if "super" in undeclared:767 ref = block_frame.symbols.declare_parameter("super")817 self.writeline("%s = context.super(%r, block_%s)" % (ref, name, name))768 self.writeline(f"{ref} = context.super({name!r}, block_{name})")769 block_frame.symbols.analyze_node(block)770 block_frame.block = name771 self.enter_frame(block_frame)772 self.pull_dependencies(block.body)773 self.blockvisit(block.body, block_frame)774 self.leave_frame(block_frame, with_python_scope=True)775 self.outdent()776826 self.writeline(827 "blocks = {%s}" % ", ".join("%r: block_%s" % (x, x) for x in self.blocks),828 extra=1,829 )777 blocks_kv_str = ", ".join(f"{x!r}: block_{x}" for x in self.blocks)778 self.writeline(f"blocks = {{{blocks_kv_str}}}", extra=1)779 debug_kv_str = "&".join(f"{k}={v}" for k, v in self.debug_info)780 self.writeline(f"debug_info = {debug_kv_str!r}")781831 # add a function that returns the debug info832 self.writeline(833 "debug_info = %r" % "&".join("%s=%s" % x for x in self.debug_info)834 )835782 def visit_Block(self, node, frame):783 """Call a block and register it for the template."""784 level = 0785 if frame.toplevel:
10 unmodified lines
796 context = self.derive_context(frame)797 else:798 context = self.get_context_ref()799854 if (855 supports_yield_from856 and not self.environment.is_async857 and frame.buffer is None858 ):800 if not self.environment.is_async and frame.buffer is None:801 self.writeline(860 "yield from context.blocks[%r][0](%s)" % (node.name, context), node802 f"yield from context.blocks[{node.name!r}][0]({context})", node803 )804 else:863 loop = self.environment.is_async and "async for" or "for"805 loop = "async for" if self.environment.is_async else "for"806 self.writeline(865 "%s event in context.blocks[%r][0](%s):" % (loop, node.name, context),866 node,807 f"{loop} event in context.blocks[{node.name!r}][0]({context}):", node808 )809 self.indent()810 self.simple_write("event", frame)811 self.outdent()
16 unmodified lines
828 # same error at different times just "because we can".829 if not self.has_known_extends:830 self.writeline("if parent_template is not None:")831 self.indent()891 self.writeline("raise TemplateRuntimeError(%r)" % "extended multiple times")832 self.writeline('raise TemplateRuntimeError("extended multiple times")')833834 # if we have a known extends already we don't need that code here835 # as we know that the template execution will end here.836 if self.has_known_extends:
2 unmodified lines
839 self.outdent()840841 self.writeline("parent_template = environment.get_template(", node)842 self.visit(node.template, frame)902 self.write(", %r)" % self.name)903 self.writeline(904 "for name, parent_block in parent_template.blocks.%s():" % dict_item_iter905 )843 self.write(f", {self.name!r})")844 self.writeline("for name, parent_block in parent_template.blocks.items():")845 self.indent()846 self.writeline("context.blocks.setdefault(name, []).append(parent_block)")847 self.outdent()848
13 unmodified lines
862 self.indent()863864 func_name = "get_or_select_template"865 if isinstance(node.template, nodes.Const):927 if isinstance(node.template.value, string_types):866 if isinstance(node.template.value, str):867 func_name = "get_template"868 elif isinstance(node.template.value, (tuple, list)):869 func_name = "select_template"870 elif isinstance(node.template, (nodes.Tuple, nodes.List)):871 func_name = "select_template"872934 self.writeline("template = environment.%s(" % func_name, node)873 self.writeline(f"template = environment.{func_name}(", node)874 self.visit(node.template, frame)936 self.write(", %r)" % self.name)875 self.write(f", {self.name!r})")876 if node.ignore_missing:877 self.outdent()878 self.writeline("except TemplateNotFound:")879 self.indent()
3 unmodified lines
883 self.indent()884885 skip_event_yield = False886 if node.with_context:948 loop = self.environment.is_async and "async for" or "for"887 loop = "async for" if self.environment.is_async else "for"888 self.writeline(950 "%s event in template.root_render_func("951 "template.new_context(context.get_all(), True, "952 "%s)):" % (loop, self.dump_local_context(frame))889 f"{loop} event in template.root_render_func("890 "template.new_context(context.get_all(), True,"891 f" {self.dump_local_context(frame)})):"892 )893 elif self.environment.is_async:894 self.writeline(956 "for event in (await "957 "template._get_default_module_async())"895 "for event in (await template._get_default_module_async())"896 "._body_stream:"897 )898 else:961 if supports_yield_from:962 self.writeline("yield from template._get_default_module()._body_stream")963 skip_event_yield = True899 self.writeline("yield from template._get_default_module()._body_stream")900 skip_event_yield = True964 else:965 self.writeline(966 "for event in template._get_default_module()._body_stream:"967 )901902 if not skip_event_yield:903 self.indent()904 self.simple_write("event", frame)
3 unmodified lines
908 self.outdent()909910 def visit_Import(self, node, frame):911 """Visit regular imports."""979 self.writeline("%s = " % frame.symbols.ref(node.target), node)912 self.writeline(f"{frame.symbols.ref(node.target)} = ", node)913 if frame.toplevel:981 self.write("context.vars[%r] = " % node.target)914 self.write(f"context.vars[{node.target!r}] = ")915 if self.environment.is_async:916 self.write("await ")917 self.write("environment.get_template(")918 self.visit(node.template, frame)986 self.write(", %r)." % self.name)919 self.write(f", {self.name!r}).")920 if node.with_context:921 func = "make_module" + ("_async" if self.environment.is_async else "")922 self.write(989 "make_module%s(context.get_all(), True, %s)"990 % (991 self.environment.is_async and "_async" or "",992 self.dump_local_context(frame),993 )923 f"{func}(context.get_all(), True, {self.dump_local_context(frame)})"924 )925 elif self.environment.is_async:926 self.write("_get_default_module_async()")927 else:928 self.write("_get_default_module()")929 if frame.toplevel and not node.target.startswith("_"):1000 self.writeline("context.exported_vars.discard(%r)" % node.target)930 self.writeline(f"context.exported_vars.discard({node.target!r})")931932 def visit_FromImport(self, node, frame):933 """Visit named imports."""934 self.newline(node)1005 self.write(1006 "included_template = %senvironment.get_template("1007 % (self.environment.is_async and "await " or "")1008 )935 prefix = "await " if self.environment.is_async else ""936 self.write(f"included_template = {prefix}environment.get_template(")937 self.visit(node.template, frame)1010 self.write(", %r)." % self.name)938 self.write(f", {self.name!r}).")939 if node.with_context:940 func = "make_module" + ("_async" if self.environment.is_async else "")941 self.write(1013 "make_module%s(context.get_all(), True, %s)"1014 % (1015 self.environment.is_async and "_async" or "",1016 self.dump_local_context(frame),1017 )942 f"{func}(context.get_all(), True, {self.dump_local_context(frame)})"943 )944 elif self.environment.is_async:945 self.write("_get_default_module_async()")946 else:
6 unmodified lines
953 name, alias = name954 else:955 alias = name956 self.writeline(1032 "%s = getattr(included_template, "1033 "%r, missing)" % (frame.symbols.ref(alias), name)957 f"{frame.symbols.ref(alias)} ="958 f" getattr(included_template, {name!r}, missing)"959 )1035 self.writeline("if %s is missing:" % frame.symbols.ref(alias))960 self.writeline(f"if {frame.symbols.ref(alias)} is missing:")961 self.indent()962 message = (963 "the template {included_template.__name__!r}"964 f" (imported on {self.position(node)})"965 f" does not export the requested name {name!r}"966 )967 self.writeline(1038 "%s = undefined(%r %% "1039 "included_template.__name__, "1040 "name=%r)"1041 % (1042 frame.symbols.ref(alias),1043 "the template %%r (imported on %s) does "1044 "not export the requested name %s"1045 % (self.position(node), repr(name)),1046 name,1047 )968 f"{frame.symbols.ref(alias)} = undefined(f{message!r}, name={name!r})"969 )970 self.outdent()971 if frame.toplevel:972 var_names.append(alias)
2 unmodified lines
975976 if var_names:977 if len(var_names) == 1:978 name = var_names[0]1058 self.writeline(1059 "context.vars[%r] = %s" % (name, frame.symbols.ref(name))1060 )979 self.writeline(f"context.vars[{name!r}] = {frame.symbols.ref(name)}")980 else:1062 self.writeline(1063 "context.vars.update({%s})"1064 % ", ".join(1065 "%r: %s" % (name, frame.symbols.ref(name)) for name in var_names1066 )981 names_kv = ", ".join(982 f"{name!r}: {frame.symbols.ref(name)}" for name in var_names983 )984 self.writeline(f"context.vars.update({{{names_kv}}})")985 if discarded_names:986 if len(discarded_names) == 1:1070 self.writeline("context.exported_vars.discard(%r)" % discarded_names[0])987 self.writeline(f"context.exported_vars.discard({discarded_names[0]!r})")988 else:989 names_str = ", ".join(map(repr, discarded_names))990 self.writeline(1073 "context.exported_vars.difference_"1074 "update((%s))" % ", ".join(imap(repr, discarded_names))991 f"context.exported_vars.difference_update(({names_str}))"992 )993994 def visit_For(self, node, frame):995 loop_frame = frame.inner()
17 unmodified lines
10131014 if node.test:1015 loop_filter_func = self.temporary_identifier()1016 test_frame.symbols.analyze_node(node, for_branch="test")1100 self.writeline("%s(fiter):" % self.func(loop_filter_func), node.test)1017 self.writeline(f"{self.func(loop_filter_func)}(fiter):", node.test)1018 self.indent()1019 self.enter_frame(test_frame)1103 self.writeline(self.environment.is_async and "async for " or "for ")1020 self.writeline("async for " if self.environment.is_async else "for ")1021 self.visit(node.target, loop_frame)1022 self.write(" in ")1106 self.write(self.environment.is_async and "auto_aiter(fiter)" or "fiter")1023 self.write("auto_aiter(fiter)" if self.environment.is_async else "fiter")1024 self.write(":")1025 self.indent()1026 self.writeline("if ", node.test)1027 self.visit(node.test, test_frame)
8 unmodified lines
1036 # variables at that point. Because loops can be nested but the loop1037 # variable is a special one we have to enforce aliasing for it.1038 if node.recursive:1039 self.writeline(1123 "%s(reciter, loop_render_func, depth=0):" % self.func("loop"), node1040 f"{self.func('loop')}(reciter, loop_render_func, depth=0):", node1041 )1042 self.indent()1043 self.buffer(loop_frame)1044
2 unmodified lines
10471048 # make sure the loop variable is a special one and raise a template1049 # assertion error if a loop tries to write to loop1050 if extended_loop:1134 self.writeline("%s = missing" % loop_ref)1051 self.writeline(f"{loop_ref} = missing")10521053 for name in node.find_all(nodes.Name):1054 if name.ctx == "store" and name.name == "loop":1055 self.fail(
2 unmodified lines
1058 )10591060 if node.else_:1061 iteration_indicator = self.temporary_identifier()1145 self.writeline("%s = 1" % iteration_indicator)1062 self.writeline(f"{iteration_indicator} = 1")10631147 self.writeline(self.environment.is_async and "async for " or "for ", node)1064 self.writeline("async for " if self.environment.is_async else "for ", node)1065 self.visit(node.target, loop_frame)1066 if extended_loop:1150 if self.environment.is_async:1151 self.write(", %s in AsyncLoopContext(" % loop_ref)1152 else:1153 self.write(", %s in LoopContext(" % loop_ref)1067 prefix = "Async" if self.environment.is_async else ""1068 self.write(f", {loop_ref} in {prefix}LoopContext(")1069 else:1070 self.write(" in ")10711072 if node.test:1158 self.write("%s(" % loop_filter_func)1073 self.write(f"{loop_filter_func}(")1074 if node.recursive:1075 self.write("reciter")1076 else:1077 if self.environment.is_async and not extended_loop:
6 unmodified lines
10841085 if node.recursive:1086 self.write(", undefined, loop_render_func, depth):")1087 else:1173 self.write(extended_loop and ", undefined):" or ":")1088 self.write(", undefined):" if extended_loop else ":")10891090 self.indent()1091 self.enter_frame(loop_frame)10921093 self.blockvisit(node.body, loop_frame)1094 if node.else_:1180 self.writeline("%s = 0" % iteration_indicator)1095 self.writeline(f"{iteration_indicator} = 0")1096 self.outdent()1097 self.leave_frame(1098 loop_frame, with_python_scope=node.recursive and not node.else_1099 )11001101 if node.else_:1187 self.writeline("if %s:" % iteration_indicator)1102 self.writeline(f"if {iteration_indicator}:")1103 self.indent()1104 self.enter_frame(else_frame)1105 self.blockvisit(node.else_, else_frame)1106 self.leave_frame(else_frame)
41 unmodified lines
1148 macro_frame, macro_ref = self.macro_body(node, frame)1149 self.newline()1150 if frame.toplevel:1151 if not node.name.startswith("_"):1237 self.write("context.exported_vars.add(%r)" % node.name)1238 self.writeline("context.vars[%r] = " % node.name)1239 self.write("%s = " % frame.symbols.ref(node.name))1152 self.write(f"context.exported_vars.add({node.name!r})")1153 self.writeline(f"context.vars[{node.name!r}] = ")1154 self.write(f"{frame.symbols.ref(node.name)} = ")1155 self.macro_def(macro_ref, macro_frame)11561157 def visit_CallBlock(self, node, frame):1158 call_frame, macro_ref = self.macro_body(node, frame)
17 unmodified lines
1176 def visit_With(self, node, frame):1177 with_frame = frame.inner()1178 with_frame.symbols.analyze_node(node)1179 self.enter_frame(with_frame)1265 for target, expr in izip(node.targets, node.values):1180 for target, expr in zip(node.targets, node.values):1181 self.newline()1182 self.visit(target, with_frame)1183 self.write(" = ")1184 self.visit(expr, frame)
7 unmodified lines
1192 _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1193 #: The default finalize function if the environment isn't configured1194 #: with one. Or if the environment has one, this is called on that1195 #: function's output for constants.1281 _default_finalize = text_type1196 _default_finalize = str1197 _finalize = None11981199 def _make_finalize(self):1200 """Build the finalize function to be used on constants and at
57 unmodified lines
1258 const = escape(const)12591260 # Template data doesn't go through finalize.1261 if isinstance(node, nodes.TemplateData):1347 return text_type(const)1262 return str(const)12631264 return finalize.const(const)12651266 def _output_child_pre(self, node, frame, finalize):1267 """Output extra source code before visiting a child of an1268 ``Output`` node.1269 """1270 if frame.eval_ctx.volatile:1356 self.write("(escape if context.eval_ctx.autoescape else to_string)(")1271 self.write("(escape if context.eval_ctx.autoescape else str)(")1272 elif frame.eval_ctx.autoescape:1273 self.write("escape(")1274 else:1360 self.write("to_string(")1275 self.write("str(")12761277 if finalize.src is not None:1278 self.write(finalize.src)1279
48 unmodified lines
1328 body.append([const])13291330 if frame.buffer is not None:1331 if len(body) == 1:1417 self.writeline("%s.append(" % frame.buffer)1332 self.writeline(f"{frame.buffer}.append(")1333 else:1419 self.writeline("%s.extend((" % frame.buffer)1334 self.writeline(f"{frame.buffer}.extend((")13351336 self.indent()13371338 for item in body:
50 unmodified lines
1389 self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")1390 if node.filter is not None:1391 self.visit_Filter(node.filter, block_frame)1392 else:1478 self.write("concat(%s)" % block_frame.buffer)1393 self.write(f"concat({block_frame.buffer})")1394 self.write(")")1395 self.pop_assign_tracking(frame)1396 self.leave_frame(block_frame)1397
15 unmodified lines
1413 and load[0] == VAR_LOAD_PARAMETER1414 and not self.parameter_is_undeclared(ref)1415 ):1416 self.write(1502 "(undefined(name=%r) if %s is missing else %s)"1503 % (node.name, ref, ref)1417 f"(undefined(name={node.name!r}) if {ref} is missing else {ref})"1418 )1419 return14201421 self.write(ref)
2 unmodified lines
1424 # NSRefs can only be used to store values; since they use the normal1425 # `foo.bar` notation they will be parsed as a normal attribute access1426 # when used anywhere but in a `set` context1427 ref = frame.symbols.ref(node.name)1514 self.writeline("if not isinstance(%s, Namespace):" % ref)1428 self.writeline(f"if not isinstance({ref}, Namespace):")1429 self.indent()1430 self.writeline(1517 "raise TemplateRuntimeError(%r)"1518 % "cannot assign attribute on non-namespace object"1431 "raise TemplateRuntimeError"1432 '("cannot assign attribute on non-namespace object")'1433 )1434 self.outdent()1521 self.writeline("%s[%r]" % (ref, node.attr))1435 self.writeline(f"{ref}[{node.attr!r}]")14361437 def visit_Const(self, node, frame):1438 val = node.as_const(frame.eval_ctx)1439 if isinstance(val, float):
5 unmodified lines
1445 try:1446 self.write(repr(node.as_const(frame.eval_ctx)))1447 except nodes.Impossible:1448 self.write(1535 "(Markup if context.eval_ctx.autoescape else identity)(%r)" % node.data1449 f"(Markup if context.eval_ctx.autoescape else identity)({node.data!r})"1450 )14511452 def visit_Tuple(self, node, frame):1453 self.write("(")
1 unmodified line
1455 for idx, item in enumerate(node.items):1456 if idx:1457 self.write(", ")1458 self.visit(item, frame)1545 self.write(idx == 0 and ",)" or ")")1459 self.write(",)" if idx == 0 else ")")14601461 def visit_List(self, node, frame):1462 self.write("[")1463 for idx, item in enumerate(node.items):
18 unmodified lines
1482 if (1483 self.environment.sandboxed1484 and operator in self.environment.intercepted_binops1485 ):1572 self.write("environment.call_binop(context, %r, " % operator)1486 self.write(f"environment.call_binop(context, {operator!r}, ")1487 self.visit(node.left, frame)1488 self.write(", ")1489 self.visit(node.right, frame)1490 else:1491 self.write("(")1492 self.visit(node.left, frame)1579 self.write(" %s " % operator)1493 self.write(f" {operator} ")1494 self.visit(node.right, frame)1495 self.write(")")14961497 return visitor
4 unmodified lines
1502 if (1503 self.environment.sandboxed1504 and operator in self.environment.intercepted_unops1505 ):1592 self.write("environment.call_unop(context, %r, " % operator)1506 self.write(f"environment.call_unop(context, {operator!r}, ")1507 self.visit(node.node, frame)1508 else:1509 self.write("(" + operator)1510 self.visit(node.node, frame)
17 unmodified lines
15281529 @optimizeconst1530 def visit_Concat(self, node, frame):1531 if frame.eval_ctx.volatile:1618 func_name = "(context.eval_ctx.volatile and markup_join or unicode_join)"1532 func_name = "(markup_join if context.eval_ctx.volatile else str_join)"1533 elif frame.eval_ctx.autoescape:1534 func_name = "markup_join"1535 else:1622 func_name = "unicode_join"1623 self.write("%s((" % func_name)1536 func_name = "str_join"1537 self.write(f"{func_name}((")1538 for arg in node.nodes:1539 self.visit(arg, frame)1540 self.write(", ")1541 self.write("))")
6 unmodified lines
1548 self.visit(op, frame)1549 self.write(")")15501551 def visit_Operand(self, node, frame):1638 self.write(" %s " % operators[node.op])1552 self.write(f" {operators[node.op]} ")1553 self.visit(node.expr, frame)15541555 @optimizeconst1556 def visit_Getattr(self, node, frame):
1 unmodified line
1558 self.write("(await auto_await(")15591560 self.write("environment.getattr(")1561 self.visit(node.node, frame)1648 self.write(", %r)" % node.attr)1562 self.write(f", {node.attr!r})")15631564 if self.environment.is_async:1565 self.write("))")1566
34 unmodified lines
1601 self.write("await auto_await(")1602 self.write(self.filters[node.name] + "(")1603 func = self.environment.filters.get(node.name)1604 if func is None:1691 self.fail("no filter named %r" % node.name, node.lineno)1605 self.fail(f"no filter named {node.name!r}", node.lineno)1606 if getattr(func, "contextfilter", False) is True:1607 self.write("context, ")1608 elif getattr(func, "evalcontextfilter", False) is True:1609 self.write("context.eval_ctx, ")
5 unmodified lines
1615 if node.node is not None:1616 self.visit(node.node, frame)1617 elif frame.eval_ctx.volatile:1618 self.write(1705 "(context.eval_ctx.autoescape and"1706 " Markup(concat(%s)) or concat(%s))" % (frame.buffer, frame.buffer)1619 f"(Markup(concat({frame.buffer}))"1620 f" if context.eval_ctx.autoescape else concat({frame.buffer}))"1621 )1622 elif frame.eval_ctx.autoescape:1709 self.write("Markup(concat(%s))" % frame.buffer)1623 self.write(f"Markup(concat({frame.buffer}))")1624 else:1711 self.write("concat(%s)" % frame.buffer)1625 self.write(f"concat({frame.buffer})")1626 self.signature(node, frame)1627 self.write(")")1628 if self.environment.is_async:1629 self.write(")")
1 unmodified line
1631 @optimizeconst1632 def visit_Test(self, node, frame):1633 self.write(self.tests[node.name] + "(")1634 if node.name not in self.environment.tests:1721 self.fail("no test named %r" % node.name, node.lineno)1635 self.fail(f"no test named {node.name!r}", node.lineno)1636 self.visit(node.node, frame)1637 self.signature(node, frame)1638 self.write(")")1639
2 unmodified lines
1642 def write_expr2():1643 if node.expr2 is not None:1644 return self.visit(node.expr2, frame)1645 self.write(1732 "cond_expr_undefined(%r)"1733 % (1734 "the inline if-"1735 "expression on %s evaluated to false and "1736 "no else section was defined." % self.position(node)1737 )1646 f'cond_expr_undefined("the inline if-expression on'1647 f" {self.position(node)} evaluated to false and no else"1648 f' section was defined.")'1649 )16501651 self.write("(")1652 self.visit(node.expr1, frame)
11 unmodified lines
1664 self.write("environment.call(context, ")1665 else:1666 self.write("context.call(")1667 self.visit(node.node, frame)1757 extra_kwargs = forward_caller and {"caller": "caller"} or None1668 extra_kwargs = {"caller": "caller"} if forward_caller else None1669 self.signature(node, frame, extra_kwargs)1670 self.write(")")1671 if self.environment.is_async:1672 self.write(")")
9 unmodified lines
1682 self.visit(node.expr, frame)1683 self.write(")")16841685 def visit_MarkSafeIfAutoescape(self, node, frame):1775 self.write("(context.eval_ctx.autoescape and Markup or identity)(")1686 self.write("(Markup if context.eval_ctx.autoescape else identity)(")1687 self.visit(node.expr, frame)1688 self.write(")")16891690 def visit_EnvironmentAttribute(self, node, frame):1691 self.write("environment." + node.name)16921693 def visit_ExtensionAttribute(self, node, frame):1783 self.write("environment.extensions[%r].%s" % (node.identifier, node.name))1694 self.write(f"environment.extensions[{node.identifier!r}].{node.name}")16951696 def visit_ImportedName(self, node, frame):1697 self.write(self.import_aliases[node.importname])1698
20 unmodified lines
1719 self.leave_frame(scope_frame)17201721 def visit_OverlayScope(self, node, frame):1722 ctx = self.temporary_identifier()1812 self.writeline("%s = %s" % (ctx, self.derive_context(frame)))1813 self.writeline("%s.vars = " % ctx)1723 self.writeline(f"{ctx} = {self.derive_context(frame)}")1724 self.writeline(f"{ctx}.vars = ")1725 self.visit(node.context, frame)1726 self.push_context_reference(ctx)17271728 scope_frame = frame.inner(isolated=True)
4 unmodified lines
1733 self.pop_context_reference()17341735 def visit_EvalContextModifier(self, node, frame):1736 for keyword in node.options:1826 self.writeline("context.eval_ctx.%s = " % keyword.key)1737 self.writeline(f"context.eval_ctx.{keyword.key} = ")1738 self.visit(keyword.value, frame)1739 try:1740 val = keyword.value.as_const(frame.eval_ctx)1741 except nodes.Impossible:
3 unmodified lines
17451746 def visit_ScopedEvalContextModifier(self, node, frame):1747 old_ctx_name = self.temporary_identifier()1748 saved_ctx = frame.eval_ctx.save()1838 self.writeline("%s = context.eval_ctx.save()" % old_ctx_name)1749 self.writeline(f"{old_ctx_name} = context.eval_ctx.save()")1750 self.visit_EvalContextModifier(node, frame)1751 for child in node.body:1752 self.visit(child, frame)1753 frame.eval_ctx.revert(saved_ctx)1843 self.writeline("context.eval_ctx.revert(%s)" % old_ctx_name)1754 self.writeline(f"context.eval_ctx.revert({old_ctx_name})")
modified:src/jinja2/constants.py+1 added-2 removed
1# -*- coding: utf-8 -*-1#: list of lorem ipsum words used by the lipsum() helper function3LOREM_IPSUM_WORDS = u"""\2LOREM_IPSUM_WORDS = """\3a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at4auctor augue bibendum blandit class commodo condimentum congue consectetuer5consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus6diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend
14 unmodified lines
modified:src/jinja2/debug.py+10 added-17 removed
1import platform2import sys3from types import CodeType45from . import TemplateSyntaxError5from ._compat import PYPY6from .utils import internal_code7from .utils import missing89
3 unmodified lines
13 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.17 :param source: For ``TemplateSyntaxError``, the original source if18 known.21 :return: A :meth:`sys.exc_info` tuple that can be re-raised.19 :return: The original exception with the rewritten traceback.20 """23 exc_type, exc_value, tb = sys.exc_info()21 _, exc_value, tb = sys.exc_info()2223 if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:24 exc_value.translated = True25 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)26 # Remove the old traceback, otherwise the frames from the27 # compiler still show up.28 exc_value.with_traceback(None)33 except AttributeError:34 pass3529 # Outside of runtime, so the frame isn't executing template30 # code, but it still needs to point at the template.31 tb = fake_traceback(32 exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno
29 unmodified lines
62 # Assign tb_next in reverse to avoid circular references.63 for tb in reversed(stack):64 tb_next = tb_set_next(tb, tb_next)6573 return exc_type, exc_value, tb_next66 return exc_value.with_traceback(tb_next)676869def fake_traceback(exc_value, tb, filename, lineno):70 """Produce a new traceback object that looks like it came from the
34 unmodified lines
105106 if function == "root":107 location = "top-level template code"108 elif function.startswith("block_"):116 location = 'block "%s"' % function[6:]109 location = f"block {function[6:]!r}"110111 # Collect arguments for the new code object. CodeType only112 # accepts positional arguments, and arguments were inserted in113 # new Python versions.
1 unmodified line
115116 for attr in (117 "argcount",118 "posonlyargcount", # Python 3.8126 "kwonlyargcount", # Python 3119 "kwonlyargcount",120 "nlocals",121 "stacksize",122 "flags",123 "code", # codestring
83 unmodified lines
207 tb.tb_next = tb_next208 return tb209210218elif PYPY:211elif platform.python_implementation() == "PyPy":212 # PyPy might have special support, and won't work with ctypes.213 try:214 import tputil215 except ImportError:
49 unmodified lines
modified:src/jinja2/defaults.py+1 added-3 removed
1# -*- coding: utf-8 -*-2from ._compat import range_type1from .filters import FILTERS as DEFAULT_FILTERS # noqa: F4012from .tests import TESTS as DEFAULT_TESTS # noqa: F4013from .utils import Cycler4from .utils import generate_lorem_ipsum
16 unmodified lines
2122# default filters, tests and namespace2324DEFAULT_NAMESPACE = {27 "range": range_type,25 "range": range,26 "dict": dict,27 "lipsum": generate_lorem_ipsum,28 "cycler": Cycler,29 "joiner": Joiner,
13 unmodified lines
modified:src/jinja2/environment.py+49 added-97 removed
1# -*- coding: utf-8 -*-1"""Classes for managing templates and their runtime and compile time2options.3"""4import os
4 unmodified lines
910from markupsafe import Markup1112from . import nodes14from ._compat import encode_filename15from ._compat import implements_iterator16from ._compat import implements_to_string17from ._compat import iteritems18from ._compat import PY219from ._compat import PYPY20from ._compat import reraise21from ._compat import string_types22from ._compat import text_type13from .compiler import CodeGenerator14from .compiler import generate15from .defaults import BLOCK_END_STRING16from .defaults import BLOCK_START_STRING
76 unmodified lines
93 Returns a dict of instantiated environments.94 """95 result = {}96 for extension in extensions:107 if isinstance(extension, string_types):97 if isinstance(extension, str):98 extension = import_string(extension)99 result[extension.identifier] = extension(environment)100 return result101102113def fail_for_missing_callable(string, name):114 msg = string % name103def fail_for_missing_callable(thing, name):104 msg = f"no {thing} named {name!r}"105106 if isinstance(name, Undefined):107 try:108 name._fail_with_undefined_error()109 except Exception as e:119 msg = "%s (%s; did you forget to quote the callable name?)" % (msg, e)110 msg = f"{msg} ({e}; did you forget to quote the callable name?)"111 raise TemplateRuntimeError(msg)112113114def _environment_sanity_check(environment):
5 unmodified lines
120 environment.block_start_string121 != environment.variable_start_string122 != environment.comment_start_string123 ), "block, variable and comment start strings must be different"133 assert environment.newline_sequence in (124 assert environment.newline_sequence in {125 "\r",126 "\r\n",127 "\n",137 ), "newline_sequence set to unknown line ending string."128 }, "newline_sequence set to unknown line ending string."129 return environment130131141class Environment(object):132class Environment:133 r"""The core component of Jinja is the `Environment`. It contains134 important shared variables like configuration, filters, tests,135 globals and others. Instances of this class may be modified if136 they are not shared and if no template was loaded so far.
109 unmodified lines
246247 See :ref:`bytecode-cache` for more information.248249 `enable_async`259 If set to true this enables async template execution which allows260 you to take advantage of newer Python features. This requires261 Python 3.6 or later.250 If set to true this enables async template execution which251 allows using async functions and generators.252 """253254 #: if this environment is sandboxed. Modifying this variable won't make255 #: the environment sandboxed though. For a real sandboxed environment
111 unmodified lines
367 """Add the items to the instance of the environment if they do not exist368 yet. This is used by :ref:`extensions <writing-extensions>` to register369 callbacks and configuration values without breaking inheritance.370 """381 for key, value in iteritems(attributes):371 for key, value in attributes.items():372 if not hasattr(self, key):373 setattr(self, key, value)374375 def overlay(
36 unmodified lines
412 rv.__dict__.update(self.__dict__)413 rv.overlayed = True414 rv.linked_to = self415426 for key, value in iteritems(args):416 for key, value in args.items():417 if value is not missing:418 setattr(rv, key, value)419420 if cache_size is not missing:
1 unmodified line
422 else:423 rv.cache = copy_cache(self.cache)424425 rv.extensions = {}436 for key, value in iteritems(self.extensions):426 for key, value in self.extensions.items():427 rv.extensions[key] = value.bind(rv)428 if extensions is not missing:429 rv.extensions.update(load_extensions(rv, extensions))430
9 unmodified lines
440 """Get an item or attribute of an object but prefer the item."""441 try:442 return obj[argument]443 except (AttributeError, TypeError, LookupError):454 if isinstance(argument, string_types):444 if isinstance(argument, str):445 try:446 attr = str(argument)447 except Exception:448 pass
19 unmodified lines
468469 def call_filter(470 self, name, value, args=None, kwargs=None, context=None, eval_ctx=None471 ):482 """Invokes a filter on a value the same way the compiler does it.472 """Invokes a filter on a value the same way the compiler does.473484 Note that on Python 3 this might return a coroutine in case the485 filter is running from an environment in async mode and the filter486 supports async execution. It's your responsibility to await this487 if needed.474 This might return a coroutine if the filter is running from an475 environment in async mode and the filter supports async476 execution. It's your responsibility to await this if needed.477478 .. versionadded:: 2.7479 """480 func = self.filters.get(name)481 if func is None:493 fail_for_missing_callable("no filter named %r", name)482 fail_for_missing_callable("filter", name)483 args = [value] + list(args or ())484 if getattr(func, "contextfilter", False) is True:485 if context is None:486 raise TemplateRuntimeError(
17 unmodified lines
504 .. versionadded:: 2.7505 """506 func = self.tests.get(name)507 if func is None:519 fail_for_missing_callable("no test named %r", name)508 fail_for_missing_callable("test", name)509 return func(value, *(args or ()), **(kwargs or {}))510511 @internalcode512 def parse(self, source, name=None, filename=None):
11 unmodified lines
524 self.handle_exception(source=source)525526 def _parse(self, source, name, filename):527 """Internal parsing function used by `parse` and `compile`."""539 return Parser(self, source, name, encode_filename(filename)).parse()528 return Parser(self, source, name, filename).parse()529530 def lex(self, source, name=None, filename=None):531 """Lex the given sourcecode and return a generator that yields532 tokens as tuples in the form ``(lineno, token_type, value)``.
3 unmodified lines
536 This does not perform preprocessing. If you want the preprocessing537 of the extensions to be applied you have to filter source through538 the :meth:`preprocess` method.539 """551 source = text_type(source)540 source = str(source)541 try:542 return self.lexer.tokeniter(source, name, filename)543 except TemplateSyntaxError:544 self.handle_exception(source=source)
5 unmodified lines
550 """551 return reduce(552 lambda s, e: e.preprocess(s, name, filename),553 self.iter_extensions(),565 text_type(source),554 str(source),555 )556557 def _tokenize(self, source, name, filename=None, state=None):558 """Called by the parser to do the preprocessing and filtering
52 unmodified lines
611 `defer_init` parameter added.612 """613 source_hint = None614 try:626 if isinstance(source, string_types):615 if isinstance(source, str):616 source_hint = source617 source = self._parse(source, name, filename)618 source = self._generate(source, name, filename, defer_init=defer_init)619 if raw:620 return source621 if filename is None:622 filename = "<template>"634 else:635 filename = encode_filename(filename)623 return self._compile(source, filename)624 except TemplateSyntaxError:625 self.handle_exception(source=source_hint)626
48 unmodified lines
675 filter_func=None,676 zip="deflated",677 log_function=None,678 ignore_errors=True,692 py_compile=False,679 ):680 """Finds all the templates the loader can find, compiles them681 and stores them in `target`. If `zip` is `None`, instead of in a682 zipfile, the templates will be stored in a directory.
8 unmodified lines
691 log function is provided, errors are logged. If you want template692 syntax errors to abort the compilation you can set `ignore_errors`693 to `False` and you will get an exception on syntax errors.694709 If `py_compile` is set to `True` .pyc files will be written to the710 target instead of standard .py files. This flag does not do anything711 on pypy and Python 3 where pyc files are not picked up by itself and712 don't give much benefit.713695 .. versionadded:: 2.4696 """697 from .loaders import ModuleLoader698
1 unmodified line
700701 def log_function(x):702 pass703723 if py_compile:724 if not PY2 or PYPY:725 import warnings726727 warnings.warn(728 "'py_compile=True' has no effect on PyPy or Python"729 " 3 and will be removed in version 3.0",730 DeprecationWarning,731 stacklevel=2,732 )733 py_compile = False734 else:735 import imp736 import marshal737738 py_header = imp.get_magic() + u"\xff\xff\xff\xff".encode("iso-8859-15")739740 # Python 3.3 added a source filesize to the header741 if sys.version_info >= (3, 3):742 py_header += u"\x00\x00\x00\x00".encode("iso-8859-15")743704 def write_file(filename, data):705 if zip:706 info = ZipInfo(filename)707 info.external_attr = 0o755 << 16708 zip_file.writestr(info, data)709 else:750 if isinstance(data, text_type):710 if isinstance(data, str):711 data = data.encode("utf8")712713 with open(os.path.join(target, filename), "wb") as f:714 f.write(data)
3 unmodified lines
718719 zip_file = ZipFile(720 target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]721 )762 log_function('Compiling into Zip archive "%s"' % target)722 log_function(f"Compiling into Zip archive {target!r}")723 else:724 if not os.path.isdir(target):725 os.makedirs(target)766 log_function('Compiling into folder "%s"' % target)726 log_function(f"Compiling into folder {target!r}")727728 try:729 for name in self.list_templates(extensions, filter_func):730 source, filename, _ = self.loader.get_source(self, name)
1 unmodified line
732 code = self.compile(source, name, filename, True, True)733 except TemplateSyntaxError as e:734 if not ignore_errors:735 raise776 log_function('Could not compile "%s": %s' % (name, e))736 log_function(f'Could not compile "{name}": {e}')737 continue738739 filename = ModuleLoader.get_module_filename(name)740781 if py_compile:782 c = self._compile(code, encode_filename(filename))783 write_file(filename + "c", py_header + marshal.dumps(c))784 log_function('Byte-compiled "%s" as %s' % (name, filename + "c"))785 else:786 write_file(filename, code)787 log_function('Compiled "%s" as %s' % (name, filename))741 write_file(filename, code)742 log_function(f'Compiled "{name}" as {filename}')743 finally:744 if zip:745 zip_file.close()746
36 unmodified lines
783 rewritten exceptions or return a rendered traceback for the template.784 """785 from .debug import rewrite_traceback_stack786832 reraise(*rewrite_traceback_stack(source=source))787 raise rewrite_traceback_stack(source=source)788789 def join_path(self, template, parent):790 """Join a template with the parent. By default all the lookups are791 relative to the loader root so this method returns the `template`
66 unmodified lines
858 names._fail_with_undefined_error()859860 if not names:861 raise TemplatesNotFound(907 message=u"Tried to select from an empty list " u"of templates."862 message="Tried to select from an empty list of templates."863 )864 globals = self.make_globals(globals)865 for name in names:866 if isinstance(name, Template):
13 unmodified lines
880 :meth:`get_template`.881882 .. versionadded:: 2.3883 """929 if isinstance(template_name_or_list, (string_types, Undefined)):884 if isinstance(template_name_or_list, (str, Undefined)):885 return self.get_template(template_name_or_list, parent, globals)886 elif isinstance(template_name_or_list, Template):887 return template_name_or_list888 return self.select_template(template_name_or_list, parent, globals)
12 unmodified lines
901 return self.globals902 return dict(self.globals, **d)903904950class Template(object):905class Template:906 """The central template object. This class represents a compiled template907 and is used to evaluate it.908909 Normally the template object is generated from an :class:`Environment` but
125 unmodified lines
10351036 template.render(knights='that say nih')1037 template.render({'knights': 'that say nih'})10381084 This will return the rendered template as unicode string.1039 This will return the rendered template as a string.1040 """1041 vars = dict(*args, **kwargs)1042 try:1043 return concat(self.root_render_func(self.new_context(vars)))
23 unmodified lines
1067 def generate(self, *args, **kwargs):1068 """For very large templates it can be useful to not render the whole1069 template at once but evaluate each statement after another and yield1070 piece for piece. This method basically does exactly that and returns1116 a generator that yields one item after another as unicode strings.1071 a generator that yields one item after another as strings.10721073 It accepts the same arguments as :meth:`render`.1074 """1075 vars = dict(*args, **kwargs)1076 try:1122 for event in self.root_render_func(self.new_context(vars)):1123 yield event1077 yield from self.root_render_func(self.new_context(vars))1078 except Exception:1079 yield self.environment.handle_exception()10801081 def generate_async(self, *args, **kwargs):
84 unmodified lines
1166 return []11671168 def __repr__(self):1169 if self.name is None:1216 name = "memory:%x" % id(self)1170 name = f"memory:{id(self):x}"1171 else:1172 name = repr(self.name)1219 return "<%s %s>" % (self.__class__.__name__, name)1173 return f"<{self.__class__.__name__} {name}>"117411751222@implements_to_string1223class TemplateModule(object):1176class TemplateModule:1177 """Represents an imported template. All the exported names of the1178 template are available as attributes on this object. Additionally1226 converting it into an unicode- or bytestrings renders the contents.1179 converting it into a string renders the contents.1180 """11811182 def __init__(self, template, context, body_stream=None):1183 if body_stream is None:
16 unmodified lines
1200 return concat(self._body_stream)12011202 def __repr__(self):1203 if self.__name__ is None:1251 name = "memory:%x" % id(self)1204 name = f"memory:{id(self):x}"1205 else:1206 name = repr(self.__name__)1254 return "<%s %s>" % (self.__class__.__name__, name)1207 return f"<{self.__class__.__name__} {name}>"120812091257class TemplateExpression(object):1210class TemplateExpression:1211 """The :meth:`jinja2.Environment.compile_expression` method returns an1212 instance of this object. It encapsulates the expression-like access1213 to the template with an expression it wraps.1214 """
10 unmodified lines
1225 rv = None1226 return rv122712281276@implements_iterator1277class TemplateStream(object):1229class TemplateStream:1230 """A template stream works pretty much like an ordinary python generator1231 but it can buffer multiple items to reduce the number of total iterations.1232 Per default the output is unbuffered which means that for every unbuffered1281 instruction in the template one unicode string is yielded.1233 instruction in the template one string is yielded.12341235 If buffering is enabled with a buffer size of 5, five items are combined1284 into a new unicode string. This is mainly useful if you are streaming1236 into a new string. This is mainly useful if you are streaming1237 big templates to a client via WSGI which flushes after each iteration.1238 """12391240 def __init__(self, gen):
1 unmodified line
1242 self.disable_buffering()12431244 def dump(self, fp, encoding=None, errors="strict"):1245 """Dump the complete stream into a file or file-like object.1294 Per default unicode strings are written, if you want to encode1246 Per default strings are written, if you want to encode1247 before writing specify an `encoding`.12481249 Example usage::12501251 Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1252 """1253 close = False1302 if isinstance(fp, string_types):1254 if isinstance(fp, str):1255 if encoding is None:1256 encoding = "utf-8"1257 fp = open(fp, "wb")1258 close = True
56 unmodified lines
modified:src/jinja2/exceptions.py+14 added-44 removed
1# -*- coding: utf-8 -*-2from ._compat import imap3from ._compat import implements_to_string4from ._compat import PY25from ._compat import text_type671class TemplateError(Exception):2 """Baseclass for all template errors."""311 if PY2:4 def __init__(self, message=None):5 super().__init__(message)613 def __init__(self, message=None):14 if message is not None:15 message = text_type(message).encode("utf-8")16 Exception.__init__(self, message)7 @property8 def message(self):9 if self.args:10 return self.args[0]1118 @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")1225 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_string13class TemplateNotFound(IOError, LookupError, TemplateError):14 """Raised if a template does not exist.1516 .. versionchanged:: 2.1117 If the given name is :class:`Undefined` and no message was18 provided, an :exc:`UndefinedError` is raised.19 """2050 # looks weird, but removes the warning descriptor that just51 # bogusly warns us about message being deprecated21 # Silence the Python warning about message being deprecated since22 # it's not valid here.23 message = None2425 def __init__(self, name, message=None):26 IOError.__init__(self, name)
37 unmodified lines
64 parts.append(name._undefined_message)65 else:66 parts.append(name)6797 message = u"none of the templates given were found: " + u", ".join(98 imap(text_type, parts)68 message = "none of the templates given were found: " + ", ".join(69 map(str, parts)70 )100 TemplateNotFound.__init__(self, names and names[-1] or None, message)71 TemplateNotFound.__init__(self, names[-1] if names else None, message)72 self.templates = list(names)7374104@implements_to_string75class TemplateSyntaxError(TemplateError):76 """Raised to tell the user that there is a problem with the template."""7778 def __init__(self, message, lineno, name=None, filename=None):
12 unmodified lines
91 if self.translated:92 return self.message9394 # otherwise attach some stuff125 location = "line %d" % self.lineno95 location = f"line {self.lineno}"96 name = self.filename or self.name97 if name:128 location = 'File "%s", %s' % (name, location)98 location = f'File "{name}", {location}'99 lines = [self.message, " " + location]100101 # if the source is set, add the line to the output102 if self.source is not None:
3 unmodified lines
106 line = None107 if line:108 lines.append(" " + line.strip())109140 return u"\n".join(lines)110 return "\n".join(lines)111112 def __reduce__(self):113 # https://bugs.python.org/issue1692335 Exceptions that take114 # multiple required arguments have problems with pickling.
33 unmodified lines
modified:src/jinja2/ext.py+18 added-22 removed
1# -*- coding: utf-8 -*-1"""Extension API for adding custom tags and behavior."""2import pprint3import re4from sys import version_info56from markupsafe import Markup78from . import nodes10from ._compat import iteritems11from ._compat import string_types12from ._compat import with_metaclass9from .defaults import BLOCK_END_STRING10from .defaults import BLOCK_START_STRING11from .defaults import COMMENT_END_STRING12from .defaults import COMMENT_START_STRING
12 unmodified lines
25from .runtime import concat26from .utils import contextfunction27from .utils import import_string2833# the only real useful gettext functions for a Jinja template. Note34# that ugettext must be assigned to gettext as Jinja doesn't support35# non unicode strings.29# I18N functions available in Jinja templates. If the I18N library30# provides ugettext, it will be assigned to gettext.31GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext")3732_ws_re = re.compile(r"\s*\n\s*")333435class ExtensionRegistry(type):36 """Gives the extension an unique identifier."""3738 def __new__(mcs, name, bases, d):39 rv = type.__new__(mcs, name, bases, d)46 rv.identifier = rv.__module__ + "." + rv.__name__40 rv.identifier = f"{rv.__module__}.{rv.__name__}"41 return rv424350class Extension(with_metaclass(ExtensionRegistry, object)):44class Extension(metaclass=ExtensionRegistry):45 """Extensions can be used to add extra functionality to the Jinja template46 system at the parser level. Custom extensions are bound to an environment47 but may not store environment specific data on `self`. The reason for48 this is that an extension can be bound to another environment (for
140 unmodified lines
189 newstyle_gettext=False,190 )191192 def _install(self, translations, newstyle=None):193 # ugettext and ungettext are preferred in case the I18N library194 # is providing compatibility with older Python versions.195 gettext = getattr(translations, "ugettext", None)196 if gettext is None:197 gettext = translations.gettext198 ngettext = getattr(translations, "ungettext", None)
2 unmodified lines
201 self._install_callables(gettext, ngettext, newstyle)202203 def _install_null(self, newstyle=None):204 self._install_callables(209 lambda x: x, lambda s, p, n: (n != 1 and (p,) or (s,))[0], newstyle205 lambda x: x, lambda s, p, n: s if n == 1 else p, newstyle206 )207208 def _install_callables(self, gettext, ngettext, newstyle=None):209 if newstyle is not None:
7 unmodified lines
217 for key in "gettext", "ngettext":218 self.environment.globals.pop(key, None)219220 def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):225 if isinstance(source, string_types):221 if isinstance(source, str):222 source = self.environment.parse(source)223 return extract_from_ast(source, gettext_functions)224225 def parse(self, parser):
18 unmodified lines
244245 name = parser.stream.expect("name")246 if name.value in variables:247 parser.fail(252 "translatable variable %r defined twice." % name.value,248 f"translatable variable {name.value!r} defined twice.",249 name.lineno,250 exc=TemplateAssertionError,251 )252
39 unmodified lines
292 if parser.stream.current.type != "block_end":293 name = parser.stream.expect("name")294 if name.value not in variables:295 parser.fail(300 "unknown variable %r for pluralization" % name.value,296 f"unknown variable {name.value!r} for pluralization",297 name.lineno,298 exc=TemplateAssertionError,299 )300 plural_expr = variables[name.value]
50 unmodified lines
351 elif parser.stream.current.type == "variable_begin":352 next(parser.stream)353 name = parser.stream.expect("name").value354 referenced.append(name)359 buf.append("%%(%s)s" % name)355 buf.append(f"%({name})s")356 parser.stream.expect("variable_end")357 elif parser.stream.current.type == "block_begin":358 next(parser.stream)359 if parser.stream.current.test("name:endtrans"):
44 unmodified lines
404 # in case newstyle gettext is used, the method is powerful405 # enough to handle the variable expansion and autoescape406 # handling itself407 if self.environment.newstyle_gettext:412 for key, value in iteritems(variables):408 for key, value in variables.items():409 # the function adds that later anyways in case num was410 # called num, so just skip it.411 if num_called_num and key == "num":412 continue
21 unmodified lines
434 """Adds a `do` tag to Jinja that works like the print statement just435 that it doesn't print the return value.436 """437442 tags = set(["do"])438 tags = {"do"}439440 def parse(self, parser):441 node = nodes.ExprStmt(lineno=next(parser.stream).lineno)442 node.node = parser.parse_tuple()
2 unmodified lines
445446class LoopControlExtension(Extension):447 """Adds break and continue to the template engine."""448453 tags = set(["break", "continue"])449 tags = {"break", "continue"}450451 def parse(self, parser):452 token = next(parser.stream)453 if token.value == "break":
79 unmodified lines
533534 * ``lineno`` is the number of the line on which the string was found,535 * ``function`` is the name of the ``gettext`` function used (if the536 string was extracted from embedded Python code), and541 * ``message`` is the string itself (a ``unicode`` object, or a tuple542 of ``unicode`` objects for functions with multiple string arguments).537 * ``message`` is the string, or a tuple of strings for functions538 with multiple string arguments.539540 This extraction function operates on the AST and is because of that unable541 to extract any comments. For comment support you have to use the babel542 extraction interface or extract comments yourself.
6 unmodified lines
549 continue550551 strings = []552 for arg in node.args:557 if isinstance(arg, nodes.Const) and isinstance(arg.value, string_types):553 if isinstance(arg, nodes.Const) and isinstance(arg.value, str):554 strings.append(arg.value)555 else:556 strings.append(None)557
15 unmodified lines
573 strings = tuple(strings)574 yield node.lineno, node.node.name, strings575576581class _CommentFinder(object):577class _CommentFinder:578 """Helper class to find comments in a token stream. Can only579 find comments for gettext calls forwards. Once the comment580 from line 4 is found, a comment for line 1 will not return a581 usable value.
119 unmodified lines
modified:src/jinja2/filters.py+64 added-85 removed
1# -*- coding: utf-8 -*-1"""Built-in template filters used with the ``|`` operator."""2import math3import random4import re6import warnings5from collections import abc6from collections import namedtuple7from itertools import chain8from itertools import groupby910from markupsafe import escape11from markupsafe import Markup13from markupsafe import soft_unicode12from markupsafe import soft_str1315from ._compat import abc16from ._compat import imap17from ._compat import iteritems18from ._compat import string_types19from ._compat import text_type14from .exceptions import FilterArgumentError15from .runtime import Undefined16from .utils import htmlsafe_json_dumps17from .utils import pformat24from .utils import unicode_urlencode18from .utils import url_quote19from .utils import urlize2027_word_re = re.compile(r"\w+", re.UNICODE)28_word_beginning_split_re = re.compile(r"([-\s\(\{\[\<]+)", re.UNICODE)21_word_re = re.compile(r"\w+")22_word_beginning_split_re = re.compile(r"([-\s({\[<]+)")232425def contextfilter(f):26 """Decorator for marking context dependent filters. The current
24 unmodified lines
5152def ignore_case(value):53 """For use as a postprocessor for :func:`make_attrgetter`. Converts strings54 to lowercase and returns other types as-is."""61 return value.lower() if isinstance(value, string_types) else value55 return value.lower() if isinstance(value, str) else value565758def make_attrgetter(environment, attribute, postprocess=None, default=None):59 """Returns a callable that looks up the given attribute from a
29 unmodified lines
8990 Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.91 """92 attribute_parts = (99 attribute.split(",") if isinstance(attribute, string_types) else [attribute]93 attribute.split(",") if isinstance(attribute, str) else [attribute]94 )95 attribute = [96 _prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts97 ]
16 unmodified lines
114115def _prepare_attribute_parts(attr):116 if attr is None:117 return []124 elif isinstance(attr, string_types):118 elif isinstance(attr, str):119 return [int(x) if x.isdigit() else x for x in attr.split(".")]120 else:121 return [attr]122
1 unmodified line
124def do_forceescape(value):125 """Enforce HTML escaping. This will probably double escape variables."""126 if hasattr(value, "__html__"):127 value = value.__html__()134 return escape(text_type(value))128 return escape(str(value))129130131def do_urlencode(value):132 """Quote data for use in a URL path or query using UTF-8.
10 unmodified lines
143 ``|replace("/", "%2F")`` filter.144145 .. versionadded:: 2.7146 """153 if isinstance(value, string_types) or not isinstance(value, abc.Iterable):154 return unicode_urlencode(value)147 if isinstance(value, str) or not isinstance(value, abc.Iterable):148 return url_quote(value)149150 if isinstance(value, dict):157 items = iteritems(value)151 items = value.items()152 else:153 items = iter(value)154161 return u"&".join(162 "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))163 for k, v in items155 return "&".join(156 f"{url_quote(k, for_qs=True)}={url_quote(v, for_qs=True)}" for k, v in items157 )158159160@evalcontextfilter
14 unmodified lines
175 """176 if count is None:177 count = -1178 if not eval_ctx.autoescape:186 return text_type(s).replace(text_type(old), text_type(new), count)179 return str(s).replace(str(old), str(new), count)180 if (181 hasattr(old, "__html__")182 or hasattr(new, "__html__")183 and not hasattr(s, "__html__")184 ):185 s = escape(s)186 else:194 s = soft_unicode(s)195 return s.replace(soft_unicode(old), soft_unicode(new), count)187 s = soft_str(s)188 return s.replace(soft_str(old), soft_str(new), count)189190191def do_upper(s):192 """Convert a value to uppercase."""200 return soft_unicode(s).upper()193 return soft_str(s).upper()194195196def do_lower(s):197 """Convert a value to lowercase."""205 return soft_unicode(s).lower()198 return soft_str(s).lower()199200201@evalcontextfilter202def do_xmlattr(_eval_ctx, d, autospace=True):
18 unmodified lines
221222 As you can see it automatically prepends a space in front of the item223 if the filter returned something unless the second parameter is false.224 """232 rv = u" ".join(233 u'%s="%s"' % (escape(key), escape(value))234 for key, value in iteritems(d)225 rv = " ".join(226 f'{escape(key)}="{escape(value)}"'227 for key, value in d.items()228 if value is not None and not isinstance(value, Undefined)229 )230 if autospace and rv:238 rv = u" " + rv231 rv = " " + rv232 if _eval_ctx.autoescape:233 rv = Markup(rv)234 return rv235
1 unmodified line
237def do_capitalize(s):238 """Capitalize a value. The first character will be uppercase, all others239 lowercase.240 """248 return soft_unicode(s).capitalize()241 return soft_str(s).capitalize()242243244def do_title(s):245 """Return a titlecased version of the value. I.e. words will start with
1 unmodified line
247 """248 return "".join(249 [250 item[0].upper() + item[1:].lower()258 for item in _word_beginning_split_re.split(soft_unicode(s))251 for item in _word_beginning_split_re.split(soft_str(s))252 if item253 ]254 )255
156 unmodified lines
412 """413 return _min_or_max(environment, value, max, case_sensitive, attribute)414415423def do_default(value, default_value=u"", boolean=False):416def do_default(value, default_value="", boolean=False):417 """If the value is undefined it will return the passed default value,418 otherwise the value of the variable:419420 .. sourcecode:: jinja
20 unmodified lines
441 return value442443444@evalcontextfilter452def do_join(eval_ctx, value, d=u"", attribute=None):445def do_join(eval_ctx, value, d="", attribute=None):446 """Return a string which is the concatenation of the strings in the447 sequence. The separator between elements is an empty string per448 default, you can define it with the optional parameter:449
14 unmodified lines
464 .. versionadded:: 2.6465 The `attribute` parameter was added.466 """467 if attribute is not None:475 value = imap(make_attrgetter(eval_ctx.environment, attribute), value)468 value = map(make_attrgetter(eval_ctx.environment, attribute), value)469470 # no automatic escaping? joining is a lot easier then471 if not eval_ctx.autoescape:479 return text_type(d).join(imap(text_type, value))472 return str(d).join(map(str, value))473474 # if the delimiter doesn't have an html representation we check475 # if any of the items has. If yes we do a coercion to Markup476 if not hasattr(d, "__html__"):
2 unmodified lines
479 for idx, item in enumerate(value):480 if hasattr(item, "__html__"):481 do_escape = True482 else:490 value[idx] = text_type(item)483 value[idx] = str(item)484 if do_escape:485 d = escape(d)486 else:494 d = text_type(d)487 d = str(d)488 return d.join(value)489490 # no html involved, to normal joining498 return soft_unicode(d).join(imap(soft_unicode, value))491 return soft_str(d).join(map(soft_str, value))492493494def do_center(value, width=80):495 """Centers the value in a field of a given width."""503 return text_type(value).center(width)496 return str(value).center(width)497498499@environmentfilter500def do_first(environment, seq):
37 unmodified lines
538 Giga, etc.), if the second parameter is set to `True` the binary539 prefixes are used (Mebi, Gibi).540 """541 bytes = float(value)549 base = binary and 1024 or 1000542 base = 1024 if binary else 1000543 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"),544 ("KiB" if binary else "kB"),545 ("MiB" if binary else "MB"),546 ("GiB" if binary else "GB"),547 ("TiB" if binary else "TB"),548 ("PiB" if binary else "PB"),549 ("EiB" if binary else "EB"),550 ("ZiB" if binary else "ZB"),551 ("YiB" if binary else "YB"),552 ]553 if bytes == 1:554 return "1 Byte"555 elif bytes < base:563 return "%d Bytes" % bytes556 return f"{int(bytes)} Bytes"557 else:558 for i, prefix in enumerate(prefixes):559 unit = base ** (i + 2)560 if bytes < unit:568 return "%.1f %s" % ((base * bytes / unit), prefix)569 return "%.1f %s" % ((base * bytes / unit), prefix)561 return f"{base * bytes / unit:.1f} {prefix}"562 return f"{base * bytes / unit:.1f} {prefix}"563564572def do_pprint(value, verbose=False):573 """Pretty print a variable. Useful for debugging.565def do_pprint(value):566 """Pretty print a variable. Useful for debugging."""567 return pformat(value)568575 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)569580570@evalcontextfilter571def do_urlize(572 eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None573):
14 unmodified lines
588 .. sourcecode:: jinja589590 {{ mytext|urlize(40, target='_blank') }}591603 .. versionchanged:: 2.8+604 The *target* parameter was added.592 .. versionchanged:: 2.8593 The ``target`` parameter was added.594 """595 policies = eval_ctx.environment.policies596 rel = set((rel or "").split() or [])597 if nofollow:
7 unmodified lines
605 rv = Markup(rv)606 return rv607608620def do_indent(s, width=4, first=False, blank=False, indentfirst=None):609def do_indent(s, width=4, first=False, blank=False):610 """Return a copy of the string with each line indented by 4 spaces. The611 first line and blank lines are not indented by default.612613 :param width: Number of spaces to indent by.
4 unmodified lines
618 Blank lines are not indented by default.619620 Rename the ``indentfirst`` argument to ``first``.621 """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 = indentfirst622 indention = " " * width623 newline = "\n"624642 indention = u" " * width643 newline = u"\n"644625 if isinstance(s, Markup):626 indention = Markup(indention)627 newline = Markup(newline)628
42 unmodified lines
671 can be reconfigured globally.672 """673 if leeway is None:674 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" % leeway675 assert length >= len(end), f"expected length >= {len(end)}, got {length}"676 assert leeway >= 0, f"expected leeway >= 0, got {leeway}"677 if len(s) <= length + leeway:678 return s679 if killwords:680 return s[: length - len(end)] + end
72 unmodified lines
753 0b, 0o and 0x for bases 2, 8 and 16 respectively.754 The base is ignored for decimal numbers and non-string values.755 """756 try:777 if isinstance(value, string_types):757 if isinstance(value, str):758 return int(value, base)759 return int(value)760 except (TypeError, ValueError):761 # this quirk is necessary so that "42.23"|int gives 42.
37 unmodified lines
799 if args and kwargs:800 raise FilterArgumentError(801 "can't handle positional and keyword arguments at the same time"802 )823 return soft_unicode(value) % (kwargs or args)803 return soft_str(value) % (kwargs or args)804805806def do_trim(value, chars=None):807 """Strip leading and trailing characters, by default whitespace."""828 return soft_unicode(value).strip(chars)808 return soft_str(value).strip(chars)809810811def do_striptags(value):812 """Strip SGML/XML tags and replace adjacent whitespace by one space."""813 if hasattr(value, "__html__"):814 value = value.__html__()835 return Markup(text_type(value)).striptags()815 return Markup(str(value)).striptags()816817818def do_slice(value, slices, fill_with=None):819 """Slice an iterator and return a list of lists containing
164 unmodified lines
984 The `attribute` parameter was added to allow suming up over985 attributes. Also the `start` parameter was moved on to the right.986 """987 if attribute is not None:1008 iterable = imap(make_attrgetter(environment, attribute), iterable)988 iterable = map(make_attrgetter(environment, attribute), iterable)989 return sum(iterable, start)990991992def do_list(value):
11 unmodified lines
100410051006def do_mark_unsafe(value):1007 """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1028 return text_type(value)1008 return str(value)100910101011def do_reverse(value):1012 """Reverse the object or return an iterator that iterates over it the other1013 way round.1014 """1035 if isinstance(value, string_types):1015 if isinstance(value, str):1016 return value[::-1]1017 try:1018 return reversed(value)1019 except TypeError:
222 unmodified lines
12421243def prepare_map(args, kwargs):1244 context = args[0]1245 seq = args[1]1266 default = None12461247 if len(args) == 2 and "attribute" in kwargs:1248 attribute = kwargs.pop("attribute")1249 default = kwargs.pop("default", None)1250 if kwargs:1251 raise FilterArgumentError(1273 "Unexpected keyword argument %r" % next(iter(kwargs))1252 f"Unexpected keyword argument {next(iter(kwargs))!r}"1253 )1254 func = make_attrgetter(context.environment, attribute, default=default)1255 else:1256 try:
86 unmodified lines
1343 "select": do_select,1344 "selectattr": do_selectattr,1345 "slice": do_slice,1346 "sort": do_sort,1368 "string": soft_unicode,1347 "string": soft_str,1348 "striptags": do_striptags,1349 "sum": do_sum,1350 "title": do_title,1351 "trim": do_trim,
10 unmodified lines
modified:src/jinja2/idtracking.py+7 added-8 removed
1from ._compat import iteritems1from .visitor import NodeVisitor23VAR_LOAD_PARAMETER = "param"4VAR_LOAD_RESOLVE = "resolve"
14 unmodified lines
19 sym.analyze_node(node)20 return sym212224class Symbols(object):23class Symbols:24 def __init__(self, parent=None, level=None):25 if level is None:26 if parent is None:27 level = 0
9 unmodified lines
37 visitor = RootVisitor(self)38 visitor.visit(node, **kwargs)3940 def _define_ref(self, name, load=None):42 ident = "l_%d_%s" % (self.level, name)41 ident = f"l_{self.level}_{name}"42 self.refs[name] = ident43 if load is not None:44 self.loads[ident] = load45 return ident
13 unmodified lines
59 def ref(self, name):60 rv = self.find_ref(name)61 if rv is None:62 raise AssertionError(64 "Tried to resolve a name to a reference that "65 "was unknown to the frame (%r)" % name63 "Tried to resolve a name to a reference that was"64 f" unknown to the frame ({name!r})"65 )66 return rv6768 def copy(self):
43 unmodified lines
112 self.refs.update(sym.refs)113 self.loads.update(sym.loads)114 self.stores.update(sym.stores)115117 for name, branch_count in iteritems(stores):116 for name, branch_count in stores.items():117 if branch_count == len(branch_symbols):118 continue119 target = self.find_ref(name)120 assert target is not None, "should not happen"
18 unmodified lines
139 def dump_param_targets(self):140 rv = set()141 node = self142 while node is not None:144 for target, (instr, _) in iteritems(self.loads):143 for target, (instr, _) in self.loads.items():144 if instr == VAR_LOAD_PARAMETER:145 rv.add(target)146 node = node.parent147 return rv
50 unmodified lines
198 self.sym_visitor.visit(child)199200 def generic_visit(self, node, *args, **kwargs):201 raise NotImplementedError(203 "Cannot find symbols for %r" % node.__class__.__name__202 f"Cannot find symbols for {node.__class__.__name__!r}"203 )204205206class FrameSymbolVisitor(NodeVisitor):
83 unmodified lines
modified:src/jinja2/lexer.py+52 added-103 removed
1# -*- coding: utf-8 -*-1"""Implements a Jinja / Python combination lexer. The ``Lexer`` class2is used to do some preprocessing. It filters out invalid operators like3the bitshift operators we don't allow in templates. It separates4template code and python code in expressions.
1 unmodified line
6import re7from ast import literal_eval8from collections import deque9from operator import itemgetter10from sys import intern1112from ._compat import implements_iterator13from ._compat import intern14from ._compat import iteritems15from ._compat import text_type12from ._identifier import pattern as name_re13from .exceptions import TemplateSyntaxError14from .utils import LRUCache1516# cache for the lexers. Exists in order to be able to have multiple17# environments with the same lexer18_lexer_cache = LRUCache(50)1920# static regular expressions24whitespace_re = re.compile(r"\s+", re.U)21whitespace_re = re.compile(r"\s+")22newline_re = re.compile(r"(\r\n|\r|\n)")23string_re = re.compile(24 r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S25)
11 unmodified lines
37 """,38 re.IGNORECASE | re.VERBOSE,39)4044try: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 = True5741# internal the tokens and keep references to them42TOKEN_ADD = intern("add")43TOKEN_ASSIGN = intern("assign")44TOKEN_COLON = intern("colon")
73 unmodified lines
118 ",": TOKEN_COMMA,119 ";": TOKEN_SEMICOLON,120}121139reverse_operators = dict([(v, k) for k, v in iteritems(operators)])122reverse_operators = {v: k for k, v in operators.items()}123assert len(operators) == len(reverse_operators), "operators dropped"124operator_re = re.compile(142 "(%s)" % "|".join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))125 f"({'|'.join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))})"126)127128ignored_tokens = frozenset(129 [
95 unmodified lines
225226 return [x[1:] for x in sorted(rules, reverse=True)]227228246class Failure(object):229class Failure:230 """Class that raises a `TemplateSyntaxError` if called.231 Used by the `Lexer` to specify known errors.232 """233
41 unmodified lines
275 return True276 return False277278 def __repr__(self):296 return "Token(%r, %r, %r)" % (self.lineno, self.type, self.value)279 return f"Token({self.lineno!r}, {self.type!r}, {self.value!r})"280281299@implements_iterator300class TokenStreamIterator(object):282class TokenStreamIterator:283 """The iterator for tokenstreams. Iterate over the stream284 until the eof token is reached.285 """286
11 unmodified lines
298 next(self.stream)299 return token300301320@implements_iterator321class TokenStream(object):302class TokenStream:303 """A token stream is an iterable that yields :class:`Token`\\s. The304 parser however does not iterate over it but calls :meth:`next` to go305 one token ahead. The current active token is stored as :attr:`current`.306 """
76 unmodified lines
383 if not self.current.test(expr):384 expr = describe_token_expr(expr)385 if self.current.type is TOKEN_EOF:386 raise TemplateSyntaxError(406 "unexpected end of template, expected %r." % expr,387 f"unexpected end of template, expected {expr!r}.",388 self.current.lineno,389 self.name,390 self.filename,391 )392 raise TemplateSyntaxError(412 "expected token %r, got %r" % (expr, describe_token(self.current)),393 f"expected token {expr!r}, got {describe_token(self.current)!r}",394 self.current.lineno,395 self.name,396 self.filename,397 )
35 unmodified lines
433434 # Even though it looks like a no-op, creating instances fails435 # without this.436 def __new__(cls, *members, **kwargs):456 return super(OptionalLStrip, cls).__new__(cls, members)437 return super().__new__(cls, members)438439459class Lexer(object):440class Lexer:441 """Class that implements a lexer for a given environment. Automatically442 created by the environment class, usually you don't have to do that.443444 Note that the lexer is not automatically bound to an environment.
24 unmodified lines
469 # variables are just part of the rules if variable processing470 # is required.471 root_tag_rules = compile_rules(environment)472473 block_start_re = e(environment.block_start_string)474 block_end_re = e(environment.block_end_string)475 comment_end_re = e(environment.comment_end_string)476 variable_end_re = e(environment.variable_end_string)477478 # block suffix if trimming is enabled493 block_suffix_re = environment.trim_blocks and "\\n?" or ""479 block_suffix_re = "\\n?" if environment.trim_blocks else ""480481 # If lstrip is enabled, it should not be applied if there is any482 # non-whitespace between the newline and block.483 self.lstrip_unless_re = c(r"[^ \t]") if environment.lstrip_blocks else None484485 self.newline_sequence = environment.newline_sequence486 self.keep_trailing_newline = environment.keep_trailing_newline487488 root_raw_re = (489 fr"(?P<raw_begin>{block_start_re}(\-|\+|)\s*raw\s*"490 fr"(?:\-{block_end_re}\s*|{block_end_re}))"491 )492 root_parts_re = "|".join(493 [root_raw_re] + [fr"(?P<{n}>{r}(\-|\+|))" for n, r in root_tag_rules]494 )495496 # global lexing rules497 self.rules = {498 "root": [499 # directives500 (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 ),501 c(fr"(.*?)(?:{root_parts_re})"),502 OptionalLStrip(TOKEN_DATA, "#bygroup"),503 "#bygroup",504 ),505 # data
2 unmodified lines
508 # comments509 TOKEN_COMMENT_BEGIN: [510 (511 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 )512 fr"(.*?)((?:\-{comment_end_re}\s*"513 fr"|{comment_end_re}){block_suffix_re})"514 ),515 (TOKEN_COMMENT, TOKEN_COMMENT_END),516 "#pop",517 ),544 (c("(.)"), (Failure("Missing end of comment tag"),), None),518 (c(r"(.)"), (Failure("Missing end of comment tag"),), None),519 ],520 # blocks521 TOKEN_BLOCK_BEGIN: [522 (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 ),523 c(fr"(?:\-{block_end_re}\s*|{block_end_re}){block_suffix_re}"),524 TOKEN_BLOCK_END,525 "#pop",526 ),527 ]528 + tag_rules,529 # variables530 TOKEN_VARIABLE_BEGIN: [531 (565 c(566 r"\-%s\s*|%s"567 % (568 e(environment.variable_end_string),569 e(environment.variable_end_string),570 )571 ),532 c(fr"\-{variable_end_re}\s*|{variable_end_re}"),533 TOKEN_VARIABLE_END,534 "#pop",535 )536 ]
1 unmodified line
538 # raw block539 TOKEN_RAW_BEGIN: [540 (541 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 )542 fr"(.*?)((?:{block_start_re}(\-|\+|))\s*endraw\s*"543 fr"(?:\-{block_end_re}\s*|{block_end_re}{block_suffix_re}))"544 ),545 OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END),546 "#pop",547 ),592 (c("(.)"), (Failure("Missing end of raw directive"),), None),548 (c(r"(.)"), (Failure("Missing end of raw directive"),), None),549 ],550 # line statements551 TOKEN_LINESTATEMENT_BEGIN: [552 (c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")
9 unmodified lines
562 ],563 }564565 def _normalize_newlines(self, value):610 """Called for strings and template data to normalize it to unicode."""566 """Replace all newlines with the configured sequence in strings567 and template data.568 """569 return newline_re.sub(self.newline_sequence, value)570571 def tokenize(self, source, name=None, filename=None, state=None):572 """Calls tokeniter + tokenize and wraps it in a token stream."""
19 unmodified lines
592 elif token == "keyword":593 token = value594 elif token == TOKEN_NAME:595 value = str(value)638 if check_ident and not value.isidentifier():596 if not value.isidentifier():597 raise TemplateSyntaxError(598 "Invalid character in identifier", lineno, name, filename599 )600 elif token == TOKEN_STRING:
19 unmodified lines
620 def tokeniter(self, source, name, filename=None, state=None):621 """This method tokenizes the text and returns the tokens in a622 generator. Use this method if you just want to tokenize a template.623 """666 source = text_type(source)624 lines = source.splitlines()625 if self.keep_trailing_newline and source:669 for newline in ("\r\n", "\r", "\n"):670 if source.endswith(newline):671 lines.append("")626 if source.endswith(("\r\n", "\r", "\n")):627 lines.append("")672 break628 source = "\n".join(lines)629 pos = 0630 lineno = 1631 stack = ["root"]
64 unmodified lines
696 # bygroup is a bit more complex, in that case we697 # yield for the current token the first named698 # group that matched699 elif token == "#bygroup":745 for key, value in iteritems(m.groupdict()):700 for key, value in m.groupdict().items():701 if value is not None:702 yield lineno, key, value703 lineno += value.count("\n")704 break705 else:706 raise RuntimeError(752 "%r wanted to resolve "753 "the token dynamically"754 " but no group matched" % regex707 f"{regex!r} wanted to resolve the token dynamically"708 " but no group matched"709 )710 # normal group711 else:712 data = groups[idx]
14 unmodified lines
727 balancing_stack.append("]")728 elif data in ("}", ")", "]"):729 if not balancing_stack:730 raise TemplateSyntaxError(777 "unexpected '%s'" % data, lineno, name, filename731 f"unexpected '{data}'", lineno, name, filename732 )733 expected_op = balancing_stack.pop()734 if expected_op != data:735 raise TemplateSyntaxError(782 "unexpected '%s', "783 "expected '%s'" % (data, expected_op),736 f"unexpected '{data}', expected '{expected_op}'",737 lineno,738 name,739 filename,740 )
13 unmodified lines
754 if new_state == "#pop":755 stack.pop()756 # resolve the new state by group checking757 elif new_state == "#bygroup":805 for key, value in iteritems(m.groupdict()):758 for key, value in m.groupdict().items():759 if value is not None:760 stack.append(key)761 break762 else:763 raise RuntimeError(811 "%r wanted to resolve the "812 "new state dynamically but"813 " no group matched" % regex764 f"{regex!r} wanted to resolve the new state dynamically"765 f" but no group matched"766 )767 # direct state name given768 else:769 stack.append(new_state)
2 unmodified lines
772 # this means a loop without break condition, avoid that and773 # raise error774 elif pos2 == pos:775 raise RuntimeError(824 "%r yielded empty string without stack change" % regex776 f"{regex!r} yielded empty string without stack change"777 )778 # publish new function and start again779 pos = pos2780 break
4 unmodified lines
785 if pos >= source_length:786 return787 # something went wrong788 raise TemplateSyntaxError(837 "unexpected char %r at %d" % (source[pos], pos),838 lineno,839 name,840 filename,789 f"unexpected char {source[pos]!r} at {pos}", lineno, name, filename790 )
modified:src/jinja2/loaders.py+25 added-35 removed
1# -*- coding: utf-8 -*-1"""API and implementations for loading templates from different data2sources.3"""4import os5import pkgutil6import sys7import weakref8from collections import abc9from hashlib import sha110from importlib import import_module11from os import path11from types import ModuleType1214from ._compat import abc15from ._compat import fspath16from ._compat import iteritems17from ._compat import string_types13from .exceptions import TemplateNotFound14from .utils import internalcode15from .utils import open_if_exists16
4 unmodified lines
21 """22 pieces = []23 for piece in template.split("/"):24 if (30 path.sep in piece31 or (path.altsep and path.altsep in piece)32 or piece == path.pardir25 os.path.sep in piece26 or (os.path.altsep and os.path.altsep in piece)27 or piece == os.path.pardir28 ):29 raise TemplateNotFound(template)30 elif piece and piece != ".":31 pieces.append(piece)32 return pieces333440class BaseLoader(object):35class BaseLoader:36 """Baseclass for all loaders. Subclass this and override `get_source` to37 implement a custom loading mechanism. The environment provides a38 `get_template` method that calls the loader's `load` method to get the39 :class:`Template` object.
31 unmodified lines
71 tuple in the form ``(source, filename, uptodate)`` or raise a72 `TemplateNotFound` error if it can't locate the template.7374 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 tracebacks75 template as a string. The filename should be the name of the76 file on the filesystem if it was loaded from there, otherwise77 ``None``. The filename is used by Python for the tracebacks78 if no loader extension is used.7980 The last item in the tuple is the `uptodate` function. If auto81 reloading is enabled it's always called to check if the template
2 unmodified lines
84 the template will be reloaded.85 """86 if not self.has_source_access:87 raise RuntimeError(93 "%s cannot provide access to the source" % self.__class__.__name__88 f"{self.__class__.__name__} cannot provide access to the source"89 )90 raise TemplateNotFound(template)9192 def list_templates(self):
64 unmodified lines
157 The ``followlinks`` parameter was added.158 """159160 def __init__(self, searchpath, encoding="utf-8", followlinks=False):166 if not isinstance(searchpath, abc.Iterable) or isinstance(167 searchpath, string_types168 ):161 if not isinstance(searchpath, abc.Iterable) or isinstance(searchpath, str):162 searchpath = [searchpath]163171 # 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]174164 self.searchpath = list(searchpath)165 self.encoding = encoding166 self.followlinks = followlinks167168 def get_source(self, environment, template):169 pieces = split_template_path(template)170 for searchpath in self.searchpath:181 filename = path.join(searchpath, *pieces)171 filename = os.path.join(searchpath, *pieces)172 f = open_if_exists(filename)173 if f is None:174 continue175 try:176 contents = f.read().decode(self.encoding)177 finally:178 f.close()179190 mtime = path.getmtime(filename)180 mtime = os.path.getmtime(filename)181182 def uptodate():183 try:194 return path.getmtime(filename) == mtime184 return os.path.getmtime(filename) == mtime185 except OSError:186 return False187188 return contents, filename, uptodate
86 unmodified lines
275 break276277 if self._template_root is None:278 raise ValueError(289 "The %r package was not installed in a way that"290 " PackageLoader understands." % package_name279 f"The {package_name!r} package was not installed in a"280 " way that PackageLoader understands."281 )282283 def get_source(self, environment, template):284 p = os.path.join(self._template_root, *split_template_path(template))
61 unmodified lines
346 return results347348349class 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:350 """Loads a template from a Python dict mapping template names to351 template source. This loader is useful for unittesting:352353 >>> loader = DictLoader({'index.html': 'source here'})354355 Because auto reloading is rarely useful this is disabled per default.
14 unmodified lines
370371class FunctionLoader(BaseLoader):372 """A loader that is passed a function which does the loading. The373 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,374 a string with the template source, a tuple in the form ``(source,375 filename, uptodatefunc)`` or `None` if the template does not exist.376377 >>> def load_template(name):378 ... if name == 'index.html':
13 unmodified lines
392 def get_source(self, environment, template):393 rv = self.load_func(template)394 if rv is None:395 raise TemplateNotFound(template)406 elif isinstance(rv, string_types):396 elif isinstance(rv, str):397 return rv, None, None398 return rv399400
44 unmodified lines
445 raise TemplateNotFound(name)446447 def list_templates(self):448 result = []459 for prefix, loader in iteritems(self.mapping):449 for prefix, loader in self.mapping.items():450 for template in loader.list_templates():451 result.append(prefix + self.delimiter + template)452 return result453
58 unmodified lines
512513 has_source_access = False514515 def __init__(self, path):526 package_name = "_jinja2_module_templates_%x" % id(self)516 package_name = f"_jinja2_module_templates_{id(self):x}"517518 # create a fake module that looks for the templates in the519 # path given.520 mod = _TemplateModule(package_name)521532 if not isinstance(path, abc.Iterable) or isinstance(path, string_types):522 if not isinstance(path, abc.Iterable) or isinstance(path, str):523 path = [path]524535 mod.__path__ = [fspath(p) for p in path]525 mod.__path__ = [os.fspath(p) for p in path]526527 sys.modules[package_name] = weakref.proxy(528 mod, lambda x: sys.modules.pop(package_name, None)529 )
14 unmodified lines
544545 @internalcode546 def load(self, environment, name, globals=None):547 key = self.get_template_key(name)558 module = "%s.%s" % (self.package_name, key)548 module = f"{self.package_name}.{key}"549 mod = getattr(self.module, module, None)550 if mod is None:551 try:552 mod = __import__(module, None, None, ["root"])
10 unmodified lines
modified:src/jinja2/meta.py+5 added-8 removed
1# -*- coding: utf-8 -*-1"""Functions that expose information about templates that might be2interesting for introspection.3"""4from . import nodes6from ._compat import iteritems7from ._compat import string_types5from .compiler import CodeGenerator678class TrackingCodeGenerator(CodeGenerator):
8 unmodified lines
1718 def enter_frame(self, frame):19 """Remember all undeclared identifiers."""20 CodeGenerator.enter_frame(self, frame)24 for _, (action, param) in iteritems(frame.symbols.loads):21 for _, (action, param) in frame.symbols.loads.items():22 if action == "resolve" and param not in self.environment.globals:23 self.undeclared_identifiers.add(param)2425
5 unmodified lines
3132 >>> from jinja2 import Environment, meta33 >>> env = Environment()34 >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')38 >>> meta.find_undeclared_variables(ast) == set(['bar'])35 >>> meta.find_undeclared_variables(ast) == {'bar'}36 True3738 .. admonition:: Implementation39
31 unmodified lines
71 for template_name in node.template.items:72 # something const, only yield the strings and ignore73 # non-string consts that really just make no sense74 if isinstance(template_name, nodes.Const):78 if isinstance(template_name.value, string_types):75 if isinstance(template_name.value, str):76 yield template_name.value77 # something dynamic in there78 else:79 yield None
1 unmodified line
81 else:82 yield None83 continue84 # constant is a basestring, direct template name88 if isinstance(node.template.value, string_types):85 if isinstance(node.template.value, str):86 yield node.template.value87 # a tuple or list (latter *should* not happen) made of consts,88 # yield the consts that are strings. We could warn here for89 # non string values90 elif isinstance(node, nodes.Include) and isinstance(91 node.template.value, (tuple, list)92 ):93 for template_name in node.template.value:97 if isinstance(template_name, string_types):94 if isinstance(template_name, str):95 yield template_name96 # something else we don't care about, we could warn here97 else:98 yield None
modified:src/jinja2/nativetypes.py+4 added-4 removed
2 unmodified lines
3from itertools import chain4from itertools import islice56from . import nodes7from ._compat import text_type7from .compiler import CodeGenerator8from .compiler import has_safe_repr9from .environment import Environment10from .environment import Template
20 unmodified lines
31 raw = head[0]32 else:33 if isinstance(nodes, types.GeneratorType):34 nodes = chain(head, nodes)36 raw = u"".join([text_type(v) for v in nodes])35 raw = "".join([str(v) for v in nodes])3637 try:38 literal = literal_eval(raw)39 except (ValueError, SyntaxError, MemoryError):
3 unmodified lines
43 # quote character to avoid dropping quotes between expression nodes.44 # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should45 # be ('a', 'b').46 if preserve_quotes and isinstance(literal, str):48 return "{quote}{}{quote}".format(literal, quote=raw[0])47 quote = raw[0]48 return f"{quote}{literal}{quote}"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`55 ``str()`` around output nodes, and using :func:`native_concat`56 to convert complex strings back to Python types if possible.57 """5859 @staticmethod
52 unmodified lines
modified:src/jinja2/nodes.py+29 added-65 removed
1# -*- coding: utf-8 -*-1"""AST nodes generated by the parser for the compiler. Also provides2some node tree helper functions used by the parser and compiler in order3to normalize nodes.4"""
1 unmodified line
6from collections import deque78from markupsafe import Markup911from ._compat import izip12from ._compat import PY213from ._compat import text_type14from ._compat import with_metaclass1510_binop_to_func = {11 "*": operator.mul,12 "/": operator.truediv,13 "//": operator.floordiv,
2 unmodified lines
16 "+": operator.add,17 "-": operator.sub,18}1926_uaop_to_func = {"not": operator.not_, "+": operator.pos, "-": operator.neg}20_uaop_to_func = {21 "not": operator.not_,22 "+": operator.pos,23 "-": operator.neg,24}2526_cmpop_to_func = {27 "eq": operator.eq,28 "ne": operator.ne,
17 unmodified lines
4647 def __new__(mcs, name, bases, d):48 for attr in "fields", "attributes":49 storage = []52 storage.extend(getattr(bases[0], attr, ()))50 storage.extend(getattr(bases[0] if bases else object, attr, ()))51 storage.extend(d.get(attr, ()))54 assert len(bases) == 1, "multiple inheritance not allowed"52 assert len(bases) <= 1, "multiple inheritance not allowed"53 assert len(storage) == len(set(storage)), "layout conflict"54 d[attr] = tuple(storage)55 d.setdefault("abstract", False)56 return type.__new__(mcs, name, bases, d)575861class EvalContext(object):59class EvalContext:60 """Holds evaluation time information. Custom attributes can be attached61 to it in extensions.62 """63
16 unmodified lines
80def get_eval_context(node, ctx):81 if ctx is None:82 if node.environment is None:83 raise RuntimeError(86 "if no eval context is passed, the "87 "node must have an attached "88 "environment."84 "if no eval context is passed, the node must have an"85 " attached environment."86 )87 return EvalContext(node.environment)88 return ctx899094class Node(with_metaclass(NodeType, object)):91class Node(metaclass=NodeType):92 """Baseclass for all Jinja nodes. There are a number of nodes available93 of different types. There are four major types:9495 - :class:`Stmt`: statements
18 unmodified lines
114 raise TypeError("abstract nodes are not instantiable")115 if fields:116 if len(fields) != len(self.fields):117 if not self.fields:121 raise TypeError("%r takes 0 arguments" % self.__class__.__name__)118 raise TypeError(f"{self.__class__.__name__!r} takes 0 arguments")119 raise TypeError(123 "%r takes 0 or %d argument%s"124 % (125 self.__class__.__name__,126 len(self.fields),127 len(self.fields) != 1 and "s" or "",128 )120 f"{self.__class__.__name__!r} takes 0 or {len(self.fields)}"121 f" argument{'s' if len(self.fields) != 1 else ''}"122 )130 for name, arg in izip(self.fields, fields):123 for name, arg in zip(self.fields, fields):124 setattr(self, name, arg)125 for attr in self.attributes:126 setattr(self, attr, attributes.pop(attr, None))127 if attributes:135 raise TypeError("unknown attribute %r" % next(iter(attributes)))128 raise TypeError(f"unknown attribute {next(iter(attributes))!r}")129130 def iter_fields(self, exclude=None, only=None):131 """This method iterates over all fields that are defined and yields132 ``(key, value)`` tuples. Per default all fields are returned, but
38 unmodified lines
171 """172 for child in self.iter_child_nodes():173 if isinstance(child, node_type):174 yield child182 for result in child.find_all(node_type):183 yield result175 yield from child.find_all(node_type)176177 def set_ctx(self, ctx):178 """Reset the context of a node and all child nodes. Per default the179 parser will all generate nodes that have a 'load' context as it's the
28 unmodified lines
208 todo.extend(node.iter_child_nodes())209 return self210211 def __eq__(self, other):220 return type(self) is type(other) and tuple(self.iter_fields()) == tuple(221 other.iter_fields()222 )212 if type(self) is not type(other):213 return NotImplemented214224 def __ne__(self, other):225 return not self.__eq__(other)215 return tuple(self.iter_fields()) == tuple(other.iter_fields())216227 # Restore Python 2 hashing behavior on Python 3228 __hash__ = object.__hash__217 def __hash__(self):218 return hash(tuple(self.iter_fields()))219220 def __repr__(self):231 return "%s(%s)" % (232 self.__class__.__name__,233 ", ".join("%s=%r" % (arg, getattr(self, arg, None)) for arg in self.fields),234 )221 args_str = ", ".join(f"{a}={getattr(self, a, None)!r}" for a in self.fields)222 return f"{self.__class__.__name__}({args_str})"223224 def dump(self):225 def _dump(node):226 if not isinstance(node, Node):227 buf.append(repr(node))228 return229242 buf.append("nodes.%s(" % node.__class__.__name__)230 buf.append(f"nodes.{node.__class__.__name__}(")231 if not node.fields:232 buf.append(")")233 return234 for idx, field in enumerate(node.fields):
262 unmodified lines
497498 fields = ("value",)499500 def as_const(self, eval_ctx=None):513 rv = self.value514 if (515 PY2516 and type(rv) is text_type517 and self.environment.policies["compiler.ascii_str"]518 ):519 try:520 rv = rv.encode("ascii")521 except UnicodeError:522 pass523 return rv501 return self.value502503 @classmethod504 def from_untrusted(cls, value, lineno=None, environment=None):505 """Return a const object if the value is representable as
135 unmodified lines
641642 if eval_ctx.volatile or self.node is None:643 raise Impossible()644667 # we have to be careful here because we call filter_ below.668 # if this variable would be called filter, 2to3 would wrap the669 # call in a list because it is assuming we are talking about the670 # builtin filter function here which no longer returns a list in671 # python 3. because of that, do not rename filter_ to filter!645 filter_ = self.environment.filters.get(self.name)646647 if filter_ is None or getattr(filter_, "contextfilter", False) is True:648 raise Impossible()
111 unmodified lines
760 return slice(const(self.start), const(self.stop), const(self.step))761762763class Concat(Expr):791 """Concatenates the list of expressions provided after converting them to792 unicode.764 """Concatenates the list of expressions provided after converting765 them to strings.766 """767768 fields = ("nodes",)769770 def as_const(self, eval_ctx=None):771 eval_ctx = get_eval_context(self, eval_ctx)799 return "".join(text_type(x.as_const(eval_ctx)) for x in self.nodes)772 return "".join(str(x.as_const(eval_ctx)) for x in self.nodes)773774775class Compare(Expr):776 """Compares an expression with some other expressions. `ops` must be a
26 unmodified lines
803804 fields = ("op", "expr")805806834if __debug__:835 Operand.__doc__ += "\nThe following operators are available: " + ", ".join(836 sorted(837 "``%s``" % x838 for x in set(_binop_to_func) | set(_uaop_to_func) | set(_cmpop_to_func)839 )840 )841842807class Mul(BinExpr):808 """Multiplies the left with the right node."""809810 operator = "*"
242 unmodified lines
modified:src/jinja2/optimizer.py+1 added-2 removed
1# -*- coding: utf-8 -*-1"""The optimizer tries to constant fold expressions and modify the AST2in place so that it should be faster to evaluate.34Because the AST does not contain all the scoping information and the
17 unmodified lines
22 def __init__(self, environment):23 self.environment = environment2425 def generic_visit(self, node, *args, **kwargs):27 node = super(Optimizer, self).generic_visit(node, *args, **kwargs)26 node = super().generic_visit(node, *args, **kwargs)2728 # Do constant folding. Some other nodes besides Expr have29 # as_const, but folding them causes errors later on.30 if isinstance(node, nodes.Expr):
10 unmodified lines
modified:src/jinja2/parser.py+16 added-21 removed
1# -*- coding: utf-8 -*-1"""Parse tokens from the lexer into nodes for the compiler."""2from . import nodes4from ._compat import imap3from .exceptions import TemplateAssertionError4from .exceptions import TemplateSyntaxError5from .lexer import describe_token6from .lexer import describe_token_expr
25 unmodified lines
32 "mod": nodes.Mod,33}343538class Parser(object):36class Parser:37 """This is the central parsing class Jinja uses. It's passed to38 extensions and can be used to parse expressions or statements.39 """40
22 unmodified lines
6364 def _fail_ut_eof(self, name, end_token_stack, lineno):65 expected = []66 for exprs in end_token_stack:69 expected.extend(imap(describe_token_expr, exprs))67 expected.extend(map(describe_token_expr, exprs))68 if end_token_stack:69 currently_looking = " or ".join(72 "'%s'" % describe_token_expr(expr) for expr in end_token_stack[-1]70 map(repr, map(describe_token_expr, end_token_stack[-1]))71 )72 else:73 currently_looking = None7475 if name is None:76 message = ["Unexpected end of template."]77 else:80 message = ["Encountered unknown tag '%s'." % name]78 message = [f"Encountered unknown tag {name!r}."]7980 if currently_looking:81 if name is not None and name in expected:82 message.append(85 "You probably made a nesting mistake. Jinja "86 "is expecting this tag, but currently looking "87 "for %s." % currently_looking83 "You probably made a nesting mistake. Jinja is expecting this tag,"84 f" but currently looking for {currently_looking}."85 )86 else:87 message.append(91 "Jinja was looking for the following tags: "92 "%s." % currently_looking88 f"Jinja was looking for the following tags: {currently_looking}."89 )9091 if self._tag_stack:92 message.append(97 "The innermost block that needs to be "98 "closed is '%s'." % self._tag_stack[-1]93 "The innermost block that needs to be closed is"94 f" {self._tag_stack[-1]!r}."95 )9697 self.fail(" ".join(message), lineno)98
22 unmodified lines
121 def free_identifier(self, lineno=None):122 """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""123 self._last_identifier += 1124 rv = object.__new__(nodes.InternalName)129 nodes.Node.__init__(rv, "fi%d" % self._last_identifier, lineno=lineno)125 nodes.Node.__init__(rv, f"fi{self._last_identifier}", lineno=lineno)126 return rv127128 def parse_statement(self):129 """Parse a single statement."""
130 unmodified lines
260 # to jinja. we do not support hyphens in block names, so let's261 # raise a nicer error message in that case.262 if self.stream.current.type == "sub":263 self.fail(268 "Block names in Jinja have to be valid Python "269 "identifiers and may not contain hyphens, use an "270 "underscore instead."264 "Block names in Jinja have to be valid Python identifiers and may not"265 " contain hyphens, use an underscore instead."266 )267268 node.body = self.parse_statements(("name:endblock",), drop_needle=True)269 self.stream.skip_if("name:" + node.name)
159 unmodified lines
429 target = self.parse_primary()430 target.set_ctx("store")431 if not target.can_assign():432 self.fail(438 "can't assign to %r" % target.__class__.__name__.lower(), target.lineno433 f"can't assign to {target.__class__.__name__.lower()!r}", target.lineno434 )435 return target436437 def parse_expression(self, with_condexpr=True):
152 unmodified lines
590 node = self.parse_list()591 elif token.type == "lbrace":592 node = self.parse_dict()593 else:599 self.fail("unexpected '%s'" % describe_token(token), token.lineno)594 self.fail(f"unexpected {describe_token(token)!r}", token.lineno)595 return node596597 def parse_tuple(598 self,
53 unmodified lines
652 # nothing) in the spot of an expression would be an empty653 # tuple.654 if not explicit_parentheses:655 self.fail(661 "Expected an expression, got '%s'"662 % describe_token(self.stream.current)656 "Expected an expression,"657 f" got {describe_token(self.stream.current)!r}"658 )659660 return nodes.Tuple(args, "load", lineno=lineno)661
273 unmodified lines
modified:src/jinja2/runtime.py+88 added-183 removed
1# -*- coding: utf-8 -*-1"""The runtime functions and state used by compiled templates."""2import sys3from collections import abc4from itertools import chain5from types import MethodType67from markupsafe import escape # noqa: F4018from markupsafe import Markup9from markupsafe import soft_unicode9from markupsafe import soft_str1011from ._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_metaclass11from .exceptions import TemplateNotFound # noqa: F40112from .exceptions import TemplateRuntimeError # noqa: F40113from .exceptions import UndefinedError14from .nodes import EvalContext
14 unmodified lines
29 "missing",30 "concat",31 "escape",32 "markup_join",42 "unicode_join",43 "to_string",33 "str_join",34 "identity",35 "TemplateNotFound",36 "Namespace",37 "Undefined",38]3950#: 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_type405441def identity(x):42 """Returns its argument. Useful for certain things in the43 environment.44 """45 return x464748def markup_join(seq):63 """Concatenation that escapes if necessary and converts to unicode."""49 """Concatenation that escapes if necessary and converts to string."""50 buf = []65 iterator = imap(soft_unicode, seq)51 iterator = map(soft_str, seq)52 for arg in iterator:53 buf.append(arg)54 if hasattr(arg, "__html__"):69 return Markup(u"").join(chain(buf, iterator))55 return Markup("").join(chain(buf, iterator))56 return concat(buf)575859def str_join(seq):60 """Simple args to string conversion and concatenation."""61 return concat(map(str, seq))626364def unicode_join(seq):74 """Simple args to unicode conversion and concatenation."""75 return concat(imap(text_type, seq))65 import warnings6667 warnings.warn(68 "This template must be recompiled with at least Jinja 3.0, or"69 " it will fail in 3.1.",70 DeprecationWarning,71 stacklevel=2,72 )73 return str_join(seq)747576def new_context(77 environment,78 template_name,79 blocks,
13 unmodified lines
93 # if the parent is shared a copy should be created because94 # we don't want to modify the dict passed95 if shared:96 parent = dict(parent)99 for key, value in iteritems(locals):97 for key, value in locals.items():98 if value is not missing:99 parent[key] = value100 return environment.context_class(environment, parent, template_name, blocks)101102105class TemplateReference(object):103class TemplateReference:104 """The `self` in templates."""105106 def __init__(self, context):107 self.__context = context
2 unmodified lines
110 blocks = self.__context.blocks[name]111 return BlockReference(name, self.__context, blocks, 0)112113 def __repr__(self):116 return "<%s %r>" % (self.__class__.__name__, self.__context.name)114 return f"<{self.__class__.__name__} {self.__context.name!r}>"115116117def _get_func(x):118 return getattr(x, "__func__", x)
33 unmodified lines
152 return context.parent[key]153 return missing154155158class Context(with_metaclass(ContextMeta)):156@abc.Mapping.register157class Context(metaclass=ContextMeta):158 """The template context holds the variables of a template. It stores the159 values passed to the template and also the names the template exports.160 Creating instances is neither supported nor useful as it's created161 automatically at various stages of the template evaluation and should not
27 unmodified lines
189190 # create the initial mapping of blocks. Whenever template inheritance191 # takes place the runtime will update this mapping with the new blocks192 # from the template.194 self.blocks = dict((k, [v]) for k, v in iteritems(blocks))193 self.blocks = {k: [v] for k, v in blocks.items()}194195 # In case we detect the fast resolve mode we can set up an alias196 # here that bypasses the legacy code logic.197 if self._fast_resolve_mode:
6 unmodified lines
204 index = blocks.index(current) + 1205 blocks[index]206 except LookupError:207 return self.environment.undefined(209 "there is no parent block called %r." % name, name="super"208 f"there is no parent block called {name!r}.", name="super"209 )210 return BlockReference(name, self, blocks, index)211212 def get(self, key, default=None):
29 unmodified lines
242 return resolve_or_missing(self, key)243244 def get_exported(self):245 """Get a new dict with the exported variables."""247 return dict((k, self.vars[k]) for k in self.exported_vars)246 return {k: self.vars[k] for k in self.exported_vars}247248 def get_all(self):249 """Return the complete context as dict including the exported250 variables. For optimizations reasons this might not return an
37 unmodified lines
288 try:289 return __obj(*args, **kwargs)290 except StopIteration:291 return __self.environment.undefined(293 "value was undefined because "294 "a callable raised a "295 "StopIteration exception"292 "value was undefined because a callable raised a"293 " StopIteration exception"294 )295296 def derived(self, locals=None):297 """Internal helper function to create a derived context. This is
3 unmodified lines
301 context = new_context(302 self.environment, self.name, {}, self.get_all(), True, None, locals303 )304 context.eval_ctx = self.eval_ctx307 context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))305 context.blocks.update((k, list(v)) for k, v in self.blocks.items())306 return context307308 def _all(meth): # noqa: B902309 def proxy(self):
5 unmodified lines
315316 keys = _all("keys")317 values = _all("values")318 items = _all("items")321322 # not available on python 3323 if PY2:324 iterkeys = _all("iterkeys")325 itervalues = _all("itervalues")326 iteritems = _all("iteritems")319 del _all320321 def __contains__(self, name):322 return name in self.vars or name in self.parent
7 unmodified lines
330 raise KeyError(key)331 return item332333 def __repr__(self):342 return "<%s %s of %r>" % (343 self.__class__.__name__,344 repr(self.get_all()),345 self.name,346 )334 return f"<{self.__class__.__name__} {self.get_all()!r} of {self.name!r}>"335336349abc.Mapping.register(Context)350351352class BlockReference(object):337class BlockReference:338 """One block on a template reference."""339340 def __init__(self, name, context, stack, depth):341 self.name = name
5 unmodified lines
347 def super(self):348 """Super the block."""349 if self._depth + 1 >= len(self._stack):350 return self._context.environment.undefined(366 "there is no parent block called %r." % self.name, name="super"351 f"there is no parent block called {self.name!r}.", name="super"352 )353 return BlockReference(self.name, self._context, self._stack, self._depth + 1)354355 @internalcode
3 unmodified lines
359 rv = Markup(rv)360 return rv361362378@implements_iterator363class LoopContext:364 """A wrapper iterable for dynamic ``for`` loops, with information365 about the loop and iteration.366 """
180 unmodified lines
547548 return self._recurse(iterable, self._recurse, depth=self.depth)549550 def __repr__(self):567 return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)551 return f"<{self.__class__.__name__} {self.index}/{self.length}>"552553570class Macro(object):554class Macro:555 """Wraps a macro function."""556557 def __init__(558 self,
80 unmodified lines
639 arguments.append(kwargs)640 elif kwargs:641 if "caller" in kwargs:642 raise TypeError(659 "macro %r was invoked with two values for "660 "the special caller argument. This is "661 "most likely a bug." % self.name643 f"macro {self.name!r} was invoked with two values for the special"644 " caller argument. This is most likely a bug."645 )646 raise TypeError(664 "macro %r takes no keyword argument %r"665 % (self.name, next(iter(kwargs)))647 f"macro {self.name!r} takes no keyword argument {next(iter(kwargs))!r}"648 )649 if self.catch_varargs:650 arguments.append(args[self._argument_count :])651 elif len(args) > self._argument_count:652 raise TypeError(671 "macro %r takes not more than %d argument(s)"672 % (self.name, len(self.arguments))653 f"macro {self.name!r} takes not more than"654 f" {len(self.arguments)} argument(s)"655 )656657 return self._invoke(arguments, autoescape)658
4 unmodified lines
663 rv = Markup(rv)664 return rv665666 def __repr__(self):685 return "<%s %s>" % (686 self.__class__.__name__,687 self.name is None and "anonymous" or repr(self.name),688 )667 name = "anonymous" if self.name is None else repr(self.name)668 return f"<{self.__class__.__name__} {name}>"669670691@implements_to_string692class Undefined(object):671class Undefined:672 """The default undefined type. This undefined type can be printed and673 iterated over, but every other access will raise an :exc:`UndefinedError`:674675 >>> foo = Undefined(name='foo')
28 unmodified lines
704 if self._undefined_hint:705 return self._undefined_hint706707 if self._undefined_obj is missing:729 return "%r is undefined" % self._undefined_name708 return f"{self._undefined_name!r} is undefined"709731 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,710 if not isinstance(self._undefined_name, str):711 return (712 f"{object_type_repr(self._undefined_obj)} has no"713 f" element {self._undefined_name!r}"714 )715737 return "%r has no attribute %r" % (738 object_type_repr(self._undefined_obj),739 self._undefined_name,716 return (717 f"{object_type_repr(self._undefined_obj)!r} has no"718 f" attribute {self._undefined_name!r}"719 )720721 @internalcode722 def _fail_with_undefined_error(self, *args, **kwargs):
7 unmodified lines
730 if name[:2] == "__":731 raise AttributeError(name)732 return self._fail_with_undefined_error()733755 __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_error734 __add__ = __radd__ = __sub__ = __rsub__ = _fail_with_undefined_error735 __mul__ = __rmul__ = __div__ = __rdiv__ = _fail_with_undefined_error736 __truediv__ = __rtruediv__ = _fail_with_undefined_error737 __floordiv__ = __rfloordiv__ = _fail_with_undefined_error738 __mod__ = __rmod__ = _fail_with_undefined_error739 __pos__ = __neg__ = _fail_with_undefined_error740 __call__ = __getitem__ = _fail_with_undefined_error741 __lt__ = __le__ = __gt__ = __ge__ = _fail_with_undefined_error742 __int__ = __float__ = __complex__ = _fail_with_undefined_error743 __pow__ = __rpow__ = _fail_with_undefined_error744745 def __eq__(self, other):746 return type(self) is type(other)747
3 unmodified lines
751 def __hash__(self):752 return id(type(self))753754 def __str__(self):811 return u""755 return ""756757 def __len__(self):758 return 0759760 def __iter__(self):761 if 0:762 yield None763820 def __nonzero__(self):764 def __bool__(self):765 return False766823 __bool__ = __nonzero__824767 def __repr__(self):768 return "Undefined"769770
25 unmodified lines
796 if base is None:797 base = Undefined798799 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)800 logger.warning("Template variable warning: %s", undef._undefined_message)801802 class LoggingUndefined(base):803 def _fail_with_undefined_error(self, *args, **kwargs):804 try:878 return base._fail_with_undefined_error(self, *args, **kwargs)805 return super()._fail_with_undefined_error(*args, **kwargs)806 except self._undefined_exception as e:880 logger.error("Template variable error: %s", str(e))807 logger.error(f"Template variable error: %s", e)808 raise e809810 def __str__(self):884 rv = base.__str__(self)811 _log_message(self)886 return rv812 return super().__str__()813814 def __iter__(self):889 rv = base.__iter__(self)815 _log_message(self)891 return rv816 return super().__iter__()817893 if PY2:818 def __bool__(self):819 _log_message(self)820 return super().__bool__()821895 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 rv911822 return LoggingUndefined823824915# 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.825class ChainableUndefined(Undefined):826 """An undefined that is chainable, where both ``__getattr__`` and827 ``__getitem__`` return itself rather than raising an828 :exc:`UndefinedError`.
19 unmodified lines
848849 __getitem__ = __getattr__850851945@implements_to_string852class DebugUndefined(Undefined):853 """An undefined that returns the debug info when printed.854855 >>> foo = DebugUndefined(name='foo')
9 unmodified lines
865866 __slots__ = ()867868 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,869 if self._undefined_hint:870 message = f"undefined value printed: {self._undefined_hint}"871872 elif self._undefined_obj is missing:873 message = self._undefined_name874875 else:876 message = (877 f"no such element: {object_type_repr(self._undefined_obj)}"878 f"[{self._undefined_name!r}]"879 )970 return u"{{ undefined value printed: %s }}" % self._undefined_hint880881 return f"{{{{ {message} }}}}"882973@implements_to_string883884class StrictUndefined(Undefined):885 """An undefined that barks on print and iteration as well as boolean886 tests and all kinds of comparisons. In other words: you can do nothing887 with it except checking if it's defined using the `defined` test.
13 unmodified lines
901 jinja2.exceptions.UndefinedError: 'foo' is undefined902 """903904 __slots__ = ()995 __iter__ = (996 __str__997 ) = (998 __len__999 ) = (1000 __nonzero__1001 ) = __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error905 __iter__ = __str__ = __len__ = Undefined._fail_with_undefined_error906 __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error9079081004# remove remaining slots attributes, after the metaclass did the magic they1005# are unneeded and irritating as they contain wrong data for the subclasses.909# Remove slots attributes, after the metaclass is applied they are910# unneeded and contain wrong data for subclasses.911del (912 Undefined.__slots__,913 ChainableUndefined.__slots__,914 DebugUndefined.__slots__,
2 unmodified lines
modified:src/jinja2/sandbox.py+23 added-82 removed
1# -*- coding: utf-8 -*-1"""A sandbox layer that ensures unsafe operations cannot be performed.2Useful when the template itself comes from an untrusted source.3"""4import operator5import types7import warnings6from _string import formatter_field_name_split7from collections import abc8from collections import deque9from string import Formatter1011from markupsafe import EscapeFormatter12from markupsafe import Markup1314from ._compat import abc15from ._compat import PY216from ._compat import range_type17from ._compat import string_types14from .environment import Environment15from .exceptions import SecurityError1617#: maximum number of items a range may produce18MAX_RANGE = 1000001924#: 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()20#: Unsafe function attributes.21UNSAFE_FUNCTION_ATTRIBUTES = set()2238#: unsafe method attributes. function attributes are unsafe for methods too39UNSAFE_METHOD_ATTRIBUTES = {"im_class", "im_func", "im_self"}23#: Unsafe method attributes. Function attributes are unsafe for methods too.24UNSAFE_METHOD_ATTRIBUTES = set()2526#: unsafe generator attributes.27UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}28
2 unmodified lines
3132#: unsafe attributes on async generators33UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}3450# 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,)8135_mutable_spec = (36 (84 _mutable_set_types,37 abc.MutableSet,38 frozenset(39 [40 "add",41 "clear",
6 unmodified lines
48 ]49 ),50 ),51 (99 _mutable_mapping_types,52 abc.MutableMapping,53 frozenset(["clear", "pop", "popitem", "setdefault", "update"]),54 ),55 (103 _mutable_sequence_types,56 abc.MutableSequence,57 frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),58 ),59 (60 deque,
50 unmodified lines
111 callable, (types.MethodType, types.BuiltinMethodType)112 ) or callable.__name__ not in ("format", "format_map"):113 return None114 obj = callable.__self__162 if isinstance(obj, string_types):115 if isinstance(obj, str):116 return obj117118119def safe_range(*args):120 """A range that can't generate ranges with a length of more than121 MAX_RANGE items.122 """170 rng = range_type(*args)123 rng = range(*args)124125 if len(rng) > MAX_RANGE:126 raise OverflowError(127 "Range too big. The sandbox blocks ranges larger than"175 " MAX_RANGE (%d)." % MAX_RANGE128 f" MAX_RANGE ({MAX_RANGE})."129 )130131 return rng132133134def unsafe(f):135 """Marks a function or method as unsafe.136184 ::137 .. code-block: python138139 @unsafe140 def delete(self):141 pass
40 unmodified lines
182183184def modifies_known_mutable(obj, attr):185 """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`.186 (list, dict, set or deque) or the corresponding ABCs would modify it187 if called.188189 >>> modifies_known_mutable({}, "clear")190 True191 >>> modifies_known_mutable({}, "keys")
2 unmodified lines
194 True195 >>> modifies_known_mutable([], "index")196 False197247 If called with an unsupported object (such as unicode) `False` is248 returned.198 If called with an unsupported object, ``False`` is returned.199200 >>> modifies_known_mutable("foo", "upper")201 False202 """
129 unmodified lines
332 """Subscribe an object from sandboxed code."""333 try:334 return obj[argument]335 except (TypeError, LookupError):386 if isinstance(argument, string_types):336 if isinstance(argument, str):337 try:338 attr = str(argument)339 except Exception:340 pass
27 unmodified lines
368369 def unsafe_undefined(self, obj, attribute):370 """Return an undefined object for unsafe attributes."""371 return self.undefined(422 "access to attribute %r of %r "423 "object is unsafe." % (attribute, obj.__class__.__name__),372 f"access to attribute {attribute!r} of"373 f" {obj.__class__.__name__!r} object is unsafe.",374 name=attribute,375 obj=obj,376 exc=SecurityError,377 )
9 unmodified lines
387388 if format_func is not None and format_func.__name__ == "format_map":389 if len(args) != 1 or kwargs:390 raise TypeError(441 "format_map() takes exactly one argument %d given"442 % (len(args) + (kwargs is not None))391 "format_map() takes exactly one argument"392 f" {len(args) + (kwargs is not None)} given"393 )394395 kwargs = args[0]396 args = None
10 unmodified lines
407408 # the double prefixes are to avoid double keyword argument409 # errors when proxying the call.410 if not __self.is_safe_callable(__obj):461 raise SecurityError("%r is not safely callable" % (__obj,))411 raise SecurityError(f"{__obj!r} is not safely callable")412 return __context.call(__obj, *args, **kwargs)413414415class ImmutableSandboxedEnvironment(SandboxedEnvironment):
7 unmodified lines
423 return False424 return not modifies_known_mutable(obj, attr)425426477# 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):427class SandboxedFormatterMixin:428 def __init__(self, env):429 self._env = env430431 def get_field(self, field_name, args, kwargs):
20 unmodified lines
modified:src/jinja2/tests.py+7 added-11 removed
1# -*- coding: utf-8 -*-1"""Built-in template tests used with the ``is`` operator."""3import decimal2import operator3import re4from collections import abc5from numbers import Number67from ._compat import abc8from ._compat import integer_types9from ._compat import string_types10from ._compat import text_type7from .runtime import Undefined89number_re = re.compile(r"^-?\d+(\.\d+)?$")10regex_type = type(number_re)
71 unmodified lines
82 """Return true if the object is an integer.8384 .. versionadded:: 2.1185 """90 return isinstance(value, integer_types) and value is not True and value is not False86 return isinstance(value, int) and value is not True and value is not False878889# NOTE: The existing 'number' test matches booleans and integers90def test_float(value):
5 unmodified lines
969798def test_lower(value):99 """Return true if the variable is lowercased."""104 return text_type(value).islower()100 return str(value).islower()101102103def test_upper(value):104 """Return true if the variable is uppercased."""109 return text_type(value).isupper()105 return str(value).isupper()106107108def test_string(value):109 """Return true if the object is a string."""114 return isinstance(value, string_types)110 return isinstance(value, str)111112113def test_mapping(value):114 """Return true if the object is a mapping (dict etc.).
4 unmodified lines
119120121def test_number(value):122 """Return true if the variable is a number."""127 return isinstance(value, integer_types + (float, complex, decimal.Decimal))123 return isinstance(value, Number)124125126def test_sequence(value):127 """Return true if the variable is a sequence. Sequences are variables
84 unmodified lines
modified:src/jinja2/utils.py+64 added-127 removed
1# -*- coding: utf-8 -*-1import json2import os3import re5import warnings4from collections import abc5from collections import deque6from random import choice7from random import randrange8from threading import Lock9from urllib.parse import quote_from_bytes1011from markupsafe import escape12from markupsafe import Markup1314from ._compat import abc15from ._compat import string_types16from ._compat import text_type17from ._compat import url_quote1814_word_split_re = re.compile(r"(\s+)")15_lead_pattern = "|".join(map(re.escape, ("(", "<", "&lt;")))16_trail_pattern = "|".join(map(re.escape, (".", ",", ")", ">", "\n", "&gt;")))17_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 )18 fr"^(?P<lead>(?:{_lead_pattern})*)(?P<middle>.*?)(?P<trail>(?:{_trail_pattern})*)$"19)20_simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")21_striptags_re = re.compile(r"(<!--.*?-->|<[^>]*>)")22_entity_re = re.compile(r"&([^;]+);")
5 unmodified lines
2829# internal code30internal_code = set()3139concat = u"".join32concat = "".join3334_slash_escape = "\\/" not in json.dumps("/")3536
124 unmodified lines
161 # __builtin__ in 2.x, builtins in 3.x162 if obj.__class__.__module__ in ("__builtin__", "builtins"):163 name = obj.__class__.__name__164 else:172 name = obj.__class__.__module__ + "." + obj.__class__.__name__173 return "%s object" % name165 name = f"{obj.__class__.__module__}.{obj.__class__.__name__}"166 return f"{name} object"167168176def pformat(obj, verbose=False):177 """Prettyprint an object. Either use the `pretty` library or the178 builtin `pprint`.169def pformat(obj):170 """Format an object using :func:`pprint.pformat`.171 """180 try:181 from pretty import pretty172 from pprint import pformat173183 return pretty(obj, verbose=verbose)184 except ImportError:185 from pprint import pformat174 return pformat(obj)175187 return pformat(obj)176189177def urlize(text, trim_url_limit=None, rel=None, target=None):178 """Converts any URLs in text into clickable links. Works on http://,179 https:// and www. links. Links can have trailing punctuation (periods,180 commas, close-parens) and leading punctuation (opening parens) and
6 unmodified lines
187 attribute.188189 If target is not None, a target attribute will be added to the link.190 """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 ""191192 def trim_url(x, limit=trim_url_limit):193 if limit is not None:194 return x[:limit] + ("..." if len(x) >= limit else "")195196 return x197198 words = _word_split_re.split(str(escape(text)))199 rel_attr = f' rel="{escape(rel)}"' if rel else ""200 target_attr = f' target="{escape(target)}"' if target else ""201202 for i, word in enumerate(words):203 match = _punctuation_re.match(word)204 if match:205 lead, middle, trail = match.groups()
8 unmodified lines
214 or middle.endswith(".net")215 or middle.endswith(".com")216 )217 ):229 middle = '<a href="http://%s"%s%s>%s</a>' % (230 middle,231 rel_attr,232 target_attr,233 trim_url(middle),218 middle = (219 f'<a href="http://{middle}"{rel_attr}{target_attr}>'220 f"{trim_url(middle)}</a>"221 )222 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),223 middle = (224 f'<a href="{middle}"{rel_attr}{target_attr}>{trim_url(middle)}</a>'225 )226 if (227 "@" in middle228 and not middle.startswith("www.")229 and ":" not in middle230 and _simple_email_re.match(middle)231 ):248 middle = '<a href="mailto:%s">%s</a>' % (middle, middle)232 middle = f'<a href="mailto:{middle}">{middle}</a>'233 if lead + middle + trail != word:234 words[i] = lead + middle + trail251 return u"".join(words)235 return "".join(words)236237238def generate_lorem_ipsum(n=5, html=True, min=20, max=100):239 """Generate some lorem ipsum for the template."""
31 unmodified lines
271 next_capitalized = True272 p.append(word)273274 # ensure that the paragraph ends with a dot.291 p = u" ".join(p)275 p = " ".join(p)276 if p.endswith(","):277 p = p[:-1] + "."278 elif not p.endswith("."):279 p += "."280 result.append(p)281282 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))283 return "\n\n".join(result)284 return Markup("\n".join(f"<p>{escape(x)}</p>" for x in result))285286303def unicode_urlencode(obj, charset="utf-8", for_qs=False):287def url_quote(obj, charset="utf-8", for_qs=False):288 """Quote a string for use in a URL using the given charset.289290 This function is misnamed, it is a wrapper around291 :func:`urllib.parse.quote`.
2 unmodified lines
294 string then encoded to bytes using the given charset.295 :param charset: Encode text to bytes using this charset.296 :param for_qs: Quote "/" and use "+" for spaces.297 """314 if not isinstance(obj, string_types):315 obj = text_type(obj)298 if not isinstance(obj, bytes):299 if not isinstance(obj, str):300 obj = str(obj)301317 if isinstance(obj, text_type):302 obj = obj.encode(charset)303304 safe = b"" if for_qs else b"/"321 rv = url_quote(obj, safe)305 rv = quote_from_bytes(obj, safe)306323 if not isinstance(rv, text_type):324 rv = rv.decode("utf-8")325307 if for_qs:308 rv = rv.replace("%20", "+")309310 return rv311312313def unicode_urlencode(obj, charset="utf-8", for_qs=False):314 import warnings315316 warnings.warn(317 "'unicode_urlencode' has been renamed to 'url_quote'. The old"318 " name will be removed in version 3.1.",319 DeprecationWarning,320 stacklevel=2,321 )322 return url_quote(obj, charset=charset, for_qs=for_qs)323324325@abc.MutableMapping.register332class LRUCache(object):326class LRUCache:327 """A simple LRU Cache implementation."""328329 # this is fast for small capacities (something below 1000) but doesn't330 # scale. But as long as it's only used as storage for templates this
68 unmodified lines
399 """Return the current size of the cache."""400 return len(self._mapping)401402 def __repr__(self):409 return "<%s %r>" % (self.__class__.__name__, self._mapping)403 return f"<{self.__class__.__name__} {self._mapping!r}>"404405 def __getitem__(self, key):406 """Get an item from the cache. Moves the item up so that it has the407 highest priority then.
50 unmodified lines
458 result = [(key, self._mapping[key]) for key in list(self._queue)]459 result.reverse()460 return result461468 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())477462 def values(self):463 """Return a list of all values."""464 return [x[1] for x in self.items()]465482 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())501466 def keys(self):467 """Return a list of all keys ordered by most recent usage."""468 return list(self)469506 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)517470 def __iter__(self):471 return reversed(tuple(self._queue))472473 def __reversed__(self):
4 unmodified lines
478479 __copy__ = copy480481530abc.MutableMapping.register(LRUCache)531532482def select_autoescape(483 enabled_extensions=("html", "htm", "xml"),484 disabled_extensions=(),485 default_for_string=True,
32 unmodified lines
518 For security reasons this function operates case insensitive.519520 .. versionadded:: 2.9521 """573 enabled_patterns = tuple("." + x.lstrip(".").lower() for x in enabled_extensions)574 disabled_patterns = tuple("." + x.lstrip(".").lower() for x in disabled_extensions)522 enabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in enabled_extensions)523 disabled_patterns = tuple(f".{x.lstrip('.').lower()}" for x in disabled_extensions)524525 def autoescape(template_name):526 if template_name is None:527 return default_for_string
28 unmodified lines
556 if dumper is None:557 dumper = json.dumps558 rv = (559 dumper(obj, **kwargs)611 .replace(u"<", u"\\u003c")612 .replace(u">", u"\\u003e")613 .replace(u"&", u"\\u0026")614 .replace(u"'", u"\\u0027")560 .replace("<", "\\u003c")561 .replace(">", "\\u003e")562 .replace("&", "\\u0026")563 .replace("'", "\\u0027")564 )565 return Markup(rv)566567619class Cycler(object):568class Cycler:569 """Cycle through values by yield them one at a time, then restarting570 once the end is reached. Available as ``cycler`` in templates.571572 Similar to ``loop.cycle``, but can be used outside loops or across
45 unmodified lines
618619 __next__ = next620621673class Joiner(object):622class Joiner:623 """A joining helper for templates."""624676 def __init__(self, sep=u", "):625 def __init__(self, sep=", "):626 self.sep = sep627 self.used = False628629 def __call__(self):630 if not self.used:631 self.used = True683 return u""632 return ""633 return self.sep634635687class Namespace(object):636class Namespace:637 """A namespace object that can hold arbitrary attributes. It may be638 initialized from a dictionary or with keyword arguments."""639640 def __init__(*args, **kwargs): # noqa: B902
11 unmodified lines
652 def __setitem__(self, name, value):653 self.__attrs[name] = value654655 def __repr__(self):707 return "<Namespace %r>" % self.__attrs656 return f"<Namespace {self.__attrs!r}>"657658659# does this python version support async for in and async generators?660try:661 exec("async def _():\n async for _ in ():\n yield _")662 have_async_gen = True663except SyntaxError:664 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)
modified:src/jinja2/visitor.py+2 added-4 removed
1# -*- coding: utf-8 -*-1"""API for traversing the AST nodes. Implemented by the compiler and2meta introspection.3"""4from .nodes import Node568class NodeVisitor(object):7class NodeVisitor:8 """Walks the abstract syntax tree and call visitor functions for every9 node found. The visitor functions may return values which will be10 forwarded by the `visit` method.11
8 unmodified lines
20 """Return the visitor function for this node or `None` if no visitor21 exists for this node. In that case the generic visit function is22 used instead.23 """25 method = "visit_" + node.__class__.__name__26 return getattr(self, method, None)24 return getattr(self, f"visit_{node.__class__.__name__}", None)2526 def visit(self, node, *args, **kwargs):27 """Visit a node."""28 f = self.get_visitor(node)
51 unmodified lines
modified:tests/conftest.py-1 removed
1# -*- coding: utf-8 -*-1import os23import pytest4
96 unmodified lines
modified:tests/test_api.py+26 added-30 removed
1# -*- coding: utf-8 -*-1import os2import shutil3import tempfile4
20 unmodified lines
252627@pytest.mark.api28@pytest.mark.extended30class TestExtendedAPI(object):29class TestExtendedAPI:30 def test_item_and_attribute(self, env):31 from jinja2.sandbox import SandboxedEnvironment3233 for env in Environment(), SandboxedEnvironment():35 # the |list is necessary for python334 tmpl = env.from_string("{{ foo.items()|list }}")35 assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"36 tmpl = env.from_string('{{ foo|attr("items")()|list }}')37 assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"
124 unmodified lines
162163164@pytest.mark.api165@pytest.mark.meta168class TestMeta(object):166class TestMeta:167 def test_find_undeclared_variables(self, env):168 ast = env.parse("{% set foo = 42 %}{{ bar + foo }}")169 x = meta.find_undeclared_variables(ast)172 assert x == set(["bar"])170 assert x == {"bar"}171172 ast = env.parse(173 "{% set foo = 42 %}{{ bar + foo }}"174 "{% macro meh(x) %}{{ x }}{% endmacro %}"175 "{% for item in seq %}{{ muh(item) + meh(seq) }}"176 "{% endfor %}"177 )178 x = meta.find_undeclared_variables(ast)181 assert x == set(["bar", "seq", "muh"])179 assert x == {"bar", "seq", "muh"}180181 ast = env.parse("{% for x in range(5) %}{{ x }}{% endfor %}{{ foo }}")182 x = meta.find_undeclared_variables(ast)185 assert x == set(["foo"])183 assert x == {"foo"}184185 def test_find_refererenced_templates(self, env):186 ast = env.parse('{% extends "layout.html" %}{% include helper %}')187 i = meta.find_referenced_templates(ast)
29 unmodified lines
217218219@pytest.mark.api220@pytest.mark.streaming223class TestStreaming(object):221class TestStreaming:222 def test_basic_streaming(self, env):223 t = env.from_string(224 "<ul>{% for item in seq %}<li>{{ loop.index }} - {{ item }}</li>"225 "{%- endfor %}</ul>"
8 unmodified lines
234 "{%- endfor %}</ul>"235 )236 stream = tmpl.stream(seq=list(range(3)))237 stream.enable_buffering(size=3)240 assert next(stream) == u"<ul><li>1"241 assert next(stream) == u" - 0</li>"238 assert next(stream) == "<ul><li>1"239 assert next(stream) == " - 0</li>"240241 def test_streaming_behavior(self, env):242 tmpl = env.from_string("")243 stream = tmpl.stream()
5 unmodified lines
249250 def test_dump_stream(self, env):251 tmp = tempfile.mkdtemp()252 try:255 tmpl = env.from_string(u"\u2713")253 tmpl = env.from_string("\u2713")254 stream = tmpl.stream()255 stream.dump(os.path.join(tmp, "dump.txt"), "utf-8")256 with open(os.path.join(tmp, "dump.txt"), "rb") as f:257 assert f.read() == b"\xe2\x9c\x93"
2 unmodified lines
260261262@pytest.mark.api263@pytest.mark.undefined266class TestUndefined(object):264class TestUndefined:265 def test_stopiteration_is_undefined(self):266 def test():267 raise StopIteration()268
8 unmodified lines
277278 def test_logging_undefined(self):279 _messages = []280283 class DebugLogger(object):281 class DebugLogger:282 def warning(self, msg, *args):283 _messages.append("W:" + msg % args)284285 def error(self, msg, *args):286 _messages.append("E:" + msg % args)287288 logging_undefined = make_logging_undefined(DebugLogger())289 env = Environment(undefined=logging_undefined)292 assert env.from_string("{{ missing }}").render() == u""290 assert env.from_string("{{ missing }}").render() == ""291 pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)292 assert env.from_string("{{ missing|list }}").render() == "[]"293 assert env.from_string("{{ missing is not defined }}").render() == "True"294 assert env.from_string("{{ foo.missing }}").render(foo=42) == ""295 assert env.from_string("{{ not missing }}").render() == "True"296 assert _messages == [299 "W:Template variable warning: missing is undefined",297 "W:Template variable warning: 'missing' is undefined",298 "E:Template variable error: 'missing' is undefined",301 "W:Template variable warning: missing is undefined",302 "W:Template variable warning: int object has no attribute missing",303 "W:Template variable warning: missing is undefined",299 "W:Template variable warning: 'missing' is undefined",300 "W:Template variable warning: 'int object' has no attribute 'missing'",301 "W:Template variable warning: 'missing' is undefined",302 ]303304 def test_default_undefined(self):305 env = Environment(undefined=Undefined)308 assert env.from_string("{{ missing }}").render() == u""306 assert env.from_string("{{ missing }}").render() == ""307 pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)308 assert env.from_string("{{ missing|list }}").render() == "[]"309 assert env.from_string("{{ missing is not defined }}").render() == "True"310 assert env.from_string("{{ foo.missing }}").render(foo=42) == ""
9 unmodified lines
320321 def test_chainable_undefined(self):322 env = Environment(undefined=ChainableUndefined)323 # The following tests are copied from test_default_undefined326 assert env.from_string("{{ missing }}").render() == u""324 assert env.from_string("{{ missing }}").render() == ""325 assert env.from_string("{{ missing|list }}").render() == "[]"326 assert env.from_string("{{ missing is not defined }}").render() == "True"327 assert env.from_string("{{ foo.missing }}").render(foo=42) == ""328 assert env.from_string("{{ not missing }}").render() == "True"
1 unmodified line
330 with pytest.raises(AttributeError):331 getattr(ChainableUndefined, "__slots__") # noqa: B009332333 # The following tests ensure subclass functionality works as expected336 assert env.from_string('{{ missing.bar["baz"] }}').render() == u""334 assert env.from_string('{{ missing.bar["baz"] }}').render() == ""335 assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == "foo"336 assert (338 env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == u"foo"339 )340 assert (337 env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(foo=42)342 == u"bar"338 == "bar"339 )340 assert (341 env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(342 foo={"bar": 42}343 )348 == u"baz"344 == "baz"345 )346347 def test_debug_undefined(self):348 env = Environment(undefined=DebugUndefined)
2 unmodified lines
351 assert env.from_string("{{ missing|list }}").render() == "[]"352 assert env.from_string("{{ missing is not defined }}").render() == "True"353 assert (354 env.from_string("{{ foo.missing }}").render(foo=42)359 == u"{{ no such element: int object['missing'] }}"355 == "{{ no such element: int object['missing'] }}"356 )357 assert env.from_string("{{ not missing }}").render() == "True"358 undefined_hint = "this is testing undefined hint of DebugUndefined"359 assert (360 str(DebugUndefined(hint=undefined_hint))365 == u"{{ undefined value printed: %s }}" % undefined_hint361 == f"{{{{ undefined value printed: {undefined_hint} }}}}"362 )363 with pytest.raises(AttributeError):364 getattr(DebugUndefined, "__slots__") # noqa: B009365
31 unmodified lines
397398399@pytest.mark.api400@pytest.mark.lowlevel405class TestLowLevel(object):401class TestLowLevel:402 def test_custom_code_generator(self):403 class CustomCodeGenerator(CodeGenerator):404 def visit_Const(self, node, frame=None):405 # This method is pure nonsense, but works fine for testing...406 if node.value == "foo":407 self.write(repr("bar"))408 else:413 super(CustomCodeGenerator, self).visit_Const(node, frame)409 super().visit_Const(node, frame)410411 class CustomEnvironment(Environment):412 code_generator_class = CustomCodeGenerator413
15 unmodified lines
modified:tests/test_async.py+4 added-5 removed
129 unmodified lines
130 return env131132133@pytest.mark.imports134class TestAsyncImports(object):134class TestAsyncImports:135 def test_context_imports(self, test_env_async):136 t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}')137 assert t.render(foo=42) == "[|23]"138 t = test_env_async.from_string(
42 unmodified lines
181182183@pytest.mark.imports184@pytest.mark.includes185class TestAsyncIncludes(object):185class TestAsyncIncludes:186 def test_context_include(self, test_env_async):187 t = test_env_async.from_string('{% include "header" %}')188 assert t.render(foo=42) == "[42|23]"189 t = test_env_async.from_string('{% include "header" with context %}')
90 unmodified lines
280281282@pytest.mark.core_tags283@pytest.mark.for_loop284class TestAsyncForLoop(object):284class TestAsyncForLoop:285 def test_simple(self, test_env_async):286 tmpl = test_env_async.from_string("{% for item in seq %}{{ item }}{% endfor %}")287 assert tmpl.render(seq=list(range(10))) == "0123456789"288
55 unmodified lines
344 assert not output345346 def test_varlen(self, test_env_async):347 def inner():348 for item in range(5):349 yield item348 yield from range(5)349350 tmpl = test_env_async.from_string(351 "{% for item in iter %}{{ item }}{% endfor %}"352 )
232 unmodified lines
modified:tests/test_bytecode_cache.py+3 added-4 removed
1# -*- coding: utf-8 -*-1import pytest23from jinja2 import Environment4from jinja2.bccache import Bucket
8 unmodified lines
13 return Environment(loader=package_loader, bytecode_cache=bytecode_cache)141516@pytest.mark.byte_code_cache18class TestByteCodeCache(object):17class TestByteCodeCache:18 def test_simple(self, env):19 tmpl = env.get_template("test.html")20 assert tmpl.render().strip() == "BAR"21 pytest.raises(TemplateNotFound, env.get_template, "missing.html")222325class MockMemcached(object):24class MockMemcached:25 class Error(Exception):26 pass2728 key = None
14 unmodified lines
43 def set_side_effect(self, *args):44 raise self.Error()454648class TestMemcachedBytecodeCache(object):47class TestMemcachedBytecodeCache:48 def test_dump_load(self):49 memcached = MockMemcached()50 m = MemcachedBytecodeCache(memcached)51
27 unmodified lines
modified:tests/test_core_tags.py+11 added-18 removed
1# -*- coding: utf-8 -*-1import pytest23from jinja2 import DictLoader4from jinja2 import Environment
8 unmodified lines
131415@pytest.mark.core_tags16@pytest.mark.for_loop18class TestForLoop(object):17class TestForLoop:18 def test_simple(self, env):19 tmpl = env.from_string("{% for item in seq %}{{ item }}{% endfor %}")20 assert tmpl.render(seq=list(range(10))) == "0123456789"21
79 unmodified lines
101 output = tmpl.render(seq=list(range(10)))102 assert not output103104 def test_varlen(self, env):106 def inner():107 for item in range(5):108 yield item109105 tmpl = env.from_string("{% for item in iter %}{{ item }}{% endfor %}")111 output = tmpl.render(iter=inner())106 output = tmpl.render(iter=range(5))107 assert output == "01234"108109 def test_noniter(self, env):110 tmpl = env.from_string("{% for item in none %}...{% endfor %}")
190 unmodified lines
301302303@pytest.mark.core_tags304@pytest.mark.if_condition310class TestIfCondition(object):305class TestIfCondition:306 def test_simple(self, env):307 tmpl = env.from_string("""{% if true %}...{% endif %}""")308 assert tmpl.render() == "..."309
4 unmodified lines
314 )315 assert tmpl.render() == "..."316317 def test_elif_deep(self, env):323 elifs = "\n".join("{{% elif a == {0} %}}{0}".format(i) for i in range(1, 1000))324 tmpl = env.from_string(325 "{{% if a == 0 %}}0{0}{{% else %}}x{{% endif %}}".format(elifs)326 )318 elifs = "\n".join(f"{{% elif a == {i} %}}{i}" for i in range(1, 1000))319 tmpl = env.from_string(f"{{% if a == 0 %}}0{elifs}{{% else %}}x{{% endif %}}")320 for x in (0, 10, 999):321 assert tmpl.render(a=x).strip() == str(x)322 assert tmpl.render(a=1000).strip() == "x"323
19 unmodified lines
343344345@pytest.mark.core_tags346@pytest.mark.macros354class TestMacros(object):347class TestMacros:348 def test_simple(self, env_trim):349 tmpl = env_trim.from_string(350 """\351{% macro say_hello(name) %}Hello {{ name }}!{% endmacro %}
117 unmodified lines
469470471@pytest.mark.core_tags472@pytest.mark.set480class TestSet(object):473class TestSet:474 def test_normal(self, env_trim):475 tmpl = env_trim.from_string("{% set foo = 1 %}{{ foo }}")476 assert tmpl.render() == "1"477 assert tmpl.module.foo == 1478479 def test_block(self, env_trim):480 tmpl = env_trim.from_string("{% set foo %}42{% endset %}{{ foo }}")481 assert tmpl.render() == "42"489 assert tmpl.module.foo == u"42"482 assert tmpl.module.foo == "42"483484 def test_block_escaping(self):485 env = Environment(autoescape=True)486 tmpl = env.from_string(
70 unmodified lines
557 tmpl = env_trim.from_string(558 "{% set foo | trim | length | string %} 42 {% endset %}{{ foo }}"559 )560 assert tmpl.render() == "2"568 assert tmpl.module.foo == u"2"561 assert tmpl.module.foo == "2"562563 def test_block_filtered_set(self, env_trim):564 def _myfilter(val, arg):565 assert arg == " xxx "
7 unmodified lines
573 "{% endset %}"574 "{{ foo }}"575 )576 assert tmpl.render() == "11"584 assert tmpl.module.foo == u"11"577 assert tmpl.module.foo == "11"578579580@pytest.mark.core_tags581@pytest.mark.with_589class TestWith(object):582class TestWith:583 def test_with(self, env):584 tmpl = env.from_string(585 """\586 {% with a=42, b=23 -%}
19 unmodified lines
modified:tests/test_debug.py+4 added-6 removed
1# -*- coding: utf-8 -*-1import pickle2import re3from traceback import format_exception4
11 unmodified lines
16 return Environment(loader=filesystem_loader)171819@pytest.mark.debug21class TestDebug(object):20class TestDebug:21 def assert_traceback_matches(self, callback, expected_tb):22 with pytest.raises(Exception) as exc_info:23 callback()2425 tb = format_exception(exc_info.type, exc_info.value, exc_info.tb)26 m = re.search(expected_tb.strip(), "".join(tb))28 assert m is not None, "Traceback did not match:\n\n%s\nexpected:\n%s" % (29 "".join(tb),30 expected_tb,31 )27 assert (28 m is not None29 ), "Traceback did not match:\n\n{''.join(tb)}\nexpected:\n{expected_tb}"3031 def test_runtime_error(self, fs_env):32 def test():33 tmpl.render(fail=lambda: 1 / 0)
82 unmodified lines
modified:tests/test_ext.py+70 added-85 removed
1# -*- coding: utf-8 -*-1import re2from io import BytesIO34import 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_type10from jinja2.exceptions import TemplateAssertionError11from jinja2.ext import Extension12from jinja2.lexer import count_newlines13from jinja2.lexer import Token
36 unmodified lines
505152languages = {53 "de": {57 "missing": u"fehlend",58 "watch out": u"pass auf",59 "One user online": u"Ein Benutzer online",60 "%(user_count)s users online": u"%(user_count)s Benutzer online",61 "User: %(num)s": u"Benutzer: %(num)s",62 "User: %(count)s": u"Benutzer: %(count)s",63 "%(num)s apple": u"%(num)s Apfel",64 "%(num)s apples": u"%(num)s Äpfel",54 "missing": "fehlend",55 "watch out": "pass auf",56 "One user online": "Ein Benutzer online",57 "%(user_count)s users online": "%(user_count)s Benutzer online",58 "User: %(num)s": "Benutzer: %(num)s",59 "User: %(count)s": "Benutzer: %(count)s",60 "%(num)s apple": "%(num)s Apfel",61 "%(num)s apples": "%(num)s Äpfel",62 }63}6465
27 unmodified lines
93newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)949596class ExampleExtension(Extension):100 tags = set(["test"])97 tags = {"test"}98 ext_attr = 4299 context_reference_node_cls = nodes.ContextReference100101 def parse(self, parser):
11 unmodified lines
113 ]114 ).set_lineno(next(parser.stream).lineno)115116 def _dump(self, sandboxed, ext_attr, imported_object, context):120 return "%s|%s|%s|%s|%s" % (121 sandboxed,122 ext_attr,123 imported_object,124 context.blocks,125 context.get("test_var"),117 return (118 f"{sandboxed}|{ext_attr}|{imported_object}|{context.blocks}"119 f"|{context.get('test_var')}"120 )121122123class DerivedExampleExtension(ExampleExtension):
8 unmodified lines
132class StreamFilterExtension(Extension):133 def filter_stream(self, stream):134 for token in stream:135 if token.type == "data":142 for t in self.interpolate(token):143 yield t136 yield from self.interpolate(token)137 else:138 yield token139140 def interpolate(self, token):
19 unmodified lines
160 yield Token(lineno, "data", token.value[pos:])161162163@pytest.mark.ext171class TestExtensions(object):164class TestExtensions:165 def test_extend_late(self):166 env = Environment()167 env.add_extension("jinja2.ext.autoescape")168 t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')
54 unmodified lines
223 def test_rebinding(self):224 original = Environment(extensions=[ExampleExtension])225 overlay = original.overlay()226 for env in original, overlay:234 for ext in itervalues(env.extensions):227 for ext in env.extensions.values():228 assert ext.environment is env229230 def test_preprocessor_extension(self):231 env = Environment(extensions=[PreprocessorExtension])
24 unmodified lines
256 t = env.from_string("Hello\n{% debug %}\nGoodbye")257 out = t.render()258259 for value in ("context", "cycler", "filters", "abs", "tests", "!="):267 assert "'{}'".format(value) in out260 assert f"'{value}'" in out261262263@pytest.mark.ext271class TestInternationalization(object):264class TestInternationalization:265 def test_trans(self):266 tmpl = i18n_env.get_template("child.html")267 assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"268
65 unmodified lines
334 def test_extract(self):335 from jinja2.ext import babel_extract336337 source = BytesIO(338 b"""339 {{ gettext('Hello World') }}340 {% trans %}Hello World{% endtrans %}341 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}342 """346 {{ gettext('Hello World') }}347 {% trans %}Hello World{% endtrans %}348 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}349 """.encode(350 "ascii"351 )343 )352 ) # make python 3 happy344 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [354 (2, "gettext", u"Hello World", []),355 (3, "gettext", u"Hello World", []),356 (4, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),345 (2, "gettext", "Hello World", []),346 (3, "gettext", "Hello World", []),347 (4, "ngettext", ("%(users)s user", "%(users)s users", None), []),348 ]349350 def test_extract_trimmed(self):351 from jinja2.ext import babel_extract352353 source = BytesIO(354 b"""355 {{ gettext(' Hello \n World') }}356 {% trans trimmed %} Hello \n World{% endtrans %}357 {% trans trimmed %}{{ users }} \n user358 {%- pluralize %}{{ users }} \n users{% endtrans %}359 """364 {{ gettext(' Hello \n World') }}365 {% trans trimmed %} Hello \n World{% endtrans %}366 {% trans trimmed %}{{ users }} \n user367 {%- pluralize %}{{ users }} \n users{% endtrans %}368 """.encode(369 "ascii"370 )360 )371 ) # make python 3 happy361 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], {})) == [373 (2, "gettext", u" Hello \n World", []),374 (4, "gettext", u"Hello World", []),375 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),362 (2, "gettext", " Hello \n World", []),363 (4, "gettext", "Hello World", []),364 (6, "ngettext", ("%(users)s user", "%(users)s users", None), []),365 ]366367 def test_extract_trimmed_option(self):368 from jinja2.ext import babel_extract369370 source = BytesIO(371 b"""372 {{ gettext(' Hello \n World') }}373 {% trans %} Hello \n World{% endtrans %}374 {% trans %}{{ users }} \n user375 {%- pluralize %}{{ users }} \n users{% endtrans %}376 """383 {{ gettext(' Hello \n World') }}384 {% trans %} Hello \n World{% endtrans %}385 {% trans %}{{ users }} \n user386 {%- pluralize %}{{ users }} \n users{% endtrans %}387 """.encode(388 "ascii"389 )377 )390 ) # make python 3 happy378 opts = {"trimmed": "true"}379 assert list(babel_extract(source, ("gettext", "ngettext", "_"), [], opts)) == [393 (2, "gettext", u" Hello \n World", []),394 (4, "gettext", u"Hello World", []),395 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), []),380 (2, "gettext", " Hello \n World", []),381 (4, "gettext", "Hello World", []),382 (6, "ngettext", ("%(users)s user", "%(users)s users", None), []),383 ]384385 def test_comment_extract(self):386 from jinja2.ext import babel_extract387388 source = BytesIO(389 b"""390 {# trans first #}391 {{ gettext('Hello World') }}392 {% trans %}Hello World{% endtrans %}{# trans second #}393 {#: third #}394 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}395 """403 {# trans first #}404 {{ gettext('Hello World') }}405 {% trans %}Hello World{% endtrans %}{# trans second #}406 {#: third #}407 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}408 """.encode(409 "utf-8"410 )396 )411 ) # make python 3 happy397 assert list(398 babel_extract(source, ("gettext", "ngettext", "_"), ["trans", ":"], {})399 ) == [415 (3, "gettext", u"Hello World", ["first"]),416 (4, "gettext", u"Hello World", ["second"]),417 (6, "ngettext", (u"%(users)s user", u"%(users)s users", None), ["third"]),400 (3, "gettext", "Hello World", ["first"]),401 (4, "gettext", "Hello World", ["second"]),402 (6, "ngettext", ("%(users)s user", "%(users)s users", None), ["third"]),403 ]404405406@pytest.mark.ext422class TestScope(object):407class TestScope:408 def test_basic_scope_behavior(self):409 # This is what the old with statement compiled down to410 class ScopeExt(Extension):426 tags = set(["scope"])411 tags = {"scope"}412413 def parse(self, parser):414 node = nodes.Scope(lineno=next(parser.stream).lineno)415 assignments = []
21 unmodified lines
437 assert tmpl.render(b=3, e=4) == "1|2|2|4|5"438439440@pytest.mark.ext456class TestNewstyleInternationalization(object):441class TestNewstyleInternationalization:442 def test_trans(self):443 tmpl = newstyle_i18n_env.get_template("child.html")444 assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"445
20 unmodified lines
466467 def test_newstyle_plural(self):468 tmpl = newstyle_i18n_env.get_template("ngettext.html")469 assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apfel"485 assert tmpl.render(LANGUAGE="de", apples=5) == u"5 Äpfel"470 assert tmpl.render(LANGUAGE="de", apples=5) == "5 Äpfel"471472 def test_autoescape_support(self):473 env = Environment(extensions=["jinja2.ext.autoescape", "jinja2.ext.i18n"])474 env.install_gettext_callables(490 lambda x: u"<strong>Wert: %(name)s</strong>",475 lambda x: "<strong>Wert: %(name)s</strong>",476 lambda s, p, n: s,477 newstyle=True,478 )479 t = env.from_string(
12 unmodified lines
492 assert env.from_string(template).render() == "<html>"493494 def test_num_used_twice(self):495 tmpl = newstyle_i18n_env.get_template("ngettext_long.html")511 assert tmpl.render(apples=5, LANGUAGE="de") == u"5 Äpfel"496 assert tmpl.render(apples=5, LANGUAGE="de") == "5 Äpfel"497498 def test_num_called_num(self):499 source = newstyle_i18n_env.compile(500 """
6 unmodified lines
507 # that the generated code does not pass num twice (although that508 # would work) for better performance. This only works on the509 # newstyle gettext of course510 assert (526 re.search(r"u?'\%\(num\)s apple', u?'\%\(num\)s " r"apples', 3", source)511 re.search(r"u?'%\(num\)s apple', u?'%\(num\)s apples', 3", source)512 is not None513 )514515 def test_trans_vars(self):
13 unmodified lines
529 assert t.render() == "%(foo)s"530531532@pytest.mark.ext548class TestAutoEscape(object):533class TestAutoEscape:534 def test_scoped_setting(self):535 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)536 tmpl = env.from_string(537 """
4 unmodified lines
542 {{ "<HelloWorld>" }}543 """544 )545 assert tmpl.render().split() == [561 u"&lt;HelloWorld&gt;",562 u"<HelloWorld>",563 u"&lt;HelloWorld&gt;",546 "&lt;HelloWorld&gt;",547 "<HelloWorld>",548 "&lt;HelloWorld&gt;",549 ]550551 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=False)552 tmpl = env.from_string(
5 unmodified lines
558 {{ "<HelloWorld>" }}559 """560 )561 assert tmpl.render().split() == [577 u"<HelloWorld>",578 u"&lt;HelloWorld&gt;",579 u"<HelloWorld>",562 "<HelloWorld>",563 "&lt;HelloWorld&gt;",564 "<HelloWorld>",565 ]566567 def test_nonvolatile(self):568 env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)
34 unmodified lines
603 {{ '<testing>' }}604 """605 tmpl = env.from_string(tmplsource)606 assert tmpl.render(val=True).split()[0] == "Markup"622 assert tmpl.render(val=False).split()[0] == text_type.__name__607 assert tmpl.render(val=False).split()[0] == "str"608609 # looking at the source we should see <testing> there in raw610 # (and then escaped as well)611 env = Environment(extensions=["jinja2.ext.autoescape"])
5 unmodified lines
617 assert "&lt;testing&gt;\\n" in pysource618619 def test_overlay_scopes(self):620 class MagicScopeExtension(Extension):636 tags = set(["overlay"])621 tags = {"overlay"}622623 def parse(self, parser):624 node = nodes.OverlayScope(lineno=next(parser.stream).lineno)625 node.body = list(
20 unmodified lines
modified:tests/test_features.py+2 added-30 removed
1import sys21import pytest25from jinja2 import contextfilter6from jinja2 import Environment3from jinja2 import Template8from jinja2._compat import text_type4511@pytest.mark.skipif(sys.version_info < (3, 5), reason="Requires 3.5 or later")6# Python < 3.77def test_generator_stop():13 class X(object):8 class X:9 def __getattr__(self, name):10 raise StopIteration()1112 t = Template("a{{ bad.bar() }}b")13 with pytest.raises(RuntimeError):14 t.render(bad=X())202122@pytest.mark.skipif(sys.version_info[0] > 2, reason="Feature only supported on 2.x")23def test_ascii_str():24 @contextfilter25 def assert_func(context, value):26 assert type(value) is context["expected_type"]2728 env = Environment()29 env.filters["assert"] = assert_func3031 env.policies["compiler.ascii_str"] = False32 t = env.from_string('{{ "foo"|assert }}')33 t.render(expected_type=text_type)3435 env.policies["compiler.ascii_str"] = True36 t = env.from_string('{{ "foo"|assert }}')37 t.render(expected_type=str)3839 for val in True, False:40 env.policies["compiler.ascii_str"] = val41 t = env.from_string(u'{{ "\N{SNOWMAN}"|assert }}')42 t.render(expected_type=text_type)
modified:tests/test_filters.py+22 added-28 removed
1# -*- coding: utf-8 -*-1import random2from collections import namedtuple34import pytest56from jinja2 import Environment7from jinja2 import Markup9from jinja2._compat import implements_to_string10from jinja2._compat import text_type8913@implements_to_string14class Magic(object):10class Magic:11 def __init__(self, value):12 self.value = value1314 def __str__(self):19 return text_type(self.value)15 return str(self.value)161722@implements_to_string23class Magic2(object):18class Magic2:19 def __init__(self, value1, value2):20 self.value1 = value121 self.value2 = value22223 def __str__(self):29 return u"(%s,%s)" % (text_type(self.value1), text_type(self.value2))24 return f"({self.value1},{self.value2})"252627@pytest.mark.filter33class TestFilter(object):28class TestFilter:29 def test_filter_calling(self, env):30 rv = env.call_filter("sum", [1, 2, 3])31 assert rv == 632
21 unmodified lines
54 ("reverse=true", "[('c', 2), ('b', 1), ('AB', 3), ('aa', 0)]"),55 ),56 )57 def test_dictsort(self, env, args, expect):63 t = env.from_string("{{{{ foo|dictsort({args}) }}}}".format(args=args))58 t = env.from_string(f"{{{{ foo|dictsort({args}) }}}}")59 out = t.render(foo={"aa": 0, "b": 1, "c": 2, "AB": 3})60 assert out == expect6162 def test_batch(self, env):
74 unmodified lines
137 out = tmpl.render(foo=list(range(10)))138 assert out == "0"139140 @pytest.mark.parametrize(146 ("value", "expect"), (("42", "42.0"), ("abc", "0.0"), ("32.32", "32.32"),)141 ("value", "expect"), (("42", "42.0"), ("abc", "0.0"), ("32.32", "32.32"))142 )143 def test_float(self, env, value, expect):149 t = env.from_string("{{ '%s'|float }}" % value)150 assert t.render() == expect144 t = env.from_string("{{ value|float }}")145 assert t.render(value=value) == expect146147 def test_float_default(self, env):148 t = env.from_string("{{ value|float(default=1.0) }}")149 assert t.render(value="abc") == "1.0"150151 def test_format(self, env):157 tmpl = env.from_string("""{{ "%s|%s"|format("a", "b") }}""")152 tmpl = env.from_string("{{ '%s|%s'|format('a', 'b') }}")153 out = tmpl.render()154 assert out == "a|b"155156 @staticmethod
34 unmodified lines
191 ("12345678901234567890", "12345678901234567890"),192 ),193 )194 def test_int(self, env, value, expect):200 t = env.from_string("{{ '%s'|int }}" % value)201 assert t.render() == expect195 t = env.from_string("{{ value|int }}")196 assert t.render(value=value) == expect197198 @pytest.mark.parametrize(199 ("value", "base", "expect"),200 (("0x4d32", 16, "19762"), ("011", 8, "9"), ("0x33Z", 16, "0"),),201 )202 def test_int_base(self, env, value, base, expect):208 t = env.from_string("{{ '%s'|int(base=%d) }}" % (value, base))209 assert t.render() == expect203 t = env.from_string("{{ value|int(base=base) }}")204 assert t.render(value=value, base=base) == expect205206 def test_int_default(self, env):207 t = env.from_string("{{ value|int(default=1) }}")208 assert t.render(value="abc") == "1"209210 def test_int_special_method(self, env):216 class IntIsh(object):211 class IntIsh:212 def __int__(self):213 return 42214215 t = env.from_string("{{ value|int }}")
59 unmodified lines
275276 def test_string(self, env):277 x = [1, 2, 3, 4, 5]278 tmpl = env.from_string("""{{ obj|string }}""")284 assert tmpl.render(obj=x) == text_type(x)279 assert tmpl.render(obj=x) == str(x)280281 def test_title(self, env):282 tmpl = env.from_string("""{{ "foo bar"|title }}""")283 assert tmpl.render() == "Foo Bar"
32 unmodified lines
316 '{{ data|truncate(15, false, ">>>") }}|'317 "{{ smalldata|truncate(15) }}"318 )319 out = tmpl.render(data="foobar baz bar" * 1000, smalldata="foobar baz bar")325 msg = "Current output: %s" % out326 assert out == "foobar baz b>>>|foobar baz>>>|foobar baz bar", msg320 assert out == "foobar baz b>>>|foobar baz>>>|foobar baz bar"321322 def test_truncate_very_short(self, env):323 tmpl = env.from_string(324 '{{ "foo bar baz"|truncate(9) }}|{{ "foo bar baz"|truncate(9, true) }}'325 )326 out = tmpl.render()333 assert out == "foo bar baz|foo bar baz", out327 assert out == "foo bar baz|foo bar baz"328329 def test_truncate_end_length(self, env):330 tmpl = env.from_string('{{ "Joel is a slug"|truncate(7, true) }}')331 out = tmpl.render()338 assert out == "Joel...", "Current output: %s" % out332 assert out == "Joel..."333334 def test_upper(self, env):335 tmpl = env.from_string('{{ "foo"|upper }}')336 assert tmpl.render() == "FOO"
240 unmodified lines
577 assert tmpl.render(string=Markup("foo")) == "f&gt;x&lt;&gt;x&lt;"578579 def test_forceescape(self, env):580 tmpl = env.from_string("{{ x|forceescape }}")587 assert tmpl.render(x=Markup("<div />")) == u"&lt;div /&gt;"581 assert tmpl.render(x=Markup("<div />")) == "&lt;div /&gt;"582583 def test_safe(self, env):584 env = Environment(autoescape=True)585 tmpl = env.from_string('{{ "<div>foo</div>"|safe }}')
4 unmodified lines
590 @pytest.mark.parametrize(591 ("value", "expect"),592 [593 ("Hello, world!", "Hello%2C%20world%21"),600 (u"Hello, world\u203d", "Hello%2C%20world%E2%80%BD"),594 ("Hello, world\u203d", "Hello%2C%20world%E2%80%BD"),595 ({"f": 1}, "f=1"),596 ([("f", 1), ("z", 2)], "f=1&amp;z=2"),603 ({u"\u203d": 1}, "%E2%80%BD=1"),597 ({"\u203d": 1}, "%E2%80%BD=1"),598 ({0: 1}, "0=1"),599 ([("a b/c", "a b/c")], "a+b%2Fc=a+b%2Fc"),600 ("a b/c", "a%20b/c"),601 ],
138 unmodified lines
modified:tests/test_idtracking.py+19 added-19 removed
36 unmodified lines
373839def test_complex():40 title_block = nodes.Block(41 "title", [nodes.Output([nodes.TemplateData(u"Page Title")])], False41 "title", [nodes.Output([nodes.TemplateData("Page Title")])], False42 )4344 render_title_macro = nodes.Macro(45 "render_title",
1 unmodified line
47 [],48 [49 nodes.Output(50 [51 nodes.TemplateData(u'\n <div class="title">\n <h1>'),51 nodes.TemplateData('\n <div class="title">\n <h1>'),52 nodes.Name("title", "load"),53 nodes.TemplateData(u"</h1>\n <p>"),53 nodes.TemplateData("</h1>\n <p>"),54 nodes.Name("subtitle", "load"),55 nodes.TemplateData(u"</p>\n "),55 nodes.TemplateData("</p>\n "),56 ]57 ),58 nodes.Assign(59 nodes.Name("subtitle", "store"), nodes.Const("something else")60 ),61 nodes.Output(62 [63 nodes.TemplateData(u"\n <p>"),63 nodes.TemplateData("\n <p>"),64 nodes.Name("subtitle", "load"),65 nodes.TemplateData(u"</p>\n </div>\n"),65 nodes.TemplateData("</p>\n </div>\n"),66 nodes.If(67 nodes.Name("something", "load"),68 [69 nodes.Assign(
33 unmodified lines
103 nodes.Name("seq", "load"),104 [105 nodes.Output(106 [107 nodes.TemplateData(u"\n <li>"),107 nodes.TemplateData("\n <li>"),108 nodes.Name("item", "load"),109 nodes.TemplateData(u"</li>\n <span>"),109 nodes.TemplateData("</li>\n <span>"),110 ]111 ),112 nodes.Include(nodes.Const("helper.html"), True, False),113 nodes.Output([nodes.TemplateData(u"</span>\n ")]),113 nodes.Output([nodes.TemplateData("</span>\n ")]),114 ],115 [],116 None,117 False,
3 unmodified lines
121 "body",122 [123 nodes.Output(124 [125 nodes.TemplateData(u"\n "),125 nodes.TemplateData("\n "),126 nodes.Call(127 nodes.Name("render_title", "load"),128 [nodes.Name("item", "load")],129 [],130 None,131 None,132 ),133 nodes.TemplateData(u"\n <ul>\n "),133 nodes.TemplateData("\n <ul>\n "),134 ]135 ),136 for_loop,137 nodes.Output([nodes.TemplateData(u"\n </ul>\n")]),137 nodes.Output([nodes.TemplateData("\n </ul>\n")]),138 ],139 False,140 )141
12 unmodified lines
154 }155 assert tmpl_sym.loads == {156 "l_0_render_title": ("undefined", None),157 }158 assert tmpl_sym.stores == set(["render_title"])158 assert tmpl_sym.stores == {"render_title"}159 assert tmpl_sym.dump_stores() == {160 "render_title": "l_0_render_title",161 }162
9 unmodified lines
172 "l_1_something": ("resolve", "something"),173 "l_1_title": ("param", None),174 "l_1_title_upper": ("resolve", "title_upper"),175 }176 assert macro_sym.stores == set(["title", "title_upper", "subtitle"])176 assert macro_sym.stores == {"title", "title_upper", "subtitle"}177 assert macro_sym.find_ref("render_title") == "l_0_render_title"178 assert macro_sym.dump_stores() == {179 "title": "l_1_title",180 "title_upper": "l_1_title_upper",
11 unmodified lines
192 "l_0_item": ("resolve", "item"),193 "l_0_seq": ("resolve", "seq"),194 "l_0_render_title": ("resolve", "render_title"),195 }196 assert body_sym.stores == set([])196 assert body_sym.stores == set()197198 for_sym = symbols_for_node(for_loop, body_sym)199 assert for_sym.refs == {200 "item": "l_1_item",201 }202 assert for_sym.loads == {203 "l_1_item": ("param", None),204 }205 assert for_sym.stores == set(["item"])205 assert for_sym.stores == {"item"}206 assert for_sym.dump_stores() == {207 "item": "l_1_item",208 }209
11 unmodified lines
221 )222223 sym = symbols_for_node(tmpl)224 assert sym.refs == {"variable": "l_0_variable", "expression": "l_0_expression"}225 assert sym.stores == set(["variable"])225 assert sym.stores == {"variable"}226 assert sym.loads == {227 "l_0_variable": ("resolve", "variable"),228 "l_0_expression": ("resolve", "expression"),229 }
16 unmodified lines
246 )247248 sym = symbols_for_node(tmpl)249 assert sym.refs == {"variable": "l_0_variable", "expression": "l_0_expression"}250 assert sym.stores == set(["variable"])250 assert sym.stores == {"variable"}251 assert sym.loads == {252 "l_0_variable": ("undefined", None),253 "l_0_expression": ("resolve", "expression"),254 }
25 unmodified lines
280 )281282 tmpl_sym = symbols_for_node(tmpl)283 for_sym = symbols_for_node(for_loop, tmpl_sym)284 assert for_sym.stores == set(["item", "x"])284 assert for_sym.stores == {"item", "x"}285 assert for_sym.loads == {286 "l_1_x": ("alias", "l_0_x"),287 "l_1_item": ("param", None),288 "l_1_expression": ("resolve", "expression"),
1 unmodified line
modified:tests/test_imports.py+11 added-5 removed
1# -*- coding: utf-8 -*-1import pytest24from jinja2 import DictLoader5from jinja2 import Environment3from jinja2.environment import Environment4from jinja2.exceptions import TemplateNotFound5from jinja2.exceptions import TemplatesNotFound6from jinja2.exceptions import TemplateSyntaxError7from jinja2.exceptions import UndefinedError8from jinja2.loaders import DictLoader91011@pytest.fixture12def test_env():
10 unmodified lines
23 return env242526@pytest.mark.imports27class TestImports(object):27class TestImports:28 def test_context_imports(self, test_env):29 t = test_env.from_string('{% import "module" as m %}{{ m.test() }}')30 assert t.render(foo=42) == "[|23]"31 t = test_env.from_string(
60 unmodified lines
92 assert not hasattr(m, "__missing")93 assert m.variable == 4294 assert not hasattr(m, "notthere")9596 def test_not_exported(self, test_env):97 t = test_env.from_string("{% from 'module' import nothing %}{{ nothing() }}")9899 with pytest.raises(UndefinedError, match="does not export the requested name"):100 t.render()101102103@pytest.mark.imports104@pytest.mark.includes99class TestIncludes(object):105class TestIncludes:106 def test_context_include(self, test_env):107 t = test_env.from_string('{% include "header" %}')108 assert t.render(foo=42) == "[42|23]"109 t = test_env.from_string('{% include "header" with context %}')
76 unmodified lines
modified:tests/test_inheritance.py+4 added-5 removed
1# -*- coding: utf-8 -*-1import pytest23from jinja2 import DictLoader4from jinja2 import Environment
68 unmodified lines
73 )747576@pytest.mark.inheritance78class TestInheritance(object):77class TestInheritance:78 def test_layout(self, env):79 tmpl = env.get_template("layout")80 assert tmpl.render() == (81 "|block 1 from layout|block 2 from layout|nested block 4 from layout|"
74 unmodified lines
156 )157 )158 tmpl = env.get_template("child")159 for m in range(1, 3):161 assert tmpl.render(master="master%d" % m) == "MASTER%dCHILD" % m160 assert tmpl.render(master=f"master{m}") == f"MASTER{m}CHILD"161162 def test_multi_inheritance(self, env):163 env = Environment(164 loader=DictLoader(
67 unmodified lines
232 assert rv == ["43", "44", "45"]233234235@pytest.mark.inheritance237class TestBugFix(object):236class TestBugFix:237 def test_fixed_macro_scoping_bug(self, env):238 assert (239 Environment(240 loader=DictLoader(
33 unmodified lines
274 )275 .get_template("test.html")276 .render()277 .split()279 == [u"outer_box", u"my_macro"]278 == ["outer_box", "my_macro"]279 )280281 def test_double_extends(self, env):282 """Ensures that a template with more than 1 {% extends ... %} usage
4 unmodified lines
modified:tests/test_lexnparse.py+49 added-74 removed
1# -*- coding: utf-8 -*-1import pytest23from jinja2 import Environment4from jinja2 import nodes5from jinja2 import Template6from jinja2 import TemplateSyntaxError7from jinja2 import UndefinedError9from jinja2._compat import iteritems10from jinja2._compat import PY211from jinja2._compat import text_type8from jinja2.lexer import Token9from jinja2.lexer import TOKEN_BLOCK_BEGIN10from jinja2.lexer import TOKEN_BLOCK_END11from jinja2.lexer import TOKEN_EOF12from jinja2.lexer import TokenStream131419# how does a string look like in jinja syntax?20if PY2:2122 def jinja_string_repr(string):23 return repr(string)[1:]242526else:27 jinja_string_repr = repr282915@pytest.mark.lexnparse16@pytest.mark.tokenstream32class TestTokenStream(object):17class TestTokenStream:18 test_tokens = [19 Token(1, TOKEN_BLOCK_BEGIN, ""),20 Token(2, TOKEN_BLOCK_END, ""),21 ]
21 unmodified lines
434445@pytest.mark.lexnparse46@pytest.mark.lexer62class TestLexer(object):47class TestLexer:48 def test_raw1(self, env):49 tmpl = env.from_string(50 "{% raw %}foo{% endraw %}|"51 "{%raw%}{{ bar }}|{% baz %}{% endraw %}"
42 unmodified lines
94 "<ul>\n <li>0</li>\n <li>1</li>\n <li>2</li>\n</ul>"95 )9697 def test_string_escapes(self, env):113 for char in u"\0", u"\u2668", u"\xe4", u"\t", u"\r", u"\n":114 tmpl = env.from_string("{{ %s }}" % jinja_string_repr(char))98 for char in "\0", "\u2668", "\xe4", "\t", "\r", "\n":99 tmpl = env.from_string(f"{{{{ {char!r} }}}}")100 assert tmpl.render() == char116 assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u"\u2668"101 assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == "\u2668"102103 def test_bytefallback(self, env):104 from pprint import pformat105121 tmpl = env.from_string(u"""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")122 assert tmpl.render() == pformat("foo") + "|" + pformat(u"bär")106 tmpl = env.from_string("""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")107 assert tmpl.render() == pformat("foo") + "|" + pformat("bär")108109 def test_operators(self, env):110 from jinja2.lexer import operators111127 for test, expect in iteritems(operators):112 for test, expect in operators.items():113 if test in "([{}])":114 continue130 stream = env.lexer.tokenize("{{ %s }}" % test)115 stream = env.lexer.tokenize(f"{{{{ {test} }}}}")116 next(stream)117 assert stream.current.type == expect118119 def test_normalizing(self, env):
17 unmodified lines
137 result = tmpl.render()138 assert result == expect, (keep, template, result, expect)139140 @pytest.mark.parametrize(156 "name,valid2,valid3",157 (158 (u"foo", True, True),159 (u"föö", False, True),160 (u"き", False, True),161 (u"_", True, True),162 (u"1a", False, False), # invalid ascii start163 (u"a-", False, False), # invalid ascii continue164 (u"🐍", False, False), # invalid unicode start165 (u"a🐍", False, False), # invalid unicode continue141 ("name", "valid"),142 [143 ("foo", True),144 ("föö", True),145 ("き", True),146 ("_", True),147 ("1a", False), # invalid ascii start148 ("a-", False), # invalid ascii continue149 ("\U0001f40da", False), # invalid unicode start150 ("a🐍\U0001f40d", False), # invalid unicode continue151 # start characters not matched by \w167 (u"\u1885", False, True),168 (u"\u1886", False, True),169 (u"\u2118", False, True),170 (u"\u212e", False, True),152 ("\u1885", True),153 ("\u1886", True),154 ("\u2118", True),155 ("\u212e", True),156 # continue character not matched by \w172 (u"\xb7", False, False),173 (u"a\xb7", False, True),174 ),157 ("\xb7", False),158 ("a\xb7", True),159 ],160 )176 def test_name(self, env, name, valid2, valid3):177 t = u"{{ " + name + u" }}"161 def test_name(self, env, name, valid):162 t = "{{ " + name + " }}"163179 if (valid2 and PY2) or (valid3 and not PY2):164 if valid:165 # valid for version being tested, shouldn't raise166 env.from_string(t)167 else:168 pytest.raises(TemplateSyntaxError, env.from_string, t)169170171@pytest.mark.lexnparse172@pytest.mark.parser188class TestParser(object):173class TestParser:174 def test_php_syntax(self, env):175 env = Environment("<?", "?>", "<?=", "?>", "<!--", "-->")176 tmpl = env.from_string(177 """\
126 unmodified lines
304305306@pytest.mark.lexnparse307@pytest.mark.syntax323class TestSyntax(object):308class TestSyntax:309 def test_call(self, env):310 env = Environment()311 env.globals["foo"] = lambda a, b, c, e, g: a + b + c + e + g312 tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}")
42 unmodified lines
355 (4, "!=", 5),356 ],357 )358 def test_compare(self, env, a, op, b):374 t = env.from_string("{{ %d %s %d }}" % (a, op, b))359 t = env.from_string(f"{{{{ {a} {op} {b} }}}}")360 assert t.render() == "True"361362 def test_compare_parens(self, env):363 t = env.from_string("{{ i * (j < 5) }}")
19 unmodified lines
383 assert tmpl.render() == "True|False"384385 @pytest.mark.parametrize("value", ("[]", "{}", "()"))386 def test_collection_literal(self, env, value):402 t = env.from_string("{{ %s }}" % value)387 t = env.from_string(f"{{{{ {value} }}}}")388 assert t.render() == value389390 @pytest.mark.parametrize(391 ("value", "expect"),
12 unmodified lines
404 ("1_2.3_4e5_6", "1.234e+57"),405 ),406 )407 def test_numeric_literal(self, env, value, expect):423 t = env.from_string("{{ %s }}" % value)408 t = env.from_string(f"{{{{ {value} }}}}")409 assert t.render() == expect410411 def test_bool(self, env):412 tmpl = env.from_string(
45 unmodified lines
458 (False, "foo, *args, bar=23, **baz"),459 ]460 for should_fail, sig in tests:461 if should_fail:477 pytest.raises(478 TemplateSyntaxError, env.from_string, "{{ foo(%s) }}" % sig479 )462 with pytest.raises(TemplateSyntaxError):463 env.from_string(f"{{{{ foo({sig}) }}}}")464 else:481 env.from_string("foo(%s)" % sig)465 env.from_string(f"foo({sig})")466467 def test_tuple_expr(self, env):468 for tmpl in [469 "{{ () }}",
18 unmodified lines
488 )489490 def test_constant_casing(self, env):491 for const in True, False, None:492 const = str(const)493 tmpl = env.from_string(509 "{{ %s }}|{{ %s }}|{{ %s }}"510 % (str(const), str(const).lower(), str(const).upper())494 f"{{{{ {const} }}}}|{{{{ {const.lower()} }}}}|{{{{ {const.upper()} }}}}"495 )512 assert tmpl.render() == "%s|%s|" % (const, const)496 assert tmpl.render() == f"{const}|{const}|"497498 def test_test_chaining(self, env):499 pytest.raises(500 TemplateSyntaxError, env.from_string, "{{ foo is string is sequence }}"
10 unmodified lines
511 assert tmpl.render(bar=bar) == "False"512513 def test_operator_precedence(self, env):514 tmpl = env.from_string("""{{ 2 * 3 + 4 % 2 + 1 - 2 }}""")531 assert tmpl.render() == text_type(2 * 3 + 4 % 2 + 1 - 2)515 assert tmpl.render() == "5"516517 def test_implicit_subscribed_tuple(self, env):534 class Foo(object):518 class Foo:519 def __getitem__(self, x):520 return x521522 t = env.from_string("{{ foo[1, 2] }}")539 assert t.render(foo=Foo()) == u"(1, 2)"523 assert t.render(foo=Foo()) == "(1, 2)"524525 def test_raw2(self, env):526 tmpl = env.from_string("{% raw %}{{ FOO }} and {% BAR %}{% endraw %}")527 assert tmpl.render() == "{{ FOO }} and {% BAR %}"
32 unmodified lines
560561562@pytest.mark.lexnparse563@pytest.mark.lstripblocks580class TestLstripBlocks(object):564class TestLstripBlocks:565 def test_lstrip(self, env):566 env = Environment(lstrip_blocks=True, trim_blocks=False)567 tmpl = env.from_string(""" {% if True %}\n {% endif %}""")568 assert tmpl.render() == "\n"
111 unmodified lines
680 <% for item in seq %>681${item} ## the rest of the stuff682 <% endfor %>"""683 )700 assert tmpl.render(seq=range(5)) == "".join("%s\n" % x for x in range(5))684 assert tmpl.render(seq=range(5)) == "".join(f"{x}\n" for x in range(5))685686 def test_lstrip_angle_bracket_compact(self, env):687 env = Environment(688 "<%",
13 unmodified lines
702 <%for item in seq%>703${item} ## the rest of the stuff704 <%endfor%>"""705 )722 assert tmpl.render(seq=range(5)) == "".join("%s\n" % x for x in range(5))706 assert tmpl.render(seq=range(5)) == "".join(f"{x}\n" for x in range(5))707708 def test_php_syntax_with_manual(self, env):709 env = Environment(710 "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True
17 unmodified lines
728 <? for item in seq ?>729 <?= item ?>730 <? endfor ?>"""731 )748 assert tmpl.render(seq=range(5)) == "".join(749 " %s\n" % x for x in range(5)750 )732 assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))733734 def test_php_syntax_compact(self, env):735 env = Environment(736 "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True
4 unmodified lines
741 <?for item in seq?>742 <?=item?>743 <?endfor?>"""744 )763 assert tmpl.render(seq=range(5)) == "".join(764 " %s\n" % x for x in range(5)765 )745 assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))746747 def test_erb_syntax(self, env):748 env = Environment(749 "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True750 )771 # env.from_string('')772 # for n,r in env.lexer.rules.iteritems():773 # print n774 # print env.lexer.rules['root'][0][0].pattern775 # print "'%s'" % tmpl.render(seq=range(5))751 tmpl = env.from_string(752 """\753<%# I'm a comment, I'm not interesting %>754 <% for item in seq %>755 <%= item %>756 <% endfor %>757"""758 )784 assert tmpl.render(seq=range(5)) == "".join(" %s\n" % x for x in range(5))759 assert tmpl.render(seq=range(5)) == "".join(f" {x}\n" for x in range(5))760761 def test_erb_syntax_with_manual(self, env):762 env = Environment(763 "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True
42 unmodified lines
modified:tests/test_loader.py+11 added-34 removed
1# -*- coding: utf-8 -*-1import os2import platform3import shutil4import sys5import tempfile6import time
3 unmodified lines
1011from jinja2 import Environment12from jinja2 import loaders13from jinja2 import PackageLoader14from jinja2._compat import PY215from jinja2._compat import PYPY14from jinja2.exceptions import TemplateNotFound15from jinja2.loaders import split_template_path161718@pytest.mark.loaders21class TestLoaders(object):19class TestLoaders:20 def test_dict_loader(self, dict_loader):21 env = Environment(loader=dict_loader)22 tmpl = env.get_template("justdict.html")23 assert tmpl.render().strip() == "FOO"
41 unmodified lines
65 changed = False6667 class TestLoader(loaders.BaseLoader):68 def get_source(self, environment, template):71 return u"foo", None, lambda: not changed69 return "foo", None, lambda: not changed7071 env = Environment(loader=TestLoader(), cache_size=-1)72 tmpl = env.get_template("template")73 assert tmpl is env.get_template("template")
42 unmodified lines
116117118@pytest.mark.loaders119@pytest.mark.filesystemloader122class TestFileSystemLoader(object):120class TestFileSystemLoader:121 searchpath = os.path.join(122 os.path.dirname(os.path.abspath(__file__)), "res", "templates"123 )124
10 unmodified lines
135136 env = Environment(loader=filesystem_loader)137 self._test_common(env)138141 @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")139 def test_searchpath_as_pathlib(self):140 import pathlib141142 searchpath = pathlib.Path(self.searchpath)146143 filesystem_loader = loaders.FileSystemLoader(searchpath)148144 env = Environment(loader=filesystem_loader)145 self._test_common(env)146152 @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")147 def test_searchpath_as_list_including_pathlib(self):148 import pathlib149150 searchpath = pathlib.Path(self.searchpath)157151 filesystem_loader = loaders.FileSystemLoader(["/tmp/templates", searchpath])159152 env = Environment(loader=filesystem_loader)153 self._test_common(env)154155 def test_caches_template_based_on_mtime(self):
10 unmodified lines
166167 @pytest.mark.parametrize(168 ("encoding", "expect"),169 [178 ("utf-8", u"文字化け"),179 ("iso-8859-1", u"æ\x96\x87\xe5\xad\x97\xe5\x8c\x96\xe3\x81\x91"),170 ("utf-8", "文字化け"),171 ("iso-8859-1", "æ\x96\x87\xe5\xad\x97\xe5\x8c\x96\xe3\x81\x91"),172 ],173 )174 def test_uses_specified_encoding(self, encoding, expect):175 loader = loaders.FileSystemLoader(self.searchpath, encoding=encoding)
3 unmodified lines
179180181@pytest.mark.loaders182@pytest.mark.moduleloader191class TestModuleLoader(object):183class TestModuleLoader:184 archive = None185194 def compile_down(self, prefix_loader, zip="deflated", py_compile=False):186 def compile_down(self, prefix_loader, zip="deflated"):187 log = []188 self.reg_env = Environment(loader=prefix_loader)189 if zip is not None:190 fd, self.archive = tempfile.mkstemp(suffix=".zip")191 os.close(fd)192 else:193 self.archive = tempfile.mkdtemp()202 self.reg_env.compile_templates(203 self.archive, zip=zip, log_function=log.append, py_compile=py_compile204 )194 self.reg_env.compile_templates(self.archive, zip=zip, log_function=log.append)195 self.mod_env = Environment(loader=loaders.ModuleLoader(self.archive))196 return "".join(log)197198 def teardown(self):
57 unmodified lines
256 pass257258 assert name not in sys.modules259270 # This test only makes sense on non-pypy python 2271 @pytest.mark.skipif(272 not (PY2 and not PYPY), reason="This test only makes sense on non-pypy python 2"273 )274 def test_byte_compilation(self, prefix_loader):275 log = self.compile_down(prefix_loader, py_compile=True)276 assert 'Byte-compiled "a/test.html"' in log277 self.mod_env.get_template("a/test.html")278 mod = self.mod_env.loader.module.tmpl_3c4ddf650c1a73df961a6d3d2ce2752f1b8fd490279 assert mod.__file__.endswith(".pyc")280260 def test_choice_loader(self, prefix_loader):261 self.compile_down(prefix_loader)262 self.mod_env.loader = loaders.ChoiceLoader(263 [self.mod_env.loader, loaders.DictLoader({"DICT_SOURCE": "DICT_TEMPLATE"})]
15 unmodified lines
279 assert tmpl1.render() == "BAR"280 tmpl2 = self.mod_env.get_template("DICT/test.html")281 assert tmpl2.render() == "DICT_TEMPLATE"282304 @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")283 def test_path_as_pathlib(self, prefix_loader):284 self.compile_down(prefix_loader)285286 mod_path = self.mod_env.loader.module.__path__[0]
4 unmodified lines
291 self.mod_env = Environment(loader=mod_loader)292293 self._test_common()294317 @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")295 def test_supports_pathlib_in_list_of_paths(self, prefix_loader):296 self.compile_down(prefix_loader)297298 mod_path = self.mod_env.loader.module.__path__[0]
46 unmodified lines
345 assert up_to_date is None346347348@pytest.mark.xfail(372 PYPY,373 reason="PyPy's zipimporter doesn't have a _files attribute.",349 platform.python_implementation() == "PyPy",350 reason="PyPy's zipimporter doesn't have a '_files' attribute.",351 raises=TypeError,352)353def test_package_zip_list(package_zip_loader):354 assert package_zip_loader.list_templates() == ["foo/test.html", "test.html"]
modified:tests/test_nativetypes.py+2 added-3 removed
1import pytest23from jinja2._compat import text_type3from jinja2.exceptions import UndefinedError4from jinja2.nativetypes import NativeEnvironment5from jinja2.nativetypes import NativeTemplate6from jinja2.runtime import Undefined
44 unmodified lines
5152def test_loops(env):53 t = env.from_string("{% for x in value %}{{ x }}{% endfor %}")54 result = t.render(value=["a", "b", "c", "d"])56 assert isinstance(result, text_type)55 assert isinstance(result, str)56 assert result == "abcd"575859def test_loops_with_ints(env):
49 unmodified lines
109110def test_string_literal_var(env):111 t = env.from_string("[{{ 'all' }}]")112 result = t.render()114 assert isinstance(result, text_type)113 assert isinstance(result, str)114 assert result == "[all]"115116117def test_string_top_level(env):
21 unmodified lines
modified:tests/test_regression.py+13 added-24 removed
1# -*- coding: utf-8 -*-2import sys31import pytest23from jinja2 import DictLoader4from jinja2 import Environment
1 unmodified line
6from jinja2 import Template7from jinja2 import TemplateAssertionError8from jinja2 import TemplateNotFound9from jinja2 import TemplateSyntaxError13from jinja2._compat import text_type101112@pytest.mark.regression17class TestCorner(object):13class TestCorner:14 def test_assigned_scoping(self, env):15 t = env.from_string(16 """17 {%- for item in (1, 2, 3, 4) -%}
63 unmodified lines
81 assert t.render(wrapper=23) == "[1][2][3][4]23"828384@pytest.mark.regression89class TestBug(object):85class TestBug:86 def test_keyword_folding(self, env):87 env = Environment()88 env.filters["testing"] = lambda value, some: value + some89 assert (
39 unmodified lines
129130 """131 )132137 assert tmpl.render().split() == [text_type(x) for x in range(1, 11)] * 5133 assert tmpl.render().split() == [str(x) for x in range(1, 11)] * 5134135 def test_weird_inline_comment(self, env):136 env = Environment(line_statement_prefix="%")137 pytest.raises(
52 unmodified lines
190 {{ x }}191 """192 )193 rv = t.render(foo=[1]).strip()198 assert rv == u"1"194 assert rv == "1"195196 def test_call_with_args(self, env):197 t = Template(198 """{% macro dump_users(users) -%}
25 unmodified lines
224 }225 ]226 ).splitlines()227 ] == [232 u"<ul><li><p>apo</p><dl>",233 u"<dl>Realname</dl>",234 u"<dd>something else</dd>",235 u"<dl>Description</dl>",236 u"<dd>test</dd>",237 u"</dl>",238 u"</li></ul>",228 "<ul><li><p>apo</p><dl>",229 "<dl>Realname</dl>",230 "<dd>something else</dd>",231 "<dl>Description</dl>",232 "<dd>test</dd>",233 "</dl>",234 "</li></ul>",235 ]236237 def test_empty_if_condition_fails(self, env):238 pytest.raises(TemplateSyntaxError, Template, "{% if %}....{% endif %}")
53 unmodified lines
292293 def test_contextfunction_callable_classes(self, env):294 from jinja2.utils import contextfunction295300 class CallableClass(object):296 class CallableClass:297 @contextfunction298 def __call__(self, ctx):299 return ctx.resolve("hello")300
2 unmodified lines
303 expected = "TEST"304305 assert output == expected306311 @pytest.mark.skipif(sys.version_info[0] > 2, reason="This only works on 2.x")312 def test_old_style_attribute(self, env):313 class Foo:314 x = 42315316 assert env.getitem(Foo(), "x") == 42317307 def test_block_set_with_extends(self):308 env = Environment(309 loader=DictLoader({"main": "{% block body %}[{{ x }}]{% endblock %}"})310 )
282 unmodified lines
593 class MyContext(Context):594 def resolve(self, name):595 if name == "foo":596 return 42608 return super(MyContext, self).resolve(name)597 return super().resolve(name)598599 x = MyContext(env, parent={"bar": 23}, name="foo", blocks={})600 assert x._legacy_resolve_mode601 assert x.resolve_or_missing("foo") == 42
14 unmodified lines
modified:tests/test_runtime.py+1 added-1 removed
60 unmodified lines
61 values for arbitrary attrs, it should not be incorrectly identified62 as a ``contextfunction``.63 """6465 class Calc(object):65 class Calc:66 def __getattr__(self, item):67 return object()6869 def __call__(self, *args, **kwargs):
6 unmodified lines
modified:tests/test_security.py+10 added-54 removed
1# -*- coding: utf-8 -*-1import pytest23from jinja2 import Environment4from jinja2 import escape6from jinja2 import Markup7from jinja2._compat import text_type5from jinja2.exceptions import SecurityError6from jinja2.exceptions import TemplateRuntimeError7from jinja2.exceptions import TemplateSyntaxError8from jinja2.nodes import EvalContext
1 unmodified line
10from jinja2.sandbox import SandboxedEnvironment11from jinja2.sandbox import unsafe121317class PrivateStuff(object):14class PrivateStuff:15 def bar(self):16 return 231718 @unsafe
3 unmodified lines
22 def __repr__(self):23 return "PrivateStuff"242529class PublicStuff(object):26class PublicStuff:27 def bar(self):28 return 232930 def _foo(self):
3 unmodified lines
34 return "PublicStuff"353637@pytest.mark.sandbox41class TestSandbox(object):38class TestSandbox:39 def test_unsafe(self, env):40 env = SandboxedEnvironment()41 pytest.raises(42 SecurityError, env.from_string("{{ foo.foo() }}").render, foo=PrivateStuff()
30 unmodified lines
73 env.from_string,74 "{% for foo, bar.baz in seq %}...{% endfor %}",75 )7680 def test_markup_operations(self, env):81 # adding two strings should escape the unsafe one82 unsafe = '<script type="application/x-some-script">alert("foo");</script>'83 safe = Markup("<em>username</em>")84 assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)8586 # string interpolations are safe to use too87 assert Markup("<em>%s</em>") % "<bad user>" == "<em>&lt;bad user&gt;</em>"88 assert (89 Markup("<em>%(username)s</em>") % {"username": "<bad user>"}90 == "<em>&lt;bad user&gt;</em>"91 )9293 # an escaped object is markup too94 assert type(Markup("foo") + "bar") is Markup9596 # and it implements __html__ by returning itself97 x = Markup("foo")98 assert x.__html__() is x99100 # it also knows how to treat __html__ objects101 class Foo(object):102 def __html__(self):103 return "<em>awesome</em>"104105 def __unicode__(self):106 return "awesome"107108 assert Markup(Foo()) == "<em>awesome</em>"109 assert (110 Markup("<strong>%s</strong>") % Foo() == "<strong><em>awesome</em></strong>"111 )112113 # escaping and unescaping114 assert escape("\"<>&'") == "&#34;&lt;&gt;&amp;&#39;"115 assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"116 assert Markup("&lt;test&gt;").unescape() == "<test>"11777 def test_template_data(self, env):78 env = Environment(autoescape=True)79 t = env.from_string(80 "{% macro say_hello(name) %}"
1 unmodified line
82 '{{ say_hello("<blink>foo</blink>") }}'83 )84 escaped_out = "<p>Hello &lt;blink&gt;foo&lt;/blink&gt;!</p>"85 assert t.render() == escaped_out127 assert text_type(t.module) == escaped_out86 assert str(t.module) == escaped_out87 assert escape(t.module) == escaped_out88 assert t.module.say_hello("<blink>foo</blink>") == escaped_out89 assert (90 escape(t.module.say_hello(EvalContext(env), "<blink>foo</blink>"))
12 unmodified lines
103104 for expr, ctx, rv in ("1 + 2", {}, "3"), ("a + 2", {"a": 2}, "4"):105 env = SandboxedEnvironment()106 env.binop_table["+"] = disable_op148 t = env.from_string("{{ %s }}" % expr)107 t = env.from_string(f"{{{{ {expr} }}}}")108 assert t.render(ctx) == rv109 env.intercepted_binops = frozenset(["+"])151 t = env.from_string("{{ %s }}" % expr)110 t = env.from_string(f"{{{{ {expr} }}}}")111 with pytest.raises(TemplateRuntimeError):112 t.render(ctx)113114 def test_unary_operator_intercepting(self, env):
2 unmodified lines
117118 for expr, ctx, rv in ("-1", {}, "-1"), ("-a", {"a": 2}, "-2"):119 env = SandboxedEnvironment()120 env.unop_table["-"] = disable_op162 t = env.from_string("{{ %s }}" % expr)121 t = env.from_string(f"{{{{ {expr} }}}}")122 assert t.render(ctx) == rv123 env.intercepted_unops = frozenset(["-"])165 t = env.from_string("{{ %s }}" % expr)124 t = env.from_string(f"{{{{ {expr} }}}}")125 with pytest.raises(TemplateRuntimeError):126 t.render(ctx)127128129@pytest.mark.sandbox171class TestStringFormat(object):130class TestStringFormat:131 def test_basic_format_safety(self):132 env = SandboxedEnvironment()133 t = env.from_string('{{ "a{0.__class__}b".format(42) }}')134 assert t.render() == "ab"
14 unmodified lines
149 assert t.render() == "a42b&lt;foo&gt;"150151152@pytest.mark.sandbox194@pytest.mark.skipif(195 not hasattr(str, "format_map"), reason="requires str.format_map method"196)197class TestStringFormatMap(object):153class TestStringFormatMap:154 def test_basic_format_safety(self):155 env = SandboxedEnvironment()156 t = env.from_string('{{ "a{x.__class__}b".format_map({"x":42}) }}')157 assert t.render() == "ab"
12 unmodified lines
modified:tests/test_tests.py+3 added-4 removed
1# -*- coding: utf-8 -*-1import pytest23from jinja2 import Environment4from jinja2 import Markup
3 unmodified lines
8 pass91011@pytest.mark.test_tests13class TestTestsCase(object):12class TestTestsCase:13 def test_defined(self, env):14 tmpl = env.from_string("{{ missing is defined }}|{{ true is defined }}")15 assert tmpl.render() == "False|True"16
92 unmodified lines
109 ("range is callable", True),110 ),111 )112 def test_types(self, env, op, expect):114 t = env.from_string("{{{{ {op} }}}}".format(op=op))113 t = env.from_string(f"{{{{ {op} }}}}")114 assert t.render(mydict=MyDict(), complex=complex(1, 2)) == str(expect)115116 def test_upper(self, env):117 tmpl = env.from_string('{{ "FOO" is upper }}|{{ "foo" is upper }}')
32 unmodified lines
150 ("ge 3", False),151 ),152 )153 def test_compare_aliases(self, env, op, expect):155 t = env.from_string("{{{{ 2 is {op} }}}}".format(op=op))154 t = env.from_string(f"{{{{ 2 is {op} }}}}")155 assert t.render() == str(expect)156157 def test_sameas(self, env):158 tmpl = env.from_string("{{ foo is sameas false }}|{{ 0 is sameas false }}")
51 unmodified lines
modified:tests/test_utils.py+14 added-24 removed
1# -*- coding: utf-8 -*-1import pickle2import random3from collections import deque4from copy import copy as shallow_copy56import pytest7from markupsafe import Markup810from jinja2._compat import range_type11from jinja2._compat import string_types9from jinja2.utils import consume10from jinja2.utils import generate_lorem_ipsum11from jinja2.utils import LRUCache12from jinja2.utils import missing
3 unmodified lines
161718@pytest.mark.utils19@pytest.mark.lrucache23class TestLRUCache(object):20class TestLRUCache:21 def test_simple(self):22 d = LRUCache(3)23 d["a"] = 124 d["b"] = 2
2 unmodified lines
27 d["d"] = 428 assert len(d) == 329 assert "a" in d and "c" in d and "d" in d and "b" not in d3034 def test_itervalue_deprecated(self):35 cache = LRUCache(3)36 cache["a"] = 137 cache["b"] = 238 with pytest.deprecated_call():39 cache.itervalue()4031 def test_itervalues(self):32 cache = LRUCache(3)33 cache["b"] = 134 cache["a"] = 2
43 unmodified lines
78 d["a"] = 179 d["b"] = 280 d["c"] = 381 # Sort the strings - mapping is unordered92 assert sorted(repr(d)) == sorted(u"<LRUCache {'a': 1, 'b': 2, 'c': 3}>")82 assert sorted(repr(d)) == sorted("<LRUCache {'a': 1, 'b': 2, 'c': 3}>")8384 def test_items(self):85 """Test various items, keys, values and iterators of LRUCache."""86 d = LRUCache(3)
24 unmodified lines
111112113@pytest.mark.utils114@pytest.mark.helpers125class TestHelpers(object):115class TestHelpers:116 def test_object_type_repr(self):127 class X(object):117 class X:118 pass119120 assert object_type_repr(42) == "int object"121 assert object_type_repr([]) == "list object"
19 unmodified lines
141142143@pytest.mark.utils144@pytest.mark.escapeUrlizeTarget155class TestEscapeUrlizeTarget(object):145class TestEscapeUrlizeTarget:146 def test_escape_urlize_target(self):147 url = "http://example.org"148 target = "<script>"149 assert urlize(url, target=target) == (
4 unmodified lines
154155156@pytest.mark.utils157@pytest.mark.loremIpsum168class TestLoremIpsum(object):158class TestLoremIpsum:159 def test_lorem_ipsum_markup(self):160 """Test that output of lorem_ipsum is Markup by default."""161 assert isinstance(generate_lorem_ipsum(), Markup)162163 def test_lorem_ipsum_html(self):164 """Test that output of lorem_ipsum is a string_type when not html."""175 assert isinstance(generate_lorem_ipsum(html=False), string_types)165 assert isinstance(generate_lorem_ipsum(html=False), str)166167 def test_lorem_ipsum_n(self):168 """Test that the n (number of lines) works as expected."""179 assert generate_lorem_ipsum(n=0, html=False) == u""180 for n in range_type(1, 50):169 assert generate_lorem_ipsum(n=0, html=False) == ""170 for n in range(1, 50):171 assert generate_lorem_ipsum(n=n, html=False).count("\n") == (n - 1) * 2172173 def test_lorem_ipsum_min(self):174 """Test that at least min words are in the output of each line"""185 for _ in range_type(5):175 for _ in range(5):176 m = random.randrange(20, 99)187 for _ in range_type(10):177 for _ in range(10):178 assert generate_lorem_ipsum(n=1, min=m, html=False).count(" ") >= m - 1179180 def test_lorem_ipsum_max(self):181 """Test that at least max words are in the output of each line"""192 for _ in range_type(5):182 for _ in range(5):183 m = random.randrange(21, 100)194 for _ in range_type(10):184 for _ in range(10):185 assert generate_lorem_ipsum(n=1, max=m, html=False).count(" ") < m - 1186187188def test_missing():189 """Test the repr of missing."""200 assert repr(missing) == u"missing"190 assert repr(missing) == "missing"191192193def test_consume():194 """Test that consume consumes an iterator."""
4 unmodified lines
modified:.pre-commit-config.yaml+5 added
1repos:2 - repo: https://github.com/asottile/pyupgrade3 rev: v1.26.24 hooks:5 - id: pyupgrade6 args: ["--py36-plus"]7 - repo: https://github.com/asottile/reorder_python_imports8 rev: v1.9.09 hooks:10 - id: reorder-python-imports
16 unmodified lines
modified:CHANGES.rst+2 added
6 unmodified lines
78- Drop support for Python 2.7 and 3.5.9- Bump MarkupSafe dependency to >=1.1.10- Bump Babel optional dependency to >=2.1.11- Remove code that was marked deprecated.12-1314152.11.216------
748 unmodified lines
modified:setup.cfg+1 added-4 removed
1[metadata]2license_file = LICENSE.rst3long_description = file:README.rst4long_description_content_type = text/x-rst55[bdist_wheel]6universal = true76[tool:pytest]7testpaths = tests8filterwarnings =9 error12 ignore:the sets module:DeprecationWarning:jinja2.sandbox1011[coverage:run]12branch = True13source =
29 unmodified lines
modified:setup.py+1 added-6 removed
1import io1import re23from setuptools import find_packages4from setuptools import setup57with 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:6with open("src/jinja2/__init__.py", "rt", encoding="utf8") as f:7 version = re.search(r'__version__ = "(.*?)"', f.read(), re.M).group(1)89setup(10 name="Jinja2",
7 unmodified lines
18 license="BSD-3-Clause",19 maintainer="Pallets",20 maintainer_email="contact@palletsprojects.com",21 description="A very fast and expressive template engine.",26 long_description=readme,22 classifiers=[23 "Development Status :: 5 - Production/Stable",24 "Environment :: Web Environment",25 "Intended Audience :: Developers",
15 unmodified lines
modified:tox.ini+1 added-1 removed
1[tox]2envlist =3 py{38,37,36,35,27,py3,py}3 py{38,37,36,py3}4 style5 docs6skip_missing_interpreters = true7
13 unmodified lines