Merge pull request #1125 from pallets/style
Before adoption: this commit came in with the history the project adopted, so no landing records it.
move to src directory, add pre-commit
authored by David Lord · committed by GitHub · parents 8342180, 51c1c8e · Browse files · 122 files·+16948 added−18321 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
122 files+16948 added−18321 removed
- tests:+3338 added−2858 removed
- other:+13610 added−15463 removed
Provenance
- Commit
42d4a4e- Tree
136e569- Author
David Lord <davidism@gmail.com>- Committer
GitHub <noreply@github.com>- Parent 1
8342180- Parent 2
51c1c8e
122 files changed+16948 added−18321 removed
added:docs/examples/cache_extension.py+54 added
1+from jinja2 import nodes2+from jinja2.ext import Extension3+4+5+class FragmentCacheExtension(Extension):6+ # a set of names that trigger the extension.7+ tags = {"cache"}8+9+ def __init__(self, environment):10+ super(FragmentCacheExtension, self).__init__(environment)11+12+ # add the defaults to the environment13+ environment.extend(fragment_cache_prefix="", fragment_cache=None)14+15+ def parse(self, parser):16+ # the first token is the token that started the tag. In our case17+ # we only listen to ``'cache'`` so this will be a name token with18+ # `cache` as value. We get the line number so that we can give19+ # that line number to the nodes we create by hand.20+ lineno = next(parser.stream).lineno21+22+ # now we parse a single expression that is used as cache key.23+ args = [parser.parse_expression()]24+25+ # if there is a comma, the user provided a timeout. If not use26+ # None as second parameter.27+ if parser.stream.skip_if("comma"):28+ args.append(parser.parse_expression())29+ else:30+ args.append(nodes.Const(None))31+32+ # now we parse the body of the cache block up to `endcache` and33+ # drop the needle (which would always be `endcache` in that case)34+ body = parser.parse_statements(["name:endcache"], drop_needle=True)35+36+ # now return a `CallBlock` node that calls our _cache_support37+ # helper method on this extension.38+ return nodes.CallBlock(39+ self.call_method("_cache_support", args), [], [], body40+ ).set_lineno(lineno)41+42+ def _cache_support(self, name, timeout, caller):43+ """Helper callback."""44+ key = self.environment.fragment_cache_prefix + name45+46+ # try to load the block from the cache47+ # if there is no fragment in the cache, render it and store48+ # it in the cache.49+ rv = self.environment.fragment_cache.get(key)50+ if rv is not None:51+ return rv52+ rv = caller()53+ self.environment.fragment_cache.add(key, rv, timeout)54+ return rvadded:docs/examples/inline_gettext_extension.py+73 added
1+# -*- coding: utf-8 -*-2+import re3+4+from jinja2.exceptions import TemplateSyntaxError5+from jinja2.ext import Extension6+from jinja2.lexer import count_newlines7+from jinja2.lexer import Token8+9+10+_outside_re = re.compile(r"\\?(gettext|_)\(")11+_inside_re = re.compile(r"\\?[()]")12+13+14+class InlineGettext(Extension):15+ """This extension implements support for inline gettext blocks::16+17+ <h1>_(Welcome)</h1>18+ <p>_(This is a paragraph)</p>19+20+ Requires the i18n extension to be loaded and configured.21+ """22+23+ def filter_stream(self, stream):24+ paren_stack = 025+26+ for token in stream:27+ if token.type != "data":28+ yield token29+ continue30+31+ pos = 032+ lineno = token.lineno33+34+ while 1:35+ if not paren_stack:36+ match = _outside_re.search(token.value, pos)37+ else:38+ match = _inside_re.search(token.value, pos)39+ if match is None:40+ break41+ new_pos = match.start()42+ if new_pos > pos:43+ preval = token.value[pos:new_pos]44+ yield Token(lineno, "data", preval)45+ lineno += count_newlines(preval)46+ gtok = match.group()47+ if gtok[0] == "\\":48+ yield Token(lineno, "data", gtok[1:])49+ elif not paren_stack:50+ yield Token(lineno, "block_begin", None)51+ yield Token(lineno, "name", "trans")52+ yield Token(lineno, "block_end", None)53+ paren_stack = 154+ else:55+ if gtok == "(" or paren_stack > 1:56+ yield Token(lineno, "data", gtok)57+ paren_stack += gtok == ")" and -1 or 158+ if not paren_stack:59+ yield Token(lineno, "block_begin", None)60+ yield Token(lineno, "name", "endtrans")61+ yield Token(lineno, "block_end", None)62+ pos = match.end()63+64+ if pos < len(token.value):65+ yield Token(lineno, "data", token.value[pos:])66+67+ if paren_stack:68+ raise TemplateSyntaxError(69+ "unclosed gettext expression",70+ token.lineno,71+ stream.name,72+ stream.filename,73+ )deleted:docs/cache_extension.py-56 removed
1-from jinja2 import nodes2-from jinja2.ext import Extension3-4-5-class FragmentCacheExtension(Extension):6- # a set of names that trigger the extension.7- tags = {'cache'}8-9- def __init__(self, environment):10- super(FragmentCacheExtension, self).__init__(environment)11-12- # add the defaults to the environment13- environment.extend(14- fragment_cache_prefix='',15- fragment_cache=None16- )17-18- def parse(self, parser):19- # the first token is the token that started the tag. In our case20- # we only listen to ``'cache'`` so this will be a name token with21- # `cache` as value. We get the line number so that we can give22- # that line number to the nodes we create by hand.23- lineno = next(parser.stream).lineno24-25- # now we parse a single expression that is used as cache key.26- args = [parser.parse_expression()]27-28- # if there is a comma, the user provided a timeout. If not use29- # None as second parameter.30- if parser.stream.skip_if('comma'):31- args.append(parser.parse_expression())32- else:33- args.append(nodes.Const(None))34-35- # now we parse the body of the cache block up to `endcache` and36- # drop the needle (which would always be `endcache` in that case)37- body = parser.parse_statements(['name:endcache'], drop_needle=True)38-39- # now return a `CallBlock` node that calls our _cache_support40- # helper method on this extension.41- return nodes.CallBlock(self.call_method('_cache_support', args),42- [], [], body).set_lineno(lineno)43-44- def _cache_support(self, name, timeout, caller):45- """Helper callback."""46- key = self.environment.fragment_cache_prefix + name47-48- # try to load the block from the cache49- # if there is no fragment in the cache, render it and store50- # it in the cache.51- rv = self.environment.fragment_cache.get(key)52- if rv is not None:53- return rv54- rv = caller()55- self.environment.fragment_cache.add(key, rv, timeout)56- return rvmodified:docs/extensions.rst+34 added-6 removed
252 unmodified lines253 errors that are horrible to debug. Always make sure you are using the nodes254 you create correctly. The API documentation below shows which nodes exist and255 how to use them.256 257-Example Extension258-~~~~~~~~~~~~~~~~~257 258+Example Extensions259+------------------260+261+Cache262+~~~~~263+264 The following example implements a ``cache`` tag for Jinja by using the265 `cachelib`_ library:266 263-.. literalinclude:: cache_extension.py267+.. literalinclude:: examples/cache_extension.py268 :language: python269 270 And here is how you use it in an environment::271 15 unmodified lines287 {% endcache %}288 289 .. _cachelib: https://github.com/pallets/cachelib290 291+292+Inline ``gettext``293+~~~~~~~~~~~~~~~~~~294+295+The following example demonstrates using :meth:`Extension.filter_stream`296+to parse calls to the ``_()`` gettext function inline with static data297+without needing Jinja blocks.298+299+.. code-block:: html300+301+ <h1>_(Welcome)</h1>302+ <p>_(This is a paragraph)</p>303+304+It requires the i18n extension to be loaded and configured.305+306+.. literalinclude:: examples/inline_gettext_extension.py307+ :language: python308+309+310 Extension API288-~~~~~~~~~~~~~311+-------------312 313+Extension314+~~~~~~~~~315+316 Extensions always have to extend the :class:`jinja2.ext.Extension` class:317 318 .. autoclass:: Extension319 :members: preprocess, filter_stream, parse, attr, call_method7 unmodified lines327 328 If the extension implements custom tags this is a set of tag names329 the extension is listening for.330 305-Parser API306-~~~~~~~~~~331 332+Parser333+~~~~~~334+335 The parser passed to :meth:`Extension.parse` provides ways to parse336 expressions of different types. The following methods may be used by337 extensions:338 43 unmodified lines382 characters in strings:383 384 .. autofunction:: jinja2.lexer.count_newlines385 386+387 AST388 ~~~389 390 The AST (Abstract Syntax Tree) is used to represent a template after parsing.14 unmodified linesmodified:examples/basic/cycle.py+10 added-6 removed
1 from __future__ import print_function2+3 from jinja2 import Environment4 4-5-env = Environment(line_statement_prefix="#", variable_start_string="${", variable_end_string="}")6-7-8-print(env.from_string("""\5+env = Environment(6+ line_statement_prefix="#", variable_start_string="${", variable_end_string="}"7+)8+print(9+ env.from_string(10+ """\11 <ul>12 # for item in range(10)13 <li class="${loop.cycle('odd', 'even')}">${item}</li>14 # endfor15 </ul>\14-""").render())16+"""17+ ).render()18+)modified:examples/basic/debugger.py+3 added-3 removed
1 from __future__ import print_function2+3 from jinja2 import Environment4 from jinja2.loaders import FileSystemLoader5 5-env = Environment(loader=FileSystemLoader('templates'))6-7-tmpl = env.get_template('broken.html')6+env = Environment(loader=FileSystemLoader("templates"))7+tmpl = env.get_template("broken.html")8 print(tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1]))modified:examples/basic/inheritance.py+11 added-9 removed
1 from __future__ import print_function2+3 from jinja2 import Environment4 from jinja2.loaders import DictLoader5 5-6-env = Environment(loader=DictLoader({7-'a': '''[A[{% block body %}{% endblock %}]]''',8-'b': '''{% extends 'a' %}{% block body %}[B]{% endblock %}''',9-'c': '''{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}'''10-}))11-12-13-print(env.get_template('c').render())6+env = Environment(7+ loader=DictLoader(8+ {9+ "a": "[A[{% block body %}{% endblock %}]]",10+ "b": "{% extends 'a' %}{% block body %}[B]{% endblock %}",11+ "c": "{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}",12+ }13+ )14+)15+print(env.get_template("c").render())modified:examples/basic/test_filter_and_linestatements.py+8 added-5 removed
1 from __future__ import print_function2+3 from jinja2 import Environment4 4-5-env = Environment(line_statement_prefix='%', variable_start_string="${", variable_end_string="}")6-tmpl = env.from_string("""\5+env = Environment(6+ line_statement_prefix="%", variable_start_string="${", variable_end_string="}"7+)8+tmpl = env.from_string(9+ """\10 % macro foo()11 ${caller(42)}12 % endmacro13 <ul>9 unmodified lines23 % for item in [1, 2, 3]24 - ${item}25 % endfor26 % endfilter24-""")25-27+"""28+)29 print(tmpl.render(seq=range(10)))modified:examples/basic/test_loop_filter.py+5 added-3 removed
1 from __future__ import print_function2+3 from jinja2 import Environment4 4-tmpl = Environment().from_string("""\5+tmpl = Environment().from_string(6+ """\7 <ul>8 {%- for item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if item % 2 == 0 %}9 <li>{{ loop.index }} / {{ loop.length }}: {{ item }}</li>10 {%- endfor %}11 </ul>12 if condition: {{ 1 if foo else 0 }}11-""")12-13+"""14+)15 print(tmpl.render(foo=True))modified:examples/basic/test.py+13 added-10 removed
1 from __future__ import print_function2+3 from jinja2 import Environment4 from jinja2.loaders import DictLoader5 5-env = Environment(loader=DictLoader({6-'child.html': u'''\6+env = Environment(7+ loader=DictLoader(8+ {9+ "child.html": u"""\10 {% extends master_layout or 'master.html' %}11 {% include helpers = 'helpers.html' %}12 {% macro get_the_answer() %}42{% endmacro %}13 {% title = 'Hello World' %}14 {% block body %}15 {{ get_the_answer() }}16 {{ helpers.conspirate() }}17 {% endblock %}15-''',16-'master.html': u'''\18+""",19+ "master.html": u"""\20 <!doctype html>21 <title>{{ title }}</title>22 {% block body %}{% endblock %}20-''',21-'helpers.html': u'''\23+""",24+ "helpers.html": u"""\25 {% macro conspirate() %}23{% endmacro %}23-'''24-}))25-26-26+""",27+ }28+ )29+)30 tmpl = env.get_template("child.html")31 print(tmpl.render())modified:examples/basic/translate.py+15 added-10 removed
1 from __future__ import print_function2+3 from jinja2 import Environment4 4-env = Environment(extensions=['jinja2.ext.i18n'])5-env.globals['gettext'] = {6- 'Hello %(user)s!': 'Hallo %(user)s!'7-}.__getitem__8-env.globals['ngettext'] = lambda s, p, n: {9- '%(count)s user': '%(count)d Benutzer',10- '%(count)s users': '%(count)d Benutzer'5+env = Environment(extensions=["jinja2.ext.i18n"])6+env.globals["gettext"] = {"Hello %(user)s!": "Hallo %(user)s!"}.__getitem__7+env.globals["ngettext"] = lambda s, p, n: {8+ "%(count)s user": "%(count)d Benutzer",9+ "%(count)s users": "%(count)d Benutzer",10 }[n == 1 and s or p]12-print(env.from_string("""\11+print(12+ env.from_string(13+ """\14 {% trans %}Hello {{ user }}!{% endtrans %}14-{% trans count=users|count %}{{ count }} user{% pluralize %}{{ count }} users{% endtrans %}15-""").render(user="someone", users=[1, 2, 3]))15+{% trans count=users|count -%}16+{{ count }} user{% pluralize %}{{ count }} users17+{% endtrans %}18+"""19+ ).render(user="someone", users=[1, 2, 3])20+)deleted:examples/rwbench/django/_form.html-1 removed
1-<form action="{{ action }}" method="{{ method }}">{{ body }}</form>deleted:examples/rwbench/django/_input_field.html-1 removed
1-<input type="{{ type }}" value="{{ value }}" name="{{ name }}">deleted:examples/rwbench/django/_textarea.html-1 removed
1-<textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols }}">{{ value }}</textarea>deleted:examples/rwbench/django/index.html-29 removed
1-{% extends "layout.html" %}2-{% block page_title %}Index Page{% endblock %}3-{% block body %}4- {% for article in articles %}5- {% if article.published %}6- <div class="article">7- <h2><a href="{{ article.href }}">{{ article.title }}</a></h2>8- <p class="meta">written by <a href="{{ article.user.href }}">{{ article.user.username }}</a> on {{ article.pub_date|dateformat }}</p>9- <div class="text">{{ article.body|safe }}</div>10- </div>11- {% endif %}12- {% endfor %}13- {% form %}14- <dl>15- <dt>Name</dt>16- <dd>{% input_field 'name' %}</dd>17- <dt>E-Mail</dt>18- <dd>{% input_field 'email' %}</dd>19- <dt>URL</dt>20- <dd>{% input_field 'url' %}</dd>21- <dt>Comment</dt>22- <dd>{% textarea 'comment' %}</dd>23- <dt>Captcha</dt>24- <dd>{% input_field 'captcha' %}</dd>25- </dl>26- {% input_field '' 'submit' 'Submit' %}27- {% input_field 'cancel' 'submit' 'Cancel' %}28- {% endform %}29-{% endblock %}deleted:examples/rwbench/django/layout.html-29 removed
1-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">2-<html>3-<head>4- <title>{% block page_title %}{% endblock %} | RealWorld Benchmark</title>5- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">6-</head>7-<body>8- <div class="contents">9- <div class="header">10- <h1>RealWorld Benchmark</h1>11- <blockquote><p>12- A less stupid benchmark for Mako and Jinja to get an impression how13- code changes affect runtime performance.14- </p></blockquote>15- </div>16- <ul class="navigation">17- {% for href, caption in page_navigation %}18- <li><a href="{{ href }}">{{ caption }}</a></li>19- {% endfor %}20- </ul>21- <div class="body">22- {% block body %}{% endblock %}23- </div>24- <div class="footer">25- © Copyright 2008 by I don't know who.26- </div>27- </div>28-</body>29-</html>deleted:examples/rwbench/genshi/helpers.html-12 removed
1-<div xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/"2- py:strip="">3-4- <py:def function="input_field(name='', value='', type='text')">5- <input type="$type" value="$value" name="$name" />6- </py:def>7-8- <py:def function="textarea(name, value='', rows=10, cols=40)">9- <textarea name="$name" rows="$rows" cols="cols">$value</textarea>10- </py:def>11-12-</div>deleted:examples/rwbench/genshi/index.html-41 removed
1-<?python2- from rwbench import dateformat3-?>4-<html xmlns="http://www.w3.org/1999/xhtml" xmlns:xi="http://www.w3.org/2001/XInclude"5- xmlns:py="http://genshi.edgewall.org/">6- <xi:include href="layout.html" />7- <xi:include href="helpers.html" />8- <head><title>Index Page</title></head>9- <body>10- <div class="article" py:for="article in articles">11- <py:if test="article.published">12- <h2><a href="${article.href}">${article.title}</a></h2>13- <p class="meta">written by <a href="${article.user.href}"14- >${article.user.username}</a> on ${dateformat(article.pub_date)}</p>15- <div class="text">${Markup(article.body)}</div>16- </py:if>17- </div>18- <!--19- For a fair and balanced comparison we would have to use a def here20- that wraps the form data but I don't know what would be the best21- Genshi equivalent for that. Quite frankly I doubt that this makes22- sense in Genshi anyways.23- -->24- <form action="" method="post">25- <dl>26- <dt>Name</dt>27- <dd>${input_field('name')}</dd>28- <dt>E-Mail</dt>29- <dd>${input_field('email')}</dd>30- <dt>URL</dt>31- <dd>${input_field('url')}</dd>32- <dt>Comment</dt>33- <dd>${textarea('comment')}</dd>34- <dt>Captcha</dt>35- <dd>${input_field('captcha')}</dd>36- </dl>37- ${input_field(type='submit', value='Submit')}38- ${input_field(name='cancel', type='submit', value='Cancel')}39- </form>40- </body>41-</html>deleted:examples/rwbench/genshi/layout.html-30 removed
1-<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/" >2- <py:match path="head" once="true">3- <head>4- <title>${select('title/text()')} | RealWorld Benchmark</title>5- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />6- </head>7- </py:match>8- <py:match path="body" once="true">9- <body>10- <div class="contents">11- <div class="header">12- <h1>RealWorld Benchmark</h1>13- <blockquote><p>14- A less stupid benchmark for Mako and Jinja to get an impression how15- code changes affect runtime performance.16- </p></blockquote>17- </div>18- <ul class="navigation">19- <li py:for="href, caption in page_navigation"><a href="$href">$caption</a></li>20- </ul>21- <div class="body">22- ${select('*|text()')}23- </div>24- <div class="footer">25- © Copyright 2008 by I don't know who.26- </div>27- </div>28- </body>29- </py:match>30-</html>deleted:examples/rwbench/jinja/helpers.html-12 removed
1-{% macro input_field(name, value='', type='text') -%}2- <input type="{{ type }}" value="{{ value|e }}" name="{{ name }}">3-{%- endmacro %}4-5-{% macro textarea(name, value='', rows=10, cols=40) -%}6- <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols }}">{{7- value|e }}</textarea>8-{%- endmacro %}9-10-{% macro form(action='', method='post') -%}11- <form action="{{ action|e }}" method="{{ method }}">{{ caller() }}</form>12-{%- endmacro %}deleted:examples/rwbench/jinja/index.html-29 removed
1-{% extends "layout.html" %}2-{% from "helpers.html" import input_field, textarea, form %}3-{% block page_title %}Index Page{% endblock %}4-{% block body %}5- {%- for article in articles if article.published %}6- <div class="article">7- <h2><a href="{{ article.href|e }}">{{ article.title|e }}</a></h2>8- <p class="meta">written by <a href="{{ article.user.href|e9- }}">{{ article.user.username|e }}</a> on {{ article.pub_date|dateformat }}</p>10- <div class="text">{{ article.body }}</div>11- </div>12- {%- endfor %}13- {%- call form() %}14- <dl>15- <dt>Name</dt>16- <dd>{{ input_field('name') }}</dd>17- <dt>E-Mail</dt>18- <dd>{{ input_field('email') }}</dd>19- <dt>URL</dt>20- <dd>{{ input_field('url') }}</dd>21- <dt>Comment</dt>22- <dd>{{ textarea('comment') }}</dd>23- <dt>Captcha</dt>24- <dd>{{ input_field('captcha') }}</dd>25- </dl>26- {{ input_field(type='submit', value='Submit') }}27- {{ input_field('cancel', type='submit', value='Cancel') }}28- {%- endcall %}29-{% endblock %}deleted:examples/rwbench/jinja/layout.html-29 removed
1-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">2-<html>3-<head>4- <title>{% block page_title %}{% endblock %} | RealWorld Benchmark</title>5- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">6-</head>7-<body>8- <div class="contents">9- <div class="header">10- <h1>RealWorld Benchmark</h1>11- <blockquote><p>12- A less stupid benchmark for Mako and Jinja to get an impression how13- code changes affect runtime performance.14- </p></blockquote>15- </div>16- <ul class="navigation">17- {%- for href, caption in page_navigation %}18- <li><a href="{{ href|e }}">{{ caption }}</a></li>19- {%- endfor %}20- </ul>21- <div class="body">22- {% block body %}{% endblock %}23- </div>24- <div class="footer">25- © Copyright 2008 by I don't know who.26- </div>27- </div>28-</body>29-</html>deleted:examples/rwbench/mako/helpers.html-11 removed
1-<%def name="input_field(name='', value='', type='text')">2- <input type="${type}" value="${value|h}" name="${name}">3-</%def>4-5-<%def name="textarea(name, value='', rows=10, cols=40)">6- <textarea name="${name}" rows="${rows}" cols="${cols}">${value|h}</textarea>7-</%def>8-9-<%def name="form(action='', method='post')">10- <form action="${action|h}" method="${method}">${caller.body()}</form>11-</%def>deleted:examples/rwbench/mako/index.html-31 removed
1-<%!2- from rwbench import dateformat3-%>4-<%inherit file="layout.html" />5-<%namespace file="helpers.html" import="input_field, textarea, form" />6-<%def name="page_title()">Index Page</%def>7-% for article in articles:8- <% if not article.published: continue %>9-<div class="article">10- <h2><a href="${article.href|h}">${article.title|h}</a></h2>11- <p class="meta">written by <a href="${article.user.href|h12- }">${article.user.username|h}</a> on ${dateformat(article.pub_date)}</p>13- <div class="text">${article.body}</div>14-</div>15-% endfor16-<%call expr="form()">17- <dl>18- <dt>Name</dt>19- <dd>${input_field('name')}</dd>20- <dt>E-Mail</dt>21- <dd>${input_field('email')}</dd>22- <dt>URL</dt>23- <dd>${input_field('url')}</dd>24- <dt>Comment</dt>25- <dd>${textarea('comment')}</dd>26- <dt>Captcha</dt>27- <dd>${input_field('captcha')}</dd>28- </dl>29- ${input_field(type='submit', value='Submit')}30- ${input_field(name='cancel', type='submit', value='Cancel')}31-</%call>deleted:examples/rwbench/mako/layout.html-30 removed
1-<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">2-<html>3-<head>4- <title>${self.page_title()} | RealWorld Benchmark</title>5- <meta http-equiv="Content-Type" content="text/html; charset=utf-8">6-</head>7-<body>8- <div class="contents">9- <div class="header">10- <h1>RealWorld Benchmark</h1>11- <blockquote><p>12- A less stupid benchmark for Mako and Jinja to get an impression how13- code changes affect runtime performance.14- </p></blockquote>15- </div>16- <ul class="navigation">17- % for href, caption in page_navigation:18- <li><a href="${href|h}">${caption}</a></li>19- % endfor20- </ul>21- <div class="body">22- ${self.body()}23- </div>24- <div class="footer">25- © Copyright 2008 by I don't know who.26- </div>27- </div>28-</body>29-</html>30-<%def name="page_title()"></%def>deleted:examples/rwbench/djangoext.py-135 removed
1-# -*- coding: utf-8 -*-2-from rwbench import ROOT3-from os.path import join4-from django.conf import settings5-settings.configure(6- TEMPLATE_DIRS=(join(ROOT, 'django'),),7- TEMPLATE_LOADERS=(8- ('django.template.loaders.cached.Loader', (9- 'django.template.loaders.filesystem.Loader',10- )),11- )12-)13-from django.template import loader as django_loader, Context as DjangoContext, \14- Node, NodeList, Variable, TokenParser15-from django import template as django_template_module16-from django.template import Library17-18-19-# for django extensions. We monkey patch our extensions in so that20-# we don't have to initialize a more complex django setup.21-django_extensions = django_template_module.Library()22-django_template_module.builtins.append(django_extensions)23-24-25-from rwbench import dateformat26-django_extensions.filter(dateformat)27-28-29-def var_or_none(x):30- if x is not None:31- return Variable(x)32-33-34-# and more django extensions35-@django_extensions.tag36-def input_field(parser, token):37- p = TokenParser(token.contents)38- args = [p.value()]39- while p.more():40- args.append(p.value())41- return InputFieldNode(*args)42-43-44-@django_extensions.tag45-def textarea(parser, token):46- p = TokenParser(token.contents)47- args = [p.value()]48- while p.more():49- args.append(p.value())50- return TextareaNode(*args)51-52-53-@django_extensions.tag54-def form(parser, token):55- p = TokenParser(token.contents)56- args = []57- while p.more():58- args.append(p.value())59- body = parser.parse(('endform',))60- parser.delete_first_token()61- return FormNode(body, *args)62-63-64-class InputFieldNode(Node):65-66- def __init__(self, name, type=None, value=None):67- self.name = var_or_none(name)68- self.type = var_or_none(type)69- self.value = var_or_none(value)70-71- def render(self, context):72- name = self.name.resolve(context)73- type = 'text'74- value = ''75- if self.type is not None:76- type = self.type.resolve(context)77- if self.value is not None:78- value = self.value.resolve(context)79- tmpl = django_loader.get_template('_input_field.html')80- return tmpl.render(DjangoContext({81- 'name': name,82- 'type': type,83- 'value': value84- }))85-86-87-class TextareaNode(Node):88-89- def __init__(self, name, rows=None, cols=None, value=None):90- self.name = var_or_none(name)91- self.rows = var_or_none(rows)92- self.cols = var_or_none(cols)93- self.value = var_or_none(value)94-95- def render(self, context):96- name = self.name.resolve(context)97- rows = 1098- cols = 4099- value = ''100- if self.rows is not None:101- rows = int(self.rows.resolve(context))102- if self.cols is not None:103- cols = int(self.cols.resolve(context))104- if self.value is not None:105- value = self.value.resolve(context)106- tmpl = django_loader.get_template('_textarea.html')107- return tmpl.render(DjangoContext({108- 'name': name,109- 'rows': rows,110- 'cols': cols,111- 'value': value112- }))113-114-115-class FormNode(Node):116-117- def __init__(self, body, action=None, method=None):118- self.body = body119- self.action = action120- self.method = method121-122- def render(self, context):123- body = self.body.render(context)124- action = ''125- method = 'post'126- if self.action is not None:127- action = self.action.resolve(context)128- if self.method is not None:129- method = self.method.resolve(context)130- tmpl = django_loader.get_template('_form.html')131- return tmpl.render(DjangoContext({132- 'body': body,133- 'action': action,134- 'method': method135- }))deleted:examples/rwbench/rwbench.py-113 removed
1-# -*- coding: utf-8 -*-2-"""3- RealWorldish Benchmark4- ~~~~~~~~~~~~~~~~~~~~~~5-6- A more real-world benchmark of Jinja. Like the other benchmark in the7- Jinja repository this has no real-world usefulnes (despite the name).8- Just go away and ignore it. NOW!9-10- :copyright: (c) 2009 by the Jinja Team.11- :license: BSD.12-"""13-from __future__ import print_function14-import sys15-from os.path import join, dirname, abspath16-try:17- from cProfile import Profile18-except ImportError:19- from profile import Profile20-from pstats import Stats21-ROOT = abspath(dirname(__file__))22-23-from random import choice, randrange24-from datetime import datetime25-from timeit import Timer26-from jinja2 import Environment, FileSystemLoader27-from jinja2.utils import generate_lorem_ipsum28-from mako.lookup import TemplateLookup29-from genshi.template import TemplateLoader as GenshiTemplateLoader30-31-32-def dateformat(x):33- return x.strftime('%Y-%m-%d')34-35-36-jinja_env = Environment(loader=FileSystemLoader(join(ROOT, 'jinja')))37-jinja_env.filters['dateformat'] = dateformat38-mako_lookup = TemplateLookup(directories=[join(ROOT, 'mako')])39-genshi_loader = GenshiTemplateLoader([join(ROOT, 'genshi')])40-41-class Article(object):42-43- def __init__(self, id):44- self.id = id45- self.href = '/article/%d' % self.id46- self.title = generate_lorem_ipsum(1, False, 5, 10)47- self.user = choice(users)48- self.body = generate_lorem_ipsum()49- self.pub_date = datetime.utcfromtimestamp(randrange(10 ** 9, 2 * 10 ** 9))50- self.published = True51-52-53-class User(object):54-55- def __init__(self, username):56- self.href = '/user/%s' % username57- self.username = username58-59-60-users = map(User, [u'John Doe', u'Jane Doe', u'Peter Somewhat'])61-articles = map(Article, range(20))62-navigation = [63- ('index', 'Index'),64- ('about', 'About'),65- ('foo?bar=1', 'Foo with Bar'),66- ('foo?bar=2&s=x', 'Foo with X'),67- ('blah', 'Blub Blah'),68- ('hehe', 'Haha'),69-] * 570-71-context = dict(users=users, articles=articles, page_navigation=navigation)72-73-74-jinja_template = jinja_env.get_template('index.html')75-mako_template = mako_lookup.get_template('index.html')76-genshi_template = genshi_loader.load('index.html')77-78-79-def test_jinja():80- jinja_template.render(context)81-82-def test_mako():83- mako_template.render_unicode(**context)84-85-86-from djangoext import django_loader, DjangoContext87-def test_django():88- # not cached because django is not thread safe and does89- # not cache by itself so it would be unfair to cache it here.90- django_template = django_loader.get_template('index.html')91- django_template.render(DjangoContext(context))92-93-94-def test_genshi():95- genshi_template.generate(**context).render('html', doctype='html')96-97-98-if __name__ == '__main__':99- sys.stdout.write('Realworldish Benchmark:\n')100- for test in 'jinja', 'mako', 'django', 'genshi':101- t = Timer(setup='from __main__ import test_%s as bench' % test,102- stmt='bench()')103- sys.stdout.write(' >> %-20s<running>' % test)104- sys.stdout.flush()105- sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=200) / 200))106-107- if '-p' in sys.argv:108- print('Jinja profile')109- p = Profile()110- p.runcall(test_jinja)111- stats = Stats(p)112- stats.sort_stats('time', 'calls')113- stats.print_stats()deleted:examples/bench.py-433 removed
1-"""\2- This benchmark compares some python templating engines with Jinja so3- that we get a picture of how fast Jinja is for a semi real world4- template. If a template engine is not installed the test is skipped.\5-"""6-import sys7-import cgi8-from timeit import Timer9-from jinja2 import Environment as JinjaEnvironment10-11-context = {12- 'page_title': 'mitsuhiko\'s benchmark',13- 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)]14-}15-16-jinja_template = JinjaEnvironment(17- line_statement_prefix='%',18- variable_start_string="${",19- variable_end_string="}"20-).from_string("""\21-<!doctype html>22-<html>23- <head>24- <title>${page_title|e}</title>25- </head>26- <body>27- <div class="header">28- <h1>${page_title|e}</h1>29- </div>30- <ul class="navigation">31- % for href, caption in [32- ('index.html', 'Index'),33- ('downloads.html', 'Downloads'),34- ('products.html', 'Products')35- ]36- <li><a href="${href|e}">${caption|e}</a></li>37- % endfor38- </ul>39- <div class="table">40- <table>41- % for row in table42- <tr>43- % for cell in row44- <td>${cell}</td>45- % endfor46- </tr>47- % endfor48- </table>49- </div>50- </body>51-</html>\52-""")53-54-def test_jinja():55- jinja_template.render(context)56-57-try:58- from tornado.template import Template59-except ImportError:60- test_tornado = None61-else:62- tornado_template = Template("""\63-<!doctype html>64-<html>65- <head>66- <title>{{ page_title }}</title>67- </head>68- <body>69- <div class="header">70- <h1>{{ page_title }}</h1>71- </div>72- <ul class="navigation">73- {% for href, caption in [ \74- ('index.html', 'Index'), \75- ('downloads.html', 'Downloads'), \76- ('products.html', 'Products') \77- ] %}78- <li><a href="{{ href }}">{{ caption }}</a></li>79- {% end %}80- </ul>81- <div class="table">82- <table>83- {% for row in table %}84- <tr>85- {% for cell in row %}86- <td>{{ cell }}</td>87- {% end %}88- </tr>89- {% end %}90- </table>91- </div>92- </body>93-</html>\94-""")95-96- def test_tornado():97- tornado_template.generate(**context)98-99-try:100- from django.conf import settings101- settings.configure()102- from django.template import Template as DjangoTemplate, Context as DjangoContext103-except ImportError:104- test_django = None105-else:106- django_template = DjangoTemplate("""\107-<!doctype html>108-<html>109- <head>110- <title>{{ page_title }}</title>111- </head>112- <body>113- <div class="header">114- <h1>{{ page_title }}</h1>115- </div>116- <ul class="navigation">117- {% for href, caption in navigation %}118- <li><a href="{{ href }}">{{ caption }}</a></li>119- {% endfor %}120- </ul>121- <div class="table">122- <table>123- {% for row in table %}124- <tr>125- {% for cell in row %}126- <td>{{ cell }}</td>127- {% endfor %}128- </tr>129- {% endfor %}130- </table>131- </div>132- </body>133-</html>\134-""")135-136- def test_django():137- c = DjangoContext(context)138- c['navigation'] = [('index.html', 'Index'), ('downloads.html', 'Downloads'),139- ('products.html', 'Products')]140- django_template.render(c)141-142-try:143- from mako.template import Template as MakoTemplate144-except ImportError:145- test_mako = None146-else:147- mako_template = MakoTemplate("""\148-<!doctype html>149-<html>150- <head>151- <title>${page_title|h}</title>152- </head>153- <body>154- <div class="header">155- <h1>${page_title|h}</h1>156- </div>157- <ul class="navigation">158- % for href, caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]:159- <li><a href="${href|h}">${caption|h}</a></li>160- % endfor161- </ul>162- <div class="table">163- <table>164- % for row in table:165- <tr>166- % for cell in row:167- <td>${cell}</td>168- % endfor169- </tr>170- % endfor171- </table>172- </div>173- </body>174-</html>\175-""")176-177- def test_mako():178- mako_template.render(**context)179-180-try:181- from genshi.template import MarkupTemplate as GenshiTemplate182-except ImportError:183- test_genshi = None184-else:185- genshi_template = GenshiTemplate("""\186-<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/">187- <head>188- <title>${page_title}</title>189- </head>190- <body>191- <div class="header">192- <h1>${page_title}</h1>193- </div>194- <ul class="navigation">195- <li py:for="href, caption in [196- ('index.html', 'Index'),197- ('downloads.html', 'Downloads'),198- ('products.html', 'Products')]"><a href="${href}">${caption}</a></li>199- </ul>200- <div class="table">201- <table>202- <tr py:for="row in table">203- <td py:for="cell in row">${cell}</td>204- </tr>205- </table>206- </div>207- </body>208-</html>\209-""")210-211- def test_genshi():212- genshi_template.generate(**context).render('html', strip_whitespace=False)213-214-try:215- from Cheetah.Template import Template as CheetahTemplate216-except ImportError:217- test_cheetah = None218-else:219- cheetah_template = CheetahTemplate("""\220-#import cgi221-<!doctype html>222-<html>223- <head>224- <title>$cgi.escape($page_title)</title>225- </head>226- <body>227- <div class="header">228- <h1>$cgi.escape($page_title)</h1>229- </div>230- <ul class="navigation">231- #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]:232- <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li>233- #end for234- </ul>235- <div class="table">236- <table>237- #for $row in $table:238- <tr>239- #for $cell in $row:240- <td>$cell</td>241- #end for242- </tr>243- #end for244- </table>245- </div>246- </body>247-</html>\248-""", searchList=[dict(context)])249-250- def test_cheetah():251- unicode(cheetah_template)252-253-try:254- import tenjin255-except ImportError:256- test_tenjin = None257-else:258- tenjin_template = tenjin.Template()259- tenjin_template.convert("""\260-<!doctype html>261-<html>262- <head>263- <title>${page_title}</title>264- </head>265- <body>266- <div class="header">267- <h1>${page_title}</h1>268- </div>269- <ul class="navigation">270-<?py for href, caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]: ?>271- <li><a href="${href}">${caption}</a></li>272-<?py #end ?>273- </ul>274- <div class="table">275- <table>276-<?py for row in table: ?>277- <tr>278-<?py for cell in row: ?>279- <td>#{cell}</td>280-<?py #end ?>281- </tr>282-<?py #end ?>283- </table>284- </div>285- </body>286-</html>\287-""")288-289- def test_tenjin():290- from tenjin.helpers import escape, to_str291- tenjin_template.render(context, locals())292-293-try:294- from spitfire.compiler import util as SpitfireTemplate295- from spitfire.compiler.analyzer import o2_options as spitfire_optimizer296-except ImportError:297- test_spitfire = None298-else:299- spitfire_template = SpitfireTemplate.load_template("""\300-<!doctype html>301-<html>302- <head>303- <title>$cgi.escape($page_title)</title>304- </head>305- <body>306- <div class="header">307- <h1>$cgi.escape($page_title)</h1>308- </div>309- <ul class="navigation">310- #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), ('products.html', 'Products')]311- <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li>312- #end for313- </ul>314- <div class="table">315- <table>316- #for $row in $table317- <tr>318- #for $cell in $row319- <td>$cell</td>320- #end for321- </tr>322- #end for323- </table>324- </div>325- </body>326-</html>\327-""", 'spitfire_tmpl', spitfire_optimizer, {'enable_filters': False})328- spitfire_context = dict(context, **{'cgi': cgi})329-330- def test_spitfire():331- spitfire_template(search_list=[spitfire_context]).main()332-333-334-try:335- from chameleon.zpt.template import PageTemplate336-except ImportError:337- test_chameleon = None338-else:339- chameleon_template = PageTemplate("""\340-<html xmlns:tal="http://xml.zope.org/namespaces/tal">341- <head>342- <title tal:content="page_title">Page Title</title>343- </head>344- <body>345- <div class="header">346- <h1 tal:content="page_title">Page Title</h1>347- </div>348- <ul class="navigation">349- <li tal:repeat="item sections"><a tal:attributes="href item[0]" tal:content="item[1]">caption</a></li>350- </ul>351- <div class="table">352- <table>353- <tr tal:repeat="row table">354- <td tal:repeat="cell row" tal:content="row[cell]">cell</td>355- </tr>356- </table>357- </div>358- </body>359-</html>\360-""")361- chameleon_context = dict(context)362- chameleon_context['sections'] = [363- ('index.html', 'Index'),364- ('downloads.html', 'Downloads'),365- ('products.html', 'Products')366- ]367- def test_chameleon():368- chameleon_template.render(**chameleon_context)369-370-try:371- from chameleon.zpt.template import PageTemplate372- from chameleon.genshi import language373-except ImportError:374- test_chameleon_genshi = None375-else:376- chameleon_genshi_template = PageTemplate("""\377-<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/">378- <head>379- <title>${page_title}</title>380- </head>381- <body>382- <div class="header">383- <h1>${page_title}</h1>384- </div>385- <ul class="navigation">386- <li py:for="info in sections"><a href="${info[0]}">${info[1]}</a></li>387- </ul>388- <div class="table">389- <table>390- <tr py:for="row in table">391- <td py:for="cell in row">${row[cell]}</td>392- </tr>393- </table>394- </div>395- </body>396-</html>\397-""", parser=language.Parser())398- chameleon_genshi_context = dict(context)399- chameleon_genshi_context['sections'] = [400- ('index.html', 'Index'),401- ('downloads.html', 'Downloads'),402- ('products.html', 'Products')403- ]404- def test_chameleon_genshi():405- chameleon_genshi_template.render(**chameleon_genshi_context)406-407-408-sys.stdout.write('\r' + '\n'.join((409- '=' * 80,410- 'Template Engine BigTable Benchmark'.center(80),411- '=' * 80,412- __doc__,413- '-' * 80414-)) + '\n')415-416-417-for test in 'jinja', 'mako', 'tornado', 'tenjin', 'spitfire', 'django', 'genshi', 'cheetah', 'chameleon', 'chameleon_genshi':418- if locals()['test_' + test] is None:419- sys.stdout.write(' %-20s*not installed*\n' % test)420- continue421- t = Timer(setup='from __main__ import test_%s as bench' % test,422- stmt='bench()')423- sys.stdout.write(' >> %-20s<running>' % test)424- sys.stdout.flush()425- sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=50) / 50))426-sys.stdout.write('-' * 80 + '\n')427-sys.stdout.write('''\428- WARNING: The results of this benchmark are useless to compare the429- performance of template engines and should not be taken seriously in any430- way. It's testing the performance of simple loops and has no real-world431- usefulnes. It only used to check if changes on the Jinja code affect432- performance in a good or bad way and how it roughly compares to others.433-''' + '=' * 80 + '\n')deleted:examples/profile.py-53 removed
1-from __future__ import print_function2-try:3- from cProfile import Profile4-except ImportError:5- from profile import Profile6-from pstats import Stats7-from jinja2 import Environment as JinjaEnvironment8-9-context = {10- 'page_title': 'mitsuhiko\'s benchmark',11- 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)]12-}13-14-source = """\15-% macro testmacro(x)16- <span>${x}</span>17-% endmacro18-<!doctype html>19-<html>20- <head>21- <title>${page_title|e}</title>22- </head>23- <body>24- <div class="header">25- <h1>${page_title|e}</h1>26- </div>27- <div class="table">28- <table>29- % for row in table30- <tr>31- % for cell in row32- <td>${testmacro(cell)}</td>33- % endfor34- </tr>35- % endfor36- </table>37- </div>38- </body>39-</html>\40-"""41-jinja_template = JinjaEnvironment(42- line_statement_prefix='%',43- variable_start_string="${",44- variable_end_string="}"45-).from_string(source)46-print(jinja_template.environment.compile(source, raw=True))47-48-49-p = Profile()50-p.runcall(lambda: jinja_template.render(context))51-stats = Stats(p)52-stats.sort_stats('time', 'calls')53-stats.print_stats()deleted:ext/django2jinja/templates/index.html-58 removed
1-{% extends "layout.html" %}2-{% load i18n %}3-{% block title %}Foo{% endblock %}4-{% block page-body %}5- {{ block.super }}6- Hello {{ name|cut:"d" }}!7-8- {% for item in seq reversed %}9- {% if forloop.index|divisibleby:2 %}10- <li class="{% cycle 'a' 'b' %}">{{ item }}</li>11- {% endif %}12- {% endfor %}13- {% ifequal foo bar %}14- haha15- {% else %}16- hmm17- {% endifequal %}18- {% filter upper %}19- {% include "subtemplate.html" %}20- {% include foo %}21- {% endfilter %}22- {% spaceless %}23- Hello World24- {{ foo }}25- Hmm26- {% endspaceless %}27- {% templatetag opencomment %}...{% templatetag closecomment %}28- {% url foo a, b, c=d %}29- {% url foo a, b, c=d as hmm %}30-31- {% with object.value as value %}32- <img src='bar.gif' height='10' width='{% widthratio value 200 100 %}'>33- {% endwith %}34-35- <pre>{% debug %}</pre>36-37- {% blocktrans with book|title as book_t and author|title as author_t %}38- This is {{ book_t }} by {{ author_t }}39- {% endblocktrans %}40-41- {% blocktrans count list|length as counter %}42- There is only one {{ name }} object.43- {% plural %}44- There are {{ counter }} {{ name }} objects.45- {% endblocktrans %}46-47- {% blocktrans with name|escape as name count list|length as counter %}48- There is only one {{ name }} object.49- {% plural %}50- There are {{ counter }} {{ name }} objects.51- {% endblocktrans %}52-53- {% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}54-55- <p>{% trans "This is the title." %}</p>56-57- {% regroup people by gender as grouped %}58-{% endblock %}deleted:ext/django2jinja/templates/layout.html-4 removed
1-<title>{% block title %}{% endblock %}</title>2-<div class="body">3- {% block page-body %}{% endblock %}4-</div>deleted:ext/django2jinja/templates/subtemplate.html-1 removed
1-Hello World!deleted:ext/django2jinja/django2jinja.py-769 removed
1-# -*- coding: utf-8 -*-2-"""3- Django to Jinja4- ~~~~~~~~~~~~~~~5-6- Helper module that can convert django templates into Jinja templates.7-8- This file is not intended to be used as stand alone application but to9- be used as library. To convert templates you basically create your own10- writer, add extra conversion logic for your custom template tags,11- configure your django environment and run the `convert_templates`12- function.13-14- Here a simple example::15-16- # configure django (or use settings.configure)17- import os18- os.environ['DJANGO_SETTINGS_MODULE'] = 'yourapplication.settings'19- from yourapplication.foo.templatetags.bar import MyNode20-21- from django2jinja import Writer, convert_templates22-23- def write_my_node(writer, node):24- writer.start_variable()25- writer.write('myfunc(')26- for idx, arg in enumerate(node.args):27- if idx:28- writer.write(', ')29- writer.node(arg)30- writer.write(')')31- writer.end_variable()32-33- writer = Writer()34- writer.node_handlers[MyNode] = write_my_node35- convert_templates('/path/to/output/folder', writer=writer)36-37- Here is an example hos to automatically translate your django38- variables to jinja2::39-40- import re41- # List of tuple (Match pattern, Replace pattern, Exclusion pattern)42-43- var_re = ((re.compile(r"(u|user)\.is_authenticated"), r"\1.is_authenticated()", None),44- (re.compile(r"\.non_field_errors"), r".non_field_errors()", None),45- (re.compile(r"\.label_tag"), r".label_tag()", None),46- (re.compile(r"\.as_dl"), r".as_dl()", None),47- (re.compile(r"\.as_table"), r".as_table()", None),48- (re.compile(r"\.as_widget"), r".as_widget()", None),49- (re.compile(r"\.as_hidden"), r".as_hidden()", None),50-51- (re.compile(r"\.get_([0-9_\w]+)_url"), r".get_\1_url()", None),52- (re.compile(r"\.url"), r".url()", re.compile(r"(form|calendar).url")),53- (re.compile(r"\.get_([0-9_\w]+)_display"), r".get_\1_display()", None),54- (re.compile(r"loop\.counter"), r"loop.index", None),55- (re.compile(r"loop\.revcounter"), r"loop.revindex", None),56- (re.compile(r"request\.GET\.([0-9_\w]+)"), r"request.GET.get('\1', '')", None),57- (re.compile(r"request\.get_host"), r"request.get_host()", None),58-59- (re.compile(r"\.all(?!_)"), r".all()", None),60- (re.compile(r"\.all\.0"), r".all()[0]", None),61- (re.compile(r"\.([0-9])($|\s+)"), r"[\1]\2", None),62- (re.compile(r"\.items"), r".items()", None),63- )64- writer = Writer(var_re=var_re)65-66- For details about the writing process have a look at the module code.67-68- :copyright: (c) 2009 by the Jinja Team.69- :license: BSD.70-"""71-from __future__ import print_function72-import re73-import os74-import sys75-from jinja2.defaults import *76-from django.conf import settings77-from django.template import defaulttags as core_tags, loader, TextNode, \78- FilterExpression, libraries, Variable, loader_tags, TOKEN_TEXT, \79- TOKEN_VAR80-from django.template.debug import DebugVariableNode as VariableNode81-from django.templatetags import i18n as i18n_tags82-from StringIO import StringIO83-84-85-_node_handlers = {}86-_resolved_filters = {}87-_newline_re = re.compile(r'(?:\r\n|\r|\n)')88-89-90-# Django stores an itertools object on the cycle node. Not only is this91-# thread unsafe but also a problem for the converter which needs the raw92-# string values passed to the constructor to create a jinja loop.cycle()93-# call from it.94-_old_cycle_init = core_tags.CycleNode.__init__95-def _fixed_cycle_init(self, cyclevars, variable_name=None):96- self.raw_cycle_vars = map(Variable, cyclevars)97- _old_cycle_init(self, cyclevars, variable_name)98-core_tags.CycleNode.__init__ = _fixed_cycle_init99-100-101-def node(cls):102- def proxy(f):103- _node_handlers[cls] = f104- return f105- return proxy106-107-108-def convert_templates(output_dir, extensions=('.html', '.txt'), writer=None,109- callback=None):110- """Iterates over all templates in the template dirs configured and111- translates them and writes the new templates into the output directory.112- """113- if writer is None:114- writer = Writer()115-116- def filter_templates(files):117- for filename in files:118- ifilename = filename.lower()119- for extension in extensions:120- if ifilename.endswith(extension):121- yield filename122-123- def translate(f, loadname):124- template = loader.get_template(loadname)125- original = writer.stream126- writer.stream = f127- writer.body(template.nodelist)128- writer.stream = original129-130- if callback is None:131- def callback(template):132- print(template)133-134- for directory in settings.TEMPLATE_DIRS:135- for dirname, _, files in os.walk(directory):136- dirname = dirname[len(directory) + 1:]137- for filename in filter_templates(files):138- source = os.path.normpath(os.path.join(dirname, filename))139- target = os.path.join(output_dir, dirname, filename)140- basetarget = os.path.dirname(target)141- if not os.path.exists(basetarget):142- os.makedirs(basetarget)143- callback(source)144- f = file(target, 'w')145- try:146- translate(f, source)147- finally:148- f.close()149-150-151-class Writer(object):152- """The core writer class."""153-154- def __init__(self, stream=None, error_stream=None,155- block_start_string=BLOCK_START_STRING,156- block_end_string=BLOCK_END_STRING,157- variable_start_string=VARIABLE_START_STRING,158- variable_end_string=VARIABLE_END_STRING,159- comment_start_string=COMMENT_START_STRING,160- comment_end_string=COMMENT_END_STRING,161- initial_autoescape=True,162- use_jinja_autoescape=False,163- custom_node_handlers=None,164- var_re=[],165- env=None):166- if stream is None:167- stream = sys.stdout168- if error_stream is None:169- error_stream = sys.stderr170- self.stream = stream171- self.error_stream = error_stream172- self.block_start_string = block_start_string173- self.block_end_string = block_end_string174- self.variable_start_string = variable_start_string175- self.variable_end_string = variable_end_string176- self.comment_start_string = comment_start_string177- self.comment_end_string = comment_end_string178- self.autoescape = initial_autoescape179- self.spaceless = False180- self.use_jinja_autoescape = use_jinja_autoescape181- self.node_handlers = dict(_node_handlers,182- **(custom_node_handlers or {}))183- self._loop_depth = 0184- self._filters_warned = set()185- self.var_re = var_re186- self.env = env187-188- def enter_loop(self):189- """Increments the loop depth so that write functions know if they190- are in a loop.191- """192- self._loop_depth += 1193-194- def leave_loop(self):195- """Reverse of enter_loop."""196- self._loop_depth -= 1197-198- @property199- def in_loop(self):200- """True if we are in a loop."""201- return self._loop_depth > 0202-203- def write(self, s):204- """Writes stuff to the stream."""205- self.stream.write(s.encode(settings.FILE_CHARSET))206-207- def print_expr(self, expr):208- """Open a variable tag, write to the string to the stream and close."""209- self.start_variable()210- self.write(expr)211- self.end_variable()212-213- def _post_open(self):214- if self.spaceless:215- self.write('- ')216- else:217- self.write(' ')218-219- def _pre_close(self):220- if self.spaceless:221- self.write(' -')222- else:223- self.write(' ')224-225- def start_variable(self):226- """Start a variable."""227- self.write(self.variable_start_string)228- self._post_open()229-230- def end_variable(self, always_safe=False):231- """End a variable."""232- if not always_safe and self.autoescape and \233- not self.use_jinja_autoescape:234- self.write('|e')235- self._pre_close()236- self.write(self.variable_end_string)237-238- def start_block(self):239- """Starts a block."""240- self.write(self.block_start_string)241- self._post_open()242-243- def end_block(self):244- """Ends a block."""245- self._pre_close()246- self.write(self.block_end_string)247-248- def tag(self, name):249- """Like `print_expr` just for blocks."""250- self.start_block()251- self.write(name)252- self.end_block()253-254- def variable(self, name):255- """Prints a variable. This performs variable name transformation."""256- self.write(self.translate_variable_name(name))257-258- def literal(self, value):259- """Writes a value as literal."""260- value = repr(value)261- if value[:2] in ('u"', "u'"):262- value = value[1:]263- self.write(value)264-265- def filters(self, filters, is_block=False):266- """Dumps a list of filters."""267- want_pipe = not is_block268- for filter, args in filters:269- name = self.get_filter_name(filter)270- if name is None:271- self.warn('Could not find filter %s' % name)272- continue273- if name not in DEFAULT_FILTERS and \274- name not in self._filters_warned:275- self._filters_warned.add(name)276- self.warn('Filter %s probably doesn\'t exist in Jinja' %277- name)278- if not want_pipe:279- want_pipe = True280- else:281- self.write('|')282- self.write(name)283- if args:284- self.write('(')285- for idx, (is_var, value) in enumerate(args):286- if idx:287- self.write(', ')288- if is_var:289- self.node(value)290- else:291- self.literal(value)292- self.write(')')293-294- def get_location(self, origin, position):295- """Returns the location for an origin and position tuple as name296- and lineno.297- """298- if hasattr(origin, 'source'):299- source = origin.source300- name = '<unknown source>'301- else:302- source = origin.loader(origin.loadname, origin.dirs)[0]303- name = origin.loadname304- lineno = len(_newline_re.findall(source[:position[0]])) + 1305- return name, lineno306-307- def warn(self, message, node=None):308- """Prints a warning to the error stream."""309- if node is not None and hasattr(node, 'source'):310- filename, lineno = self.get_location(*node.source)311- message = '[%s:%d] %s' % (filename, lineno, message)312- print(message, file=self.error_stream)313-314- def translate_variable_name(self, var):315- """Performs variable name translation."""316- if self.in_loop and var == 'forloop' or var.startswith('forloop.'):317- var = var[3:]318-319- for reg, rep, unless in self.var_re:320- no_unless = unless and unless.search(var) or True321- if reg.search(var) and no_unless:322- var = reg.sub(rep, var)323- break324- return var325-326- def get_filter_name(self, filter):327- """Returns the filter name for a filter function or `None` if there328- is no such filter.329- """330- if filter not in _resolved_filters:331- for library in libraries.values():332- for key, value in library.filters.iteritems():333- _resolved_filters[value] = key334- return _resolved_filters.get(filter, None)335-336- def node(self, node):337- """Invokes the node handler for a node."""338- for cls, handler in self.node_handlers.iteritems():339- if type(node) is cls or type(node).__name__ == cls:340- handler(self, node)341- break342- else:343- self.warn('Untranslatable node %s.%s found' % (344- node.__module__,345- node.__class__.__name__346- ), node)347-348- def body(self, nodes):349- """Calls node() for every node in the iterable passed."""350- for node in nodes:351- self.node(node)352-353-354-@node(TextNode)355-def text_node(writer, node):356- writer.write(node.s)357-358-359-@node(Variable)360-def variable(writer, node):361- if node.translate:362- writer.warn('i18n system used, make sure to install translations', node)363- writer.write('_(')364- if node.literal is not None:365- writer.literal(node.literal)366- else:367- writer.variable(node.var)368- if node.translate:369- writer.write(')')370-371-372-@node(VariableNode)373-def variable_node(writer, node):374- writer.start_variable()375- if node.filter_expression.var.var == 'block.super' \376- and not node.filter_expression.filters:377- writer.write('super()')378- else:379- writer.node(node.filter_expression)380- writer.end_variable()381-382-383-@node(FilterExpression)384-def filter_expression(writer, node):385- writer.node(node.var)386- writer.filters(node.filters)387-388-389-@node(core_tags.CommentNode)390-def comment_tag(writer, node):391- pass392-393-394-@node(core_tags.DebugNode)395-def comment_tag(writer, node):396- writer.warn('Debug tag detected. Make sure to add a global function '397- 'called debug to the namespace.', node=node)398- writer.print_expr('debug()')399-400-401-@node(core_tags.ForNode)402-def for_loop(writer, node):403- writer.start_block()404- writer.write('for ')405- for idx, var in enumerate(node.loopvars):406- if idx:407- writer.write(', ')408- writer.variable(var)409- writer.write(' in ')410- if node.is_reversed:411- writer.write('(')412- writer.node(node.sequence)413- if node.is_reversed:414- writer.write(')|reverse')415- writer.end_block()416- writer.enter_loop()417- writer.body(node.nodelist_loop)418- writer.leave_loop()419- writer.tag('endfor')420-421-422-@node(core_tags.IfNode)423-def if_condition(writer, node):424- writer.start_block()425- writer.write('if ')426- join_with = 'and'427- if node.link_type == core_tags.IfNode.LinkTypes.or_:428- join_with = 'or'429-430- for idx, (ifnot, expr) in enumerate(node.bool_exprs):431- if idx:432- writer.write(' %s ' % join_with)433- if ifnot:434- writer.write('not ')435- writer.node(expr)436- writer.end_block()437- writer.body(node.nodelist_true)438- if node.nodelist_false:439- writer.tag('else')440- writer.body(node.nodelist_false)441- writer.tag('endif')442-443-444-@node(core_tags.IfEqualNode)445-def if_equal(writer, node):446- writer.start_block()447- writer.write('if ')448- writer.node(node.var1)449- if node.negate:450- writer.write(' != ')451- else:452- writer.write(' == ')453- writer.node(node.var2)454- writer.end_block()455- writer.body(node.nodelist_true)456- if node.nodelist_false:457- writer.tag('else')458- writer.body(node.nodelist_false)459- writer.tag('endif')460-461-462-@node(loader_tags.BlockNode)463-def block(writer, node):464- writer.tag('block ' + node.name.replace('-', '_').rstrip('_'))465- node = node466- while node.parent is not None:467- node = node.parent468- writer.body(node.nodelist)469- writer.tag('endblock')470-471-472-@node(loader_tags.ExtendsNode)473-def extends(writer, node):474- writer.start_block()475- writer.write('extends ')476- if node.parent_name_expr:477- writer.node(node.parent_name_expr)478- else:479- writer.literal(node.parent_name)480- writer.end_block()481- writer.body(node.nodelist)482-483-484-@node(loader_tags.ConstantIncludeNode)485-@node(loader_tags.IncludeNode)486-def include(writer, node):487- writer.start_block()488- writer.write('include ')489- if hasattr(node, 'template'):490- writer.literal(node.template.name)491- else:492- writer.node(node.template_name)493- writer.end_block()494-495-496-@node(core_tags.CycleNode)497-def cycle(writer, node):498- if not writer.in_loop:499- writer.warn('Untranslatable free cycle (cycle outside loop)', node=node)500- return501- if node.variable_name is not None:502- writer.start_block()503- writer.write('set %s = ' % node.variable_name)504- else:505- writer.start_variable()506- writer.write('loop.cycle(')507- for idx, var in enumerate(node.raw_cycle_vars):508- if idx:509- writer.write(', ')510- writer.node(var)511- writer.write(')')512- if node.variable_name is not None:513- writer.end_block()514- else:515- writer.end_variable()516-517-518-@node(core_tags.FilterNode)519-def filter(writer, node):520- writer.start_block()521- writer.write('filter ')522- writer.filters(node.filter_expr.filters, True)523- writer.end_block()524- writer.body(node.nodelist)525- writer.tag('endfilter')526-527-528-@node(core_tags.AutoEscapeControlNode)529-def autoescape_control(writer, node):530- original = writer.autoescape531- writer.autoescape = node.setting532- writer.body(node.nodelist)533- writer.autoescape = original534-535-536-@node(core_tags.SpacelessNode)537-def spaceless(writer, node):538- original = writer.spaceless539- writer.spaceless = True540- writer.warn('entering spaceless mode with different semantics', node)541- # do the initial stripping542- nodelist = list(node.nodelist)543- if nodelist:544- if isinstance(nodelist[0], TextNode):545- nodelist[0] = TextNode(nodelist[0].s.lstrip())546- if isinstance(nodelist[-1], TextNode):547- nodelist[-1] = TextNode(nodelist[-1].s.rstrip())548- writer.body(nodelist)549- writer.spaceless = original550-551-552-@node(core_tags.TemplateTagNode)553-def template_tag(writer, node):554- tag = {555- 'openblock': writer.block_start_string,556- 'closeblock': writer.block_end_string,557- 'openvariable': writer.variable_start_string,558- 'closevariable': writer.variable_end_string,559- 'opencomment': writer.comment_start_string,560- 'closecomment': writer.comment_end_string,561- 'openbrace': '{',562- 'closebrace': '}'563- }.get(node.tagtype)564- if tag:565- writer.start_variable()566- writer.literal(tag)567- writer.end_variable()568-569-570-@node(core_tags.URLNode)571-def url_tag(writer, node):572- writer.warn('url node used. make sure to provide a proper url() '573- 'function', node)574- if node.asvar:575- writer.start_block()576- writer.write('set %s = ' % node.asvar)577- else:578- writer.start_variable()579- autoescape = writer.autoescape580- writer.write('url(')581- writer.literal(node.view_name)582- for arg in node.args:583- writer.write(', ')584- writer.node(arg)585- for key, arg in node.kwargs.items():586- writer.write(', %s=' % key)587- writer.node(arg)588- writer.write(')')589- if node.asvar:590- writer.end_block()591- else:592- writer.end_variable()593-594-595-@node(core_tags.WidthRatioNode)596-def width_ratio(writer, node):597- writer.warn('widthratio expanded into formula. You may want to provide '598- 'a helper function for this calculation', node)599- writer.start_variable()600- writer.write('(')601- writer.node(node.val_expr)602- writer.write(' / ')603- writer.node(node.max_expr)604- writer.write(' * ')605- writer.write(str(int(node.max_width)))606- writer.write(')|round|int')607- writer.end_variable(always_safe=True)608-609-610-@node(core_tags.WithNode)611-def with_block(writer, node):612- writer.warn('with block expanded into set statement. This could cause '613- 'variables following that block to be overridden.', node)614- writer.start_block()615- writer.write('set %s = ' % node.name)616- writer.node(node.var)617- writer.end_block()618- writer.body(node.nodelist)619-620-621-@node(core_tags.RegroupNode)622-def regroup(writer, node):623- if node.expression.var.literal:624- writer.warn('literal in groupby filter used. Behavior in that '625- 'situation is undefined and translation is skipped.', node)626- return627- elif node.expression.filters:628- writer.warn('filters in groupby filter used. Behavior in that '629- 'situation is undefined which is most likely a bug '630- 'in your code. Filters were ignored.', node)631- writer.start_block()632- writer.write('set %s = ' % node.var_name)633- writer.node(node.target)634- writer.write('|groupby(')635- writer.literal(node.expression.var.var)636- writer.write(')')637- writer.end_block()638-639-640-@node(core_tags.LoadNode)641-def warn_load(writer, node):642- writer.warn('load statement used which was ignored on conversion', node)643-644-645-@node(i18n_tags.GetAvailableLanguagesNode)646-def get_available_languages(writer, node):647- writer.warn('make sure to provide a get_available_languages function', node)648- writer.tag('set %s = get_available_languages()' %649- writer.translate_variable_name(node.variable))650-651-652-@node(i18n_tags.GetCurrentLanguageNode)653-def get_current_language(writer, node):654- writer.warn('make sure to provide a get_current_language function', node)655- writer.tag('set %s = get_current_language()' %656- writer.translate_variable_name(node.variable))657-658-659-@node(i18n_tags.GetCurrentLanguageBidiNode)660-def get_current_language_bidi(writer, node):661- writer.warn('make sure to provide a get_current_language_bidi function', node)662- writer.tag('set %s = get_current_language_bidi()' %663- writer.translate_variable_name(node.variable))664-665-666-@node(i18n_tags.TranslateNode)667-def simple_gettext(writer, node):668- writer.warn('i18n system used, make sure to install translations', node)669- writer.start_variable()670- writer.write('_(')671- writer.node(node.value)672- writer.write(')')673- writer.end_variable()674-675-676-@node(i18n_tags.BlockTranslateNode)677-def translate_block(writer, node):678- first_var = []679- variables = set()680-681- def touch_var(name):682- variables.add(name)683- if not first_var:684- first_var.append(name)685-686- def dump_token_list(tokens):687- for token in tokens:688- if token.token_type == TOKEN_TEXT:689- writer.write(token.contents)690- elif token.token_type == TOKEN_VAR:691- writer.print_expr(token.contents)692- touch_var(token.contents)693-694- writer.warn('i18n system used, make sure to install translations', node)695- writer.start_block()696- writer.write('trans')697- idx = -1698- for idx, (key, var) in enumerate(node.extra_context.items()):699- if idx:700- writer.write(',')701- writer.write(' %s=' % key)702- touch_var(key)703- writer.node(var.filter_expression)704-705- have_plural = False706- plural_var = None707- if node.plural and node.countervar and node.counter:708- have_plural = True709- plural_var = node.countervar710- if plural_var not in variables:711- if idx > -1:712- writer.write(',')713- touch_var(plural_var)714- writer.write(' %s=' % plural_var)715- writer.node(node.counter)716-717- writer.end_block()718- dump_token_list(node.singular)719- if node.plural and node.countervar and node.counter:720- writer.start_block()721- writer.write('pluralize')722- if node.countervar != first_var[0]:723- writer.write(' ' + node.countervar)724- writer.end_block()725- dump_token_list(node.plural)726- writer.tag('endtrans')727-728-@node("SimpleNode")729-def simple_tag(writer, node):730- """Check if the simple tag exist as a filter in """731- name = node.tag_name732- if writer.env and \733- name not in writer.env.filters and \734- name not in writer._filters_warned:735- writer._filters_warned.add(name)736- writer.warn('Filter %s probably doesn\'t exist in Jinja' %737- name)738-739- if not node.vars_to_resolve:740- # No argument, pass the request741- writer.start_variable()742- writer.write('request|')743- writer.write(name)744- writer.end_variable()745- return746-747- first_var = node.vars_to_resolve[0]748- args = node.vars_to_resolve[1:]749- writer.start_variable()750-751- # Copied from Writer.filters()752- writer.node(first_var)753-754- writer.write('|')755- writer.write(name)756- if args:757- writer.write('(')758- for idx, var in enumerate(args):759- if idx:760- writer.write(', ')761- if var.var:762- writer.node(var)763- else:764- writer.literal(var.literal)765- writer.write(')')766- writer.end_variable()767-768-# get rid of node now, it shouldn't be used normally769-del nodedeleted:ext/django2jinja/example.py-7 removed
1-from django.conf import settings2-settings.configure(TEMPLATE_DIRS=['templates'], TEMPLATE_DEBUG=True)3-4-from django2jinja import convert_templates, Writer5-6-writer = Writer(use_jinja_autoescape=True)7-convert_templates('converted', writer=writer)deleted:ext/djangojinja2.py-86 removed
1-# -*- coding: utf-8 -*-2-"""3- djangojinja24- ~~~~~~~~~~~~5-6- Adds support for Jinja to Django.7-8- Configuration variables:9-10- ======================= =============================================11- Key Description12- ======================= =============================================13- `JINJA2_TEMPLATE_DIRS` List of template folders14- `JINJA2_EXTENSIONS` List of Jinja extensions to use15- `JINJA2_CACHE_SIZE` The size of the Jinja template cache.16- ======================= =============================================17-18- :copyright: (c) 2009 by the Jinja Team.19- :license: BSD.20-"""21-from itertools import chain22-from django.conf import settings23-from django.http import HttpResponse24-from django.core.exceptions import ImproperlyConfigured25-from django.template.context import get_standard_processors26-from django.template import TemplateDoesNotExist27-from jinja2 import Environment, FileSystemLoader, TemplateNotFound28-from jinja2.defaults import DEFAULT_NAMESPACE29-30-31-# the environment is unconfigured until the first template is loaded.32-_jinja_env = None33-34-35-def get_env():36- """Get the Jinja env and initialize it if necessary."""37- global _jinja_env38- if _jinja_env is None:39- _jinja_env = create_env()40- return _jinja_env41-42-43-def create_env():44- """Create a new Jinja environment."""45- searchpath = list(settings.JINJA2_TEMPLATE_DIRS)46- return Environment(loader=FileSystemLoader(searchpath),47- auto_reload=settings.TEMPLATE_DEBUG,48- cache_size=getattr(settings, 'JINJA2_CACHE_SIZE', 400),49- extensions=getattr(settings, 'JINJA2_EXTENSIONS', ()))50-51-52-def get_template(template_name, globals=None):53- """Load a template."""54- try:55- return get_env().get_template(template_name, globals=globals)56- except TemplateNotFound as e:57- raise TemplateDoesNotExist(str(e))58-59-60-def select_template(templates, globals=None):61- """Try to load one of the given templates."""62- env = get_env()63- for template in templates:64- try:65- return env.get_template(template, globals=globals)66- except TemplateNotFound:67- continue68- raise TemplateDoesNotExist(', '.join(templates))69-70-71-def render_to_string(template_name, context=None, request=None,72- processors=None):73- """Render a template into a string."""74- context = dict(context or {})75- if request is not None:76- context['request'] = request77- for processor in chain(get_standard_processors(), processors or ()):78- context.update(processor(request))79- return get_template(template_name).render(context)80-81-82-def render_to_response(template_name, context=None, request=None,83- processors=None, mimetype=None):84- """Render a template into a response object."""85- return HttpResponse(render_to_string(template_name, context, request,86- processors), mimetype=mimetype)deleted:ext/inlinegettext.py-78 removed
1-# -*- coding: utf-8 -*-2-"""3- Inline Gettext4- ~~~~~~~~~~~~~~5-6- An example extension for Jinja that supports inline gettext calls.7- Requires the i18n extension to be loaded.8-9- :copyright: (c) 2009 by the Jinja Team.10- :license: BSD.11-"""12-import re13-from jinja2.ext import Extension14-from jinja2.lexer import Token, count_newlines15-from jinja2.exceptions import TemplateSyntaxError16-17-18-_outside_re = re.compile(r'\\?(gettext|_)\(')19-_inside_re = re.compile(r'\\?[()]')20-21-22-class InlineGettext(Extension):23- """This extension implements support for inline gettext blocks::24-25- <h1>_(Welcome)</h1>26- <p>_(This is a paragraph)</p>27-28- Requires the i18n extension to be loaded and configured.29- """30-31- def filter_stream(self, stream):32- paren_stack = 033-34- for token in stream:35- if token.type != 'data':36- yield token37- continue38-39- pos = 040- lineno = token.lineno41-42- while 1:43- if not paren_stack:44- match = _outside_re.search(token.value, pos)45- else:46- match = _inside_re.search(token.value, pos)47- if match is None:48- break49- new_pos = match.start()50- if new_pos > pos:51- preval = token.value[pos:new_pos]52- yield Token(lineno, 'data', preval)53- lineno += count_newlines(preval)54- gtok = match.group()55- if gtok[0] == '\\':56- yield Token(lineno, 'data', gtok[1:])57- elif not paren_stack:58- yield Token(lineno, 'block_begin', None)59- yield Token(lineno, 'name', 'trans')60- yield Token(lineno, 'block_end', None)61- paren_stack = 162- else:63- if gtok == '(' or paren_stack > 1:64- yield Token(lineno, 'data', gtok)65- paren_stack += gtok == ')' and -1 or 166- if not paren_stack:67- yield Token(lineno, 'block_begin', None)68- yield Token(lineno, 'name', 'endtrans')69- yield Token(lineno, 'block_end', None)70- pos = match.end()71-72- if pos < len(token.value):73- yield Token(lineno, 'data', token.value[pos:])74-75- if paren_stack:76- raise TemplateSyntaxError('unclosed gettext expression',77- token.lineno, stream.name,78- stream.filename)deleted:jinja2/__init__.py-72 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja24- ~~~~~~5-6- Jinja is a template engine written in pure Python. It provides a7- Django inspired non-XML syntax but supports inline expressions and8- an optional sandboxed environment.9-10- Nutshell11- --------12-13- Here a small example of a Jinja template::14-15- {% extends 'base.html' %}16- {% block title %}Memberlist{% endblock %}17- {% block content %}18- <ul>19- {% for user in users %}20- <li><a href="{{ user.url }}">{{ user.username }}</a></li>21- {% endfor %}22- </ul>23- {% endblock %}24-25-26- :copyright: (c) 2017 by the Jinja Team.27- :license: BSD, see LICENSE for more details.28-"""29-__docformat__ = 'restructuredtext en'30-__version__ = "2.11.0.dev0"31-32-# high level interface33-from jinja2.environment import Environment, Template34-35-# loaders36-from jinja2.loaders import BaseLoader, FileSystemLoader, PackageLoader, \37- DictLoader, FunctionLoader, PrefixLoader, ChoiceLoader, \38- ModuleLoader39-40-# bytecode caches41-from jinja2.bccache import BytecodeCache, FileSystemBytecodeCache, \42- MemcachedBytecodeCache43-44-# undefined types45-from jinja2.runtime import Undefined, ChainableUndefined, DebugUndefined, \46- StrictUndefined, make_logging_undefined47-48-# exceptions49-from jinja2.exceptions import TemplateError, UndefinedError, \50- TemplateNotFound, TemplatesNotFound, TemplateSyntaxError, \51- TemplateAssertionError, TemplateRuntimeError52-53-# decorators and public utilities54-from jinja2.filters import environmentfilter, contextfilter, \55- evalcontextfilter56-from jinja2.utils import Markup, escape, clear_caches, \57- environmentfunction, evalcontextfunction, contextfunction, \58- is_undefined, select_autoescape59-60-__all__ = [61- 'Environment', 'Template', 'BaseLoader', 'FileSystemLoader',62- 'PackageLoader', 'DictLoader', 'FunctionLoader', 'PrefixLoader',63- 'ChoiceLoader', 'BytecodeCache', 'FileSystemBytecodeCache',64- 'MemcachedBytecodeCache', 'Undefined', 'DebugUndefined',65- 'StrictUndefined', 'TemplateError', 'UndefinedError', 'TemplateNotFound',66- 'TemplatesNotFound', 'TemplateSyntaxError', 'TemplateAssertionError',67- 'TemplateRuntimeError',68- 'ModuleLoader', 'environmentfilter', 'contextfilter', 'Markup', 'escape',69- 'environmentfunction', 'contextfunction', 'clear_caches', 'is_undefined',70- 'evalcontextfilter', 'evalcontextfunction', 'make_logging_undefined',71- 'select_autoescape',72-]deleted:jinja2/_compat.py-124 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2._compat4- ~~~~~~~~~~~~~~5-6- Some py2/py3 compatibility support based on a stripped down7- version of six so we don't have to depend on a specific version8- of it.9-10- :copyright: Copyright 2013 by the Jinja team, see AUTHORS.11- :license: BSD, see LICENSE for details.12-"""13-import sys14-15-PY2 = sys.version_info[0] == 216-PYPY = hasattr(sys, 'pypy_translation_info')17-_identity = lambda x: x18-19-20-if not PY2:21- unichr = chr22- range_type = range23- text_type = str24- string_types = (str,)25- integer_types = (int,)26-27- iterkeys = lambda d: iter(d.keys())28- itervalues = lambda d: iter(d.values())29- iteritems = lambda d: iter(d.items())30-31- import pickle32- from io import BytesIO, StringIO33- NativeStringIO = StringIO34-35- def reraise(tp, value, tb=None):36- if value.__traceback__ is not tb:37- raise value.with_traceback(tb)38- raise value39-40- ifilter = filter41- imap = map42- izip = zip43- intern = sys.intern44-45- implements_iterator = _identity46- implements_to_string = _identity47- encode_filename = _identity48-49-else:50- unichr = unichr51- text_type = unicode52- range_type = xrange53- string_types = (str, unicode)54- integer_types = (int, long)55-56- iterkeys = lambda d: d.iterkeys()57- itervalues = lambda d: d.itervalues()58- iteritems = lambda d: d.iteritems()59-60- import cPickle as pickle61- from cStringIO import StringIO as BytesIO, StringIO62- NativeStringIO = BytesIO63-64- exec('def reraise(tp, value, tb=None):\n raise tp, value, tb')65-66- from itertools import imap, izip, ifilter67- intern = intern68-69- def implements_iterator(cls):70- cls.next = cls.__next__71- del cls.__next__72- return cls73-74- def implements_to_string(cls):75- cls.__unicode__ = cls.__str__76- cls.__str__ = lambda x: x.__unicode__().encode('utf-8')77- return cls78-79- def encode_filename(filename):80- if isinstance(filename, unicode):81- return filename.encode('utf-8')82- return filename83-84-85-def with_metaclass(meta, *bases):86- """Create a base class with a metaclass."""87- # This requires a bit of explanation: the basic idea is to make a88- # dummy metaclass for one level of class instantiation that replaces89- # itself with the actual metaclass.90- class metaclass(type):91- def __new__(cls, name, this_bases, d):92- return meta(name, bases, d)93- return type.__new__(metaclass, 'temporary_class', (), {})94-95-96-try:97- from urllib.parse import quote_from_bytes as url_quote98-except ImportError:99- from urllib import quote as url_quote100-101-102-try:103- from collections import abc104-except ImportError:105- import collections as abc106-107-108-try:109- from os import fspath110-except ImportError:111- try:112- from pathlib import PurePath113- except ImportError:114- PurePath = None115-116- def fspath(path):117- if hasattr(path, "__fspath__"):118- return path.__fspath__()119-120- # Python 3.5 doesn't have __fspath__ yet, use str.121- if PurePath is not None and isinstance(path, PurePath):122- return str(path)123-124- return pathdeleted:jinja2/_identifier.py-2 removed
1-# generated by scripts/generate_identifier_pattern.py2-pattern = '·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఃా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑅳𑄴𑆀-𑆂𑆳-𑇊𑇀-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯'deleted:jinja2/asyncfilters.py-146 removed
1-from functools import wraps2-3-from jinja2.asyncsupport import auto_aiter, auto_await4-from jinja2 import filters5-6-7-async def auto_to_seq(value):8- seq = []9- if hasattr(value, '__aiter__'):10- async for item in value:11- seq.append(item)12- else:13- for item in value:14- seq.append(item)15- return seq16-17-18-async def async_select_or_reject(args, kwargs, modfunc, lookup_attr):19- seq, func = filters.prepare_select_or_reject(20- args, kwargs, modfunc, lookup_attr)21- if seq:22- async for item in auto_aiter(seq):23- if func(item):24- yield item25-26-27-def dualfilter(normal_filter, async_filter):28- wrap_evalctx = False29- if getattr(normal_filter, 'environmentfilter', False):30- is_async = lambda args: args[0].is_async31- wrap_evalctx = False32- else:33- if not getattr(normal_filter, 'evalcontextfilter', False) and \34- not getattr(normal_filter, 'contextfilter', False):35- wrap_evalctx = True36- is_async = lambda args: args[0].environment.is_async37-38- @wraps(normal_filter)39- def wrapper(*args, **kwargs):40- b = is_async(args)41- if wrap_evalctx:42- args = args[1:]43- if b:44- return async_filter(*args, **kwargs)45- return normal_filter(*args, **kwargs)46-47- if wrap_evalctx:48- wrapper.evalcontextfilter = True49-50- wrapper.asyncfiltervariant = True51-52- return wrapper53-54-55-def asyncfiltervariant(original):56- def decorator(f):57- return dualfilter(original, f)58- return decorator59-60-61-@asyncfiltervariant(filters.do_first)62-async def do_first(environment, seq):63- try:64- return await auto_aiter(seq).__anext__()65- except StopAsyncIteration:66- return environment.undefined('No first item, sequence was empty.')67-68-69-@asyncfiltervariant(filters.do_groupby)70-async def do_groupby(environment, value, attribute):71- expr = filters.make_attrgetter(environment, attribute)72- return [filters._GroupTuple(key, await auto_to_seq(values))73- for key, values in filters.groupby(sorted(74- await auto_to_seq(value), key=expr), expr)]75-76-77-@asyncfiltervariant(filters.do_join)78-async def do_join(eval_ctx, value, d=u'', attribute=None):79- return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)80-81-82-@asyncfiltervariant(filters.do_list)83-async def do_list(value):84- return await auto_to_seq(value)85-86-87-@asyncfiltervariant(filters.do_reject)88-async def do_reject(*args, **kwargs):89- return async_select_or_reject(args, kwargs, lambda x: not x, False)90-91-92-@asyncfiltervariant(filters.do_rejectattr)93-async def do_rejectattr(*args, **kwargs):94- return async_select_or_reject(args, kwargs, lambda x: not x, True)95-96-97-@asyncfiltervariant(filters.do_select)98-async def do_select(*args, **kwargs):99- return async_select_or_reject(args, kwargs, lambda x: x, False)100-101-102-@asyncfiltervariant(filters.do_selectattr)103-async def do_selectattr(*args, **kwargs):104- return async_select_or_reject(args, kwargs, lambda x: x, True)105-106-107-@asyncfiltervariant(filters.do_map)108-async def do_map(*args, **kwargs):109- seq, func = filters.prepare_map(args, kwargs)110- if seq:111- async for item in auto_aiter(seq):112- yield await auto_await(func(item))113-114-115-@asyncfiltervariant(filters.do_sum)116-async def do_sum(environment, iterable, attribute=None, start=0):117- rv = start118- if attribute is not None:119- func = filters.make_attrgetter(environment, attribute)120- else:121- func = lambda x: x122- async for item in auto_aiter(iterable):123- rv += func(item)124- return rv125-126-127-@asyncfiltervariant(filters.do_slice)128-async def do_slice(value, slices, fill_with=None):129- return filters.do_slice(await auto_to_seq(value), slices, fill_with)130-131-132-ASYNC_FILTERS = {133- 'first': do_first,134- 'groupby': do_groupby,135- 'join': do_join,136- 'list': do_list,137- # we intentionally do not support do_last because that would be138- # ridiculous139- 'reject': do_reject,140- 'rejectattr': do_rejectattr,141- 'map': do_map,142- 'select': do_select,143- 'selectattr': do_selectattr,144- 'sum': do_sum,145- 'slice': do_slice,146-}deleted:jinja2/asyncsupport.py-264 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.asyncsupport4- ~~~~~~~~~~~~~~~~~~~5-6- Has all the code for async support which is implemented as a patch7- for supported Python versions.8-9- :copyright: (c) 2017 by the Jinja Team.10- :license: BSD, see LICENSE for more details.11-"""12-import asyncio13-import inspect14-from functools import update_wrapper15-16-from jinja2.environment import TemplateModule17-from jinja2.runtime import LoopContext18-from jinja2.utils import concat19-from jinja2.utils import internalcode20-from jinja2.utils import Markup21-from jinja2.utils import missing22-23-24-async def concat_async(async_gen):25- rv = []26- async def collect():27- async for event in async_gen:28- rv.append(event)29- await collect()30- return concat(rv)31-32-33-async def generate_async(self, *args, **kwargs):34- vars = dict(*args, **kwargs)35- try:36- async for event in self.root_render_func(self.new_context(vars)):37- yield event38- except Exception:39- yield self.environment.handle_exception()40-41-42-def wrap_generate_func(original_generate):43- def _convert_generator(self, loop, args, kwargs):44- async_gen = self.generate_async(*args, **kwargs)45- try:46- while 1:47- yield loop.run_until_complete(async_gen.__anext__())48- except StopAsyncIteration:49- pass50- def generate(self, *args, **kwargs):51- if not self.environment.is_async:52- return original_generate(self, *args, **kwargs)53- return _convert_generator(self, asyncio.get_event_loop(), args, kwargs)54- return update_wrapper(generate, original_generate)55-56-57-async def render_async(self, *args, **kwargs):58- if not self.environment.is_async:59- raise RuntimeError('The environment was not created with async mode '60- 'enabled.')61-62- vars = dict(*args, **kwargs)63- ctx = self.new_context(vars)64-65- try:66- return await concat_async(self.root_render_func(ctx))67- except Exception:68- return self.environment.handle_exception()69-70-71-def wrap_render_func(original_render):72- def render(self, *args, **kwargs):73- if not self.environment.is_async:74- return original_render(self, *args, **kwargs)75- loop = asyncio.get_event_loop()76- return loop.run_until_complete(self.render_async(*args, **kwargs))77- return update_wrapper(render, original_render)78-79-80-def wrap_block_reference_call(original_call):81- @internalcode82- async def async_call(self):83- rv = await concat_async(self._stack[self._depth](self._context))84- if self._context.eval_ctx.autoescape:85- rv = Markup(rv)86- return rv87-88- @internalcode89- def __call__(self):90- if not self._context.environment.is_async:91- return original_call(self)92- return async_call(self)93-94- return update_wrapper(__call__, original_call)95-96-97-def wrap_macro_invoke(original_invoke):98- @internalcode99- async def async_invoke(self, arguments, autoescape):100- rv = await self._func(*arguments)101- if autoescape:102- rv = Markup(rv)103- return rv104-105- @internalcode106- def _invoke(self, arguments, autoescape):107- if not self._environment.is_async:108- return original_invoke(self, arguments, autoescape)109- return async_invoke(self, arguments, autoescape)110- return update_wrapper(_invoke, original_invoke)111-112-113-@internalcode114-async def get_default_module_async(self):115- if self._module is not None:116- return self._module117- self._module = rv = await self.make_module_async()118- return rv119-120-121-def wrap_default_module(original_default_module):122- @internalcode123- def _get_default_module(self):124- if self.environment.is_async:125- raise RuntimeError('Template module attribute is unavailable '126- 'in async mode')127- return original_default_module(self)128- return _get_default_module129-130-131-async def make_module_async(self, vars=None, shared=False, locals=None):132- context = self.new_context(vars, shared, locals)133- body_stream = []134- async for item in self.root_render_func(context):135- body_stream.append(item)136- return TemplateModule(self, context, body_stream)137-138-139-def patch_template():140- from jinja2 import Template141- Template.generate = wrap_generate_func(Template.generate)142- Template.generate_async = update_wrapper(143- generate_async, Template.generate_async)144- Template.render_async = update_wrapper(145- render_async, Template.render_async)146- Template.render = wrap_render_func(Template.render)147- Template._get_default_module = wrap_default_module(148- Template._get_default_module)149- Template._get_default_module_async = get_default_module_async150- Template.make_module_async = update_wrapper(151- make_module_async, Template.make_module_async)152-153-154-def patch_runtime():155- from jinja2.runtime import BlockReference, Macro156- BlockReference.__call__ = wrap_block_reference_call(157- BlockReference.__call__)158- Macro._invoke = wrap_macro_invoke(Macro._invoke)159-160-161-def patch_filters():162- from jinja2.filters import FILTERS163- from jinja2.asyncfilters import ASYNC_FILTERS164- FILTERS.update(ASYNC_FILTERS)165-166-167-def patch_all():168- patch_template()169- patch_runtime()170- patch_filters()171-172-173-async def auto_await(value):174- if inspect.isawaitable(value):175- return await value176- return value177-178-179-async def auto_aiter(iterable):180- if hasattr(iterable, '__aiter__'):181- async for item in iterable:182- yield item183- return184- for item in iterable:185- yield item186-187-188-class AsyncLoopContext(LoopContext):189- _to_iterator = staticmethod(auto_aiter)190-191- @property192- async def length(self):193- if self._length is not None:194- return self._length195-196- try:197- self._length = len(self._iterable)198- except TypeError:199- iterable = [x async for x in self._iterator]200- self._iterator = self._to_iterator(iterable)201- self._length = len(iterable) + self.index + (self._after is not missing)202-203- return self._length204-205- @property206- async def revindex0(self):207- return await self.length - self.index208-209- @property210- async def revindex(self):211- return await self.length - self.index0212-213- async def _peek_next(self):214- if self._after is not missing:215- return self._after216-217- try:218- self._after = await self._iterator.__anext__()219- except StopAsyncIteration:220- self._after = missing221-222- return self._after223-224- @property225- async def last(self):226- return await self._peek_next() is missing227-228- @property229- async def nextitem(self):230- rv = await self._peek_next()231-232- if rv is missing:233- return self._undefined("there is no next item")234-235- return rv236-237- def __aiter__(self):238- return self239-240- async def __anext__(self):241- if self._after is not missing:242- rv = self._after243- self._after = missing244- else:245- rv = await self._iterator.__anext__()246-247- self.index0 += 1248- self._before = self._current249- self._current = rv250- return rv, self251-252-253-async def make_async_loop_context(iterable, undefined, recurse=None, depth0=0):254- import warnings255- 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)262-263-264-patch_all()deleted:jinja2/bccache.py-361 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.bccache4- ~~~~~~~~~~~~~~5-6- This module implements the bytecode cache system that Jinja optionally uses.7- This is useful if you have very complex template situations and8- the compilation of all those templates slows down your application too9- much.10-11- Situations where this is useful are often forking web applications that12- are initialized on the first request.13-14- :copyright: (c) 2017 by the Jinja Team.15- :license: BSD.16-"""17-from os import path, listdir18-import os19-import sys20-import stat21-import errno22-import marshal23-import tempfile24-import fnmatch25-from hashlib import sha126-from jinja2.utils import open_if_exists27-from jinja2._compat import BytesIO, pickle, PY2, text_type28-29-30-# marshal works better on 3.x, one hack less required31-if not PY2:32- marshal_dump = marshal.dump33- marshal_load = marshal.load34-else:35-36- def marshal_dump(code, f):37- if isinstance(f, file):38- marshal.dump(code, f)39- else:40- f.write(marshal.dumps(code))41-42- def marshal_load(f):43- if isinstance(f, file):44- return marshal.load(f)45- return marshal.loads(f.read())46-47-48-bc_version = 349-50-# magic version used to only change with new jinja versions. With 2.651-# we change this to also take Python version changes into account. The52-# reason for this is that Python tends to segfault if fed earlier bytecode53-# versions because someone thought it would be a good idea to reuse opcodes54-# or make Python incompatible with earlier versions.55-bc_magic = 'j2'.encode('ascii') + \56- pickle.dumps(bc_version, 2) + \57- pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1])58-59-60-class Bucket(object):61- """Buckets are used to store the bytecode for one template. It's created62- and initialized by the bytecode cache and passed to the loading functions.63-64- The buckets get an internal checksum from the cache assigned and use this65- to automatically reject outdated cache material. Individual bytecode66- cache subclasses don't have to care about cache invalidation.67- """68-69- def __init__(self, environment, key, checksum):70- self.environment = environment71- self.key = key72- self.checksum = checksum73- self.reset()74-75- def reset(self):76- """Resets the bucket (unloads the bytecode)."""77- self.code = None78-79- def load_bytecode(self, f):80- """Loads bytecode from a file or file like object."""81- # make sure the magic header is correct82- magic = f.read(len(bc_magic))83- if magic != bc_magic:84- self.reset()85- return86- # the source code of the file changed, we need to reload87- checksum = pickle.load(f)88- if self.checksum != checksum:89- self.reset()90- return91- # if marshal_load fails then we need to reload92- try:93- self.code = marshal_load(f)94- except (EOFError, ValueError, TypeError):95- self.reset()96- return97-98- def write_bytecode(self, f):99- """Dump the bytecode into the file or file like object passed."""100- if self.code is None:101- raise TypeError('can\'t write empty bucket')102- f.write(bc_magic)103- pickle.dump(self.checksum, f, 2)104- marshal_dump(self.code, f)105-106- def bytecode_from_string(self, string):107- """Load bytecode from a string."""108- self.load_bytecode(BytesIO(string))109-110- def bytecode_to_string(self):111- """Return the bytecode as string."""112- out = BytesIO()113- self.write_bytecode(out)114- return out.getvalue()115-116-117-class BytecodeCache(object):118- """To implement your own bytecode cache you have to subclass this class119- and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of120- these methods are passed a :class:`~jinja2.bccache.Bucket`.121-122- A very basic bytecode cache that saves the bytecode on the file system::123-124- from os import path125-126- class MyCache(BytecodeCache):127-128- def __init__(self, directory):129- self.directory = directory130-131- def load_bytecode(self, bucket):132- filename = path.join(self.directory, bucket.key)133- if path.exists(filename):134- with open(filename, 'rb') as f:135- bucket.load_bytecode(f)136-137- def dump_bytecode(self, bucket):138- filename = path.join(self.directory, bucket.key)139- with open(filename, 'wb') as f:140- bucket.write_bytecode(f)141-142- A more advanced version of a filesystem based bytecode cache is part of143- Jinja.144- """145-146- def load_bytecode(self, bucket):147- """Subclasses have to override this method to load bytecode into a148- bucket. If they are not able to find code in the cache for the149- bucket, it must not do anything.150- """151- raise NotImplementedError()152-153- def dump_bytecode(self, bucket):154- """Subclasses have to override this method to write the bytecode155- from a bucket back to the cache. If it unable to do so it must not156- fail silently but raise an exception.157- """158- raise NotImplementedError()159-160- def clear(self):161- """Clears the cache. This method is not used by Jinja but should be162- implemented to allow applications to clear the bytecode cache used163- by a particular environment.164- """165-166- def get_cache_key(self, name, filename=None):167- """Returns the unique hash key for this template name."""168- hash = sha1(name.encode('utf-8'))169- if filename is not None:170- filename = '|' + filename171- if isinstance(filename, text_type):172- filename = filename.encode('utf-8')173- hash.update(filename)174- return hash.hexdigest()175-176- def get_source_checksum(self, source):177- """Returns a checksum for the source."""178- return sha1(source.encode('utf-8')).hexdigest()179-180- def get_bucket(self, environment, name, filename, source):181- """Return a cache bucket for the given template. All arguments are182- mandatory but filename may be `None`.183- """184- key = self.get_cache_key(name, filename)185- checksum = self.get_source_checksum(source)186- bucket = Bucket(environment, key, checksum)187- self.load_bytecode(bucket)188- return bucket189-190- def set_bucket(self, bucket):191- """Put the bucket into the cache."""192- self.dump_bytecode(bucket)193-194-195-class FileSystemBytecodeCache(BytecodeCache):196- """A bytecode cache that stores bytecode on the filesystem. It accepts197- two arguments: The directory where the cache items are stored and a198- pattern string that is used to build the filename.199-200- If no directory is specified a default cache directory is selected. On201- Windows the user's temp directory is used, on UNIX systems a directory202- is created for the user in the system temp directory.203-204- The pattern can be used to have multiple separate caches operate on the205- same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``206- is replaced with the cache key.207-208- >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')209-210- This bytecode cache supports clearing of the cache using the clear method.211- """212-213- def __init__(self, directory=None, pattern='__jinja2_%s.cache'):214- if directory is None:215- directory = self._get_default_cache_dir()216- self.directory = directory217- self.pattern = pattern218-219- def _get_default_cache_dir(self):220- def _unsafe_dir():221- raise RuntimeError('Cannot determine safe temp directory. You '222- 'need to explicitly provide one.')223-224- tmpdir = tempfile.gettempdir()225-226- # On windows the temporary directory is used specific unless227- # explicitly forced otherwise. We can just use that.228- if os.name == 'nt':229- return tmpdir230- if not hasattr(os, 'getuid'):231- _unsafe_dir()232-233- dirname = '_jinja2-cache-%d' % os.getuid()234- actual_dir = os.path.join(tmpdir, dirname)235-236- try:237- os.mkdir(actual_dir, stat.S_IRWXU)238- except OSError as e:239- if e.errno != errno.EEXIST:240- raise241- try:242- os.chmod(actual_dir, stat.S_IRWXU)243- actual_dir_stat = os.lstat(actual_dir)244- if actual_dir_stat.st_uid != os.getuid() \245- or not stat.S_ISDIR(actual_dir_stat.st_mode) \246- or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:247- _unsafe_dir()248- except OSError as e:249- if e.errno != errno.EEXIST:250- raise251-252- actual_dir_stat = os.lstat(actual_dir)253- if actual_dir_stat.st_uid != os.getuid() \254- or not stat.S_ISDIR(actual_dir_stat.st_mode) \255- or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU:256- _unsafe_dir()257-258- return actual_dir259-260- def _get_cache_filename(self, bucket):261- return path.join(self.directory, self.pattern % bucket.key)262-263- def load_bytecode(self, bucket):264- f = open_if_exists(self._get_cache_filename(bucket), 'rb')265- if f is not None:266- try:267- bucket.load_bytecode(f)268- finally:269- f.close()270-271- def dump_bytecode(self, bucket):272- f = open(self._get_cache_filename(bucket), 'wb')273- try:274- bucket.write_bytecode(f)275- finally:276- f.close()277-278- def clear(self):279- # imported lazily here because google app-engine doesn't support280- # write access on the file system and the function does not exist281- # normally.282- from os import remove283- files = fnmatch.filter(listdir(self.directory), self.pattern % '*')284- for filename in files:285- try:286- remove(path.join(self.directory, filename))287- except OSError:288- pass289-290-291-class MemcachedBytecodeCache(BytecodeCache):292- """This class implements a bytecode cache that uses a memcache cache for293- storing the information. It does not enforce a specific memcache library294- (tummy's memcache or cmemcache) but will accept any class that provides295- the minimal interface required.296-297- Libraries compatible with this class:298-299- - `cachelib <https://github.com/pallets/cachelib>`_300- - `python-memcached <https://pypi.org/project/python-memcached/>`_301-302- (Unfortunately the django cache interface is not compatible because it303- does not support storing binary data, only unicode. You can however pass304- the underlying cache client to the bytecode cache which is available305- as `django.core.cache.cache._client`.)306-307- The minimal interface for the client passed to the constructor is this:308-309- .. class:: MinimalClientInterface310-311- .. method:: set(key, value[, timeout])312-313- Stores the bytecode in the cache. `value` is a string and314- `timeout` the timeout of the key. If timeout is not provided315- a default timeout or no timeout should be assumed, if it's316- provided it's an integer with the number of seconds the cache317- item should exist.318-319- .. method:: get(key)320-321- Returns the value for the cache key. If the item does not322- exist in the cache the return value must be `None`.323-324- The other arguments to the constructor are the prefix for all keys that325- is added before the actual cache key and the timeout for the bytecode in326- the cache system. We recommend a high (or no) timeout.327-328- This bytecode cache does not support clearing of used items in the cache.329- The clear method is a no-operation function.330-331- .. versionadded:: 2.7332- Added support for ignoring memcache errors through the333- `ignore_memcache_errors` parameter.334- """335-336- def __init__(self, client, prefix='jinja2/bytecode/', timeout=None,337- ignore_memcache_errors=True):338- self.client = client339- self.prefix = prefix340- self.timeout = timeout341- self.ignore_memcache_errors = ignore_memcache_errors342-343- def load_bytecode(self, bucket):344- try:345- code = self.client.get(self.prefix + bucket.key)346- except Exception:347- if not self.ignore_memcache_errors:348- raise349- code = None350- if code is not None:351- bucket.bytecode_from_string(code)352-353- def dump_bytecode(self, bucket):354- args = (self.prefix + bucket.key, bucket.bytecode_to_string())355- if self.timeout is not None:356- args += (self.timeout,)357- try:358- self.client.set(*args)359- except Exception:360- if not self.ignore_memcache_errors:361- raisedeleted:jinja2/compiler.py-1772 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.compiler4- ~~~~~~~~~~~~~~~5-6- Compiles nodes into python code.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-from collections import namedtuple12-from itertools import chain13-from keyword import iskeyword as is_python_keyword14-from functools import update_wrapper15-from jinja2 import nodes16-from jinja2.nodes import EvalContext17-from jinja2.visitor import NodeVisitor18-from jinja2.optimizer import Optimizer19-from jinja2.exceptions import TemplateAssertionError20-from jinja2.utils import Markup, concat, escape21-from jinja2._compat import range_type, text_type, string_types, \22- iteritems, NativeStringIO, imap, izip23-from jinja2.idtracking import Symbols, VAR_LOAD_PARAMETER, \24- VAR_LOAD_RESOLVE, VAR_LOAD_ALIAS, VAR_LOAD_UNDEFINED25-26-27-operators = {28- 'eq': '==',29- 'ne': '!=',30- 'gt': '>',31- 'gteq': '>=',32- 'lt': '<',33- 'lteq': '<=',34- 'in': 'in',35- 'notin': 'not in'36-}37-38-# what method to iterate over items do we want to use for dict iteration39-# in generated code? on 2.x let's go with iteritems, on 3.x with items40-if hasattr(dict, 'iteritems'):41- dict_item_iter = 'iteritems'42-else:43- dict_item_iter = 'items'44-45-code_features = ['division']46-47-# does this python version support generator stops? (PEP 0479)48-try:49- exec('from __future__ import generator_stop')50- code_features.append('generator_stop')51-except SyntaxError:52- pass53-54-# does this python version support yield from?55-try:56- exec('def f(): yield from x()')57-except SyntaxError:58- supports_yield_from = False59-else:60- supports_yield_from = True61-62-63-def optimizeconst(f):64- def new_func(self, node, frame, **kwargs):65- # Only optimize if the frame is not volatile66- if self.optimized and not frame.eval_ctx.volatile:67- new_node = self.optimizer.visit(node, frame.eval_ctx)68- if new_node != node:69- return self.visit(new_node, frame)70- return f(self, node, frame, **kwargs)71- return update_wrapper(new_func, f)72-73-74-def generate(node, environment, name, filename, stream=None,75- defer_init=False, optimized=True):76- """Generate the python source for a node tree."""77- if not isinstance(node, nodes.Template):78- raise TypeError('Can\'t compile non template nodes')79- generator = environment.code_generator_class(environment, name, filename,80- stream, defer_init,81- optimized)82- generator.visit(node)83- if stream is None:84- return generator.stream.getvalue()85-86-87-def has_safe_repr(value):88- """Does the node have a safe representation?"""89- if value is None or value is NotImplemented or value is Ellipsis:90- return True91- if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:92- return True93- if type(value) in (tuple, list, set, frozenset):94- for item in value:95- if not has_safe_repr(item):96- return False97- return True98- elif type(value) is dict:99- for key, value in iteritems(value):100- if not has_safe_repr(key):101- return False102- if not has_safe_repr(value):103- return False104- return True105- return False106-107-108-def find_undeclared(nodes, names):109- """Check if the names passed are accessed undeclared. The return value110- is a set of all the undeclared names from the sequence of names found.111- """112- visitor = UndeclaredNameVisitor(names)113- try:114- for node in nodes:115- visitor.visit(node)116- except VisitorExit:117- pass118- return visitor.undeclared119-120-121-class MacroRef(object):122-123- def __init__(self, node):124- self.node = node125- self.accesses_caller = False126- self.accesses_kwargs = False127- self.accesses_varargs = False128-129-130-class Frame(object):131- """Holds compile time information for us."""132-133- def __init__(self, eval_ctx, parent=None, level=None):134- self.eval_ctx = eval_ctx135- self.symbols = Symbols(parent and parent.symbols or None,136- level=level)137-138- # a toplevel frame is the root + soft frames such as if conditions.139- self.toplevel = False140-141- # the root frame is basically just the outermost frame, so no if142- # conditions. This information is used to optimize inheritance143- # situations.144- self.rootlevel = False145-146- # in some dynamic inheritance situations the compiler needs to add147- # write tests around output statements.148- self.require_output_check = parent and parent.require_output_check149-150- # inside some tags we are using a buffer rather than yield statements.151- # this for example affects {% filter %} or {% macro %}. If a frame152- # is buffered this variable points to the name of the list used as153- # buffer.154- self.buffer = None155-156- # the name of the block we're in, otherwise None.157- self.block = parent and parent.block or None158-159- # the parent of this frame160- self.parent = parent161-162- if parent is not None:163- self.buffer = parent.buffer164-165- def copy(self):166- """Create a copy of the current one."""167- rv = object.__new__(self.__class__)168- rv.__dict__.update(self.__dict__)169- rv.symbols = self.symbols.copy()170- return rv171-172- def inner(self, isolated=False):173- """Return an inner frame."""174- if isolated:175- return Frame(self.eval_ctx, level=self.symbols.level + 1)176- return Frame(self.eval_ctx, self)177-178- def soft(self):179- """Return a soft frame. A soft frame may not be modified as180- standalone thing as it shares the resources with the frame it181- was created of, but it's not a rootlevel frame any longer.182-183- This is only used to implement if-statements.184- """185- rv = self.copy()186- rv.rootlevel = False187- return rv188-189- __copy__ = copy190-191-192-class VisitorExit(RuntimeError):193- """Exception used by the `UndeclaredNameVisitor` to signal a stop."""194-195-196-class DependencyFinderVisitor(NodeVisitor):197- """A visitor that collects filter and test calls."""198-199- def __init__(self):200- self.filters = set()201- self.tests = set()202-203- def visit_Filter(self, node):204- self.generic_visit(node)205- self.filters.add(node.name)206-207- def visit_Test(self, node):208- self.generic_visit(node)209- self.tests.add(node.name)210-211- def visit_Block(self, node):212- """Stop visiting at blocks."""213-214-215-class UndeclaredNameVisitor(NodeVisitor):216- """A visitor that checks if a name is accessed without being217- declared. This is different from the frame visitor as it will218- not stop at closure frames.219- """220-221- def __init__(self, names):222- self.names = set(names)223- self.undeclared = set()224-225- def visit_Name(self, node):226- if node.ctx == 'load' and node.name in self.names:227- self.undeclared.add(node.name)228- if self.undeclared == self.names:229- raise VisitorExit()230- else:231- self.names.discard(node.name)232-233- def visit_Block(self, node):234- """Stop visiting a blocks."""235-236-237-class CompilerExit(Exception):238- """Raised if the compiler encountered a situation where it just239- doesn't make sense to further process the code. Any block that240- raises such an exception is not further processed.241- """242-243-244-class CodeGenerator(NodeVisitor):245-246- def __init__(self, environment, name, filename, stream=None,247- defer_init=False, optimized=True):248- if stream is None:249- stream = NativeStringIO()250- self.environment = environment251- self.name = name252- self.filename = filename253- self.stream = stream254- self.created_block_context = False255- self.defer_init = defer_init256- self.optimized = optimized257- if optimized:258- self.optimizer = Optimizer(environment)259-260- # aliases for imports261- self.import_aliases = {}262-263- # a registry for all blocks. Because blocks are moved out264- # into the global python scope they are registered here265- self.blocks = {}266-267- # the number of extends statements so far268- self.extends_so_far = 0269-270- # some templates have a rootlevel extends. In this case we271- # can safely assume that we're a child template and do some272- # more optimizations.273- self.has_known_extends = False274-275- # the current line number276- self.code_lineno = 1277-278- # registry of all filters and tests (global, not block local)279- self.tests = {}280- self.filters = {}281-282- # the debug information283- self.debug_info = []284- self._write_debug_info = None285-286- # the number of new lines before the next write()287- self._new_lines = 0288-289- # the line number of the last written statement290- self._last_line = 0291-292- # true if nothing was written so far.293- self._first_write = True294-295- # used by the `temporary_identifier` method to get new296- # unique, temporary identifier297- self._last_identifier = 0298-299- # the current indentation300- self._indentation = 0301-302- # Tracks toplevel assignments303- self._assign_stack = []304-305- # Tracks parameter definition blocks306- self._param_def_block = []307-308- # Tracks the current context.309- self._context_reference_stack = ['context']310-311- # -- Various compilation helpers312-313- def fail(self, msg, lineno):314- """Fail with a :exc:`TemplateAssertionError`."""315- raise TemplateAssertionError(msg, lineno, self.name, self.filename)316-317- def temporary_identifier(self):318- """Get a new unique identifier."""319- self._last_identifier += 1320- return 't_%d' % self._last_identifier321-322- def buffer(self, frame):323- """Enable buffering for the frame from that point onwards."""324- frame.buffer = self.temporary_identifier()325- self.writeline('%s = []' % frame.buffer)326-327- def return_buffer_contents(self, frame, force_unescaped=False):328- """Return the buffer contents of the frame."""329- if not force_unescaped:330- if frame.eval_ctx.volatile:331- self.writeline('if context.eval_ctx.autoescape:')332- self.indent()333- self.writeline('return Markup(concat(%s))' % frame.buffer)334- self.outdent()335- self.writeline('else:')336- self.indent()337- self.writeline('return concat(%s)' % frame.buffer)338- self.outdent()339- return340- elif frame.eval_ctx.autoescape:341- self.writeline('return Markup(concat(%s))' % frame.buffer)342- return343- self.writeline('return concat(%s)' % frame.buffer)344-345- def indent(self):346- """Indent by one."""347- self._indentation += 1348-349- def outdent(self, step=1):350- """Outdent by step."""351- self._indentation -= step352-353- def start_write(self, frame, node=None):354- """Yield or write into the frame buffer."""355- if frame.buffer is None:356- self.writeline('yield ', node)357- else:358- self.writeline('%s.append(' % frame.buffer, node)359-360- def end_write(self, frame):361- """End the writing process started by `start_write`."""362- if frame.buffer is not None:363- self.write(')')364-365- def simple_write(self, s, frame, node=None):366- """Simple shortcut for start_write + write + end_write."""367- self.start_write(frame, node)368- self.write(s)369- self.end_write(frame)370-371- def blockvisit(self, nodes, frame):372- """Visit a list of nodes as block in a frame. If the current frame373- is no buffer a dummy ``if 0: yield None`` is written automatically.374- """375- try:376- self.writeline('pass')377- for node in nodes:378- self.visit(node, frame)379- except CompilerExit:380- pass381-382- def write(self, x):383- """Write a string into the output stream."""384- if self._new_lines:385- if not self._first_write:386- self.stream.write('\n' * self._new_lines)387- self.code_lineno += self._new_lines388- if self._write_debug_info is not None:389- self.debug_info.append((self._write_debug_info,390- self.code_lineno))391- self._write_debug_info = None392- self._first_write = False393- self.stream.write(' ' * self._indentation)394- self._new_lines = 0395- self.stream.write(x)396-397- def writeline(self, x, node=None, extra=0):398- """Combination of newline and write."""399- self.newline(node, extra)400- self.write(x)401-402- def newline(self, node=None, extra=0):403- """Add one or more newlines before the next write."""404- self._new_lines = max(self._new_lines, 1 + extra)405- if node is not None and node.lineno != self._last_line:406- self._write_debug_info = node.lineno407- self._last_line = node.lineno408-409- def signature(self, node, frame, extra_kwargs=None):410- """Writes a function call to the stream for the current node.411- A leading comma is added automatically. The extra keyword412- arguments may not include python keywords otherwise a syntax413- error could occur. The extra keyword arguments should be given414- as python dict.415- """416- # if any of the given keyword arguments is a python keyword417- # we have to make sure that no invalid call is created.418- kwarg_workaround = False419- for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):420- if is_python_keyword(kwarg):421- kwarg_workaround = True422- break423-424- for arg in node.args:425- self.write(', ')426- self.visit(arg, frame)427-428- if not kwarg_workaround:429- for kwarg in node.kwargs:430- self.write(', ')431- self.visit(kwarg, frame)432- if extra_kwargs is not None:433- for key, value in iteritems(extra_kwargs):434- self.write(', %s=%s' % (key, value))435- if node.dyn_args:436- self.write(', *')437- self.visit(node.dyn_args, frame)438-439- if kwarg_workaround:440- if node.dyn_kwargs is not None:441- self.write(', **dict({')442- else:443- self.write(', **{')444- for kwarg in node.kwargs:445- self.write('%r: ' % kwarg.key)446- self.visit(kwarg.value, frame)447- self.write(', ')448- if extra_kwargs is not None:449- for key, value in iteritems(extra_kwargs):450- self.write('%r: %s, ' % (key, value))451- if node.dyn_kwargs is not None:452- self.write('}, **')453- self.visit(node.dyn_kwargs, frame)454- self.write(')')455- else:456- self.write('}')457-458- elif node.dyn_kwargs is not None:459- self.write(', **')460- self.visit(node.dyn_kwargs, frame)461-462- def pull_dependencies(self, nodes):463- """Pull all the dependencies."""464- visitor = DependencyFinderVisitor()465- for node in nodes:466- visitor.visit(node)467- for dependency in 'filters', 'tests':468- mapping = getattr(self, dependency)469- for name in getattr(visitor, dependency):470- if name not in mapping:471- mapping[name] = self.temporary_identifier()472- self.writeline('%s = environment.%s[%r]' %473- (mapping[name], dependency, name))474-475- def enter_frame(self, frame):476- undefs = []477- for target, (action, param) in iteritems(frame.symbols.loads):478- if action == VAR_LOAD_PARAMETER:479- pass480- elif action == VAR_LOAD_RESOLVE:481- self.writeline('%s = %s(%r)' %482- (target, self.get_resolve_func(), param))483- elif action == VAR_LOAD_ALIAS:484- self.writeline('%s = %s' % (target, param))485- elif action == VAR_LOAD_UNDEFINED:486- undefs.append(target)487- else:488- raise NotImplementedError('unknown load instruction')489- if undefs:490- self.writeline('%s = missing' % ' = '.join(undefs))491-492- def leave_frame(self, frame, with_python_scope=False):493- if not with_python_scope:494- undefs = []495- for target, _ in iteritems(frame.symbols.loads):496- undefs.append(target)497- if undefs:498- self.writeline('%s = missing' % ' = '.join(undefs))499-500- def func(self, name):501- if self.environment.is_async:502- return 'async def %s' % name503- return 'def %s' % name504-505- def macro_body(self, node, frame):506- """Dump the function def of a macro or call block."""507- frame = frame.inner()508- frame.symbols.analyze_node(node)509- macro_ref = MacroRef(node)510-511- explicit_caller = None512- skip_special_params = set()513- args = []514- for idx, arg in enumerate(node.args):515- if arg.name == 'caller':516- explicit_caller = idx517- if arg.name in ('kwargs', 'varargs'):518- skip_special_params.add(arg.name)519- args.append(frame.symbols.ref(arg.name))520-521- undeclared = find_undeclared(node.body, ('caller', 'kwargs', 'varargs'))522-523- if 'caller' in undeclared:524- # In older Jinja versions there was a bug that allowed caller525- # to retain the special behavior even if it was mentioned in526- # the argument list. However thankfully this was only really527- # working if it was the last argument. So we are explicitly528- # checking this now and error out if it is anywhere else in529- # the argument list.530- if explicit_caller is not None:531- try:532- node.defaults[explicit_caller - len(node.args)]533- except IndexError:534- self.fail('When defining macros or call blocks the '535- 'special "caller" argument must be omitted '536- 'or be given a default.', node.lineno)537- else:538- args.append(frame.symbols.declare_parameter('caller'))539- macro_ref.accesses_caller = True540- if 'kwargs' in undeclared and not 'kwargs' in skip_special_params:541- args.append(frame.symbols.declare_parameter('kwargs'))542- macro_ref.accesses_kwargs = True543- if 'varargs' in undeclared and not 'varargs' in skip_special_params:544- args.append(frame.symbols.declare_parameter('varargs'))545- macro_ref.accesses_varargs = True546-547- # macros are delayed, they never require output checks548- frame.require_output_check = False549- frame.symbols.analyze_node(node)550- self.writeline('%s(%s):' % (self.func('macro'), ', '.join(args)), node)551- self.indent()552-553- self.buffer(frame)554- self.enter_frame(frame)555-556- self.push_parameter_definitions(frame)557- for idx, arg in enumerate(node.args):558- ref = frame.symbols.ref(arg.name)559- self.writeline('if %s is missing:' % ref)560- self.indent()561- try:562- default = node.defaults[idx - len(node.args)]563- except IndexError:564- self.writeline('%s = undefined(%r, name=%r)' % (565- ref,566- 'parameter %r was not provided' % arg.name,567- arg.name))568- else:569- self.writeline('%s = ' % ref)570- self.visit(default, frame)571- self.mark_parameter_stored(ref)572- self.outdent()573- self.pop_parameter_definitions()574-575- self.blockvisit(node.body, frame)576- self.return_buffer_contents(frame, force_unescaped=True)577- self.leave_frame(frame, with_python_scope=True)578- self.outdent()579-580- return frame, macro_ref581-582- def macro_def(self, macro_ref, frame):583- """Dump the macro definition for the def created by macro_body."""584- arg_tuple = ', '.join(repr(x.name) for x in macro_ref.node.args)585- name = getattr(macro_ref.node, 'name', None)586- if len(macro_ref.node.args) == 1:587- arg_tuple += ','588- self.write('Macro(environment, macro, %r, (%s), %r, %r, %r, '589- 'context.eval_ctx.autoescape)' %590- (name, arg_tuple, macro_ref.accesses_kwargs,591- macro_ref.accesses_varargs, macro_ref.accesses_caller))592-593- def position(self, node):594- """Return a human readable position for the node."""595- rv = 'line %d' % node.lineno596- if self.name is not None:597- rv += ' in ' + repr(self.name)598- return rv599-600- def dump_local_context(self, frame):601- return '{%s}' % ', '.join(602- '%r: %s' % (name, target) for name, target603- in iteritems(frame.symbols.dump_stores()))604-605- def write_commons(self):606- """Writes a common preamble that is used by root and block functions.607- Primarily this sets up common local helpers and enforces a generator608- through a dead branch.609- """610- self.writeline('resolve = context.resolve_or_missing')611- self.writeline('undefined = environment.undefined')612- # always use the standard Undefined class for the implicit else of613- # conditional expressions614- self.writeline('cond_expr_undefined = Undefined')615- self.writeline('if 0: yield None')616-617- def push_parameter_definitions(self, frame):618- """Pushes all parameter targets from the given frame into a local619- stack that permits tracking of yet to be assigned parameters. In620- particular this enables the optimization from `visit_Name` to skip621- undefined expressions for parameters in macros as macros can reference622- otherwise unbound parameters.623- """624- self._param_def_block.append(frame.symbols.dump_param_targets())625-626- def pop_parameter_definitions(self):627- """Pops the current parameter definitions set."""628- self._param_def_block.pop()629-630- def mark_parameter_stored(self, target):631- """Marks a parameter in the current parameter definitions as stored.632- This will skip the enforced undefined checks.633- """634- if self._param_def_block:635- self._param_def_block[-1].discard(target)636-637- def push_context_reference(self, target):638- self._context_reference_stack.append(target)639-640- def pop_context_reference(self):641- self._context_reference_stack.pop()642-643- def get_context_ref(self):644- return self._context_reference_stack[-1]645-646- def get_resolve_func(self):647- target = self._context_reference_stack[-1]648- if target == 'context':649- return 'resolve'650- return '%s.resolve' % target651-652- def derive_context(self, frame):653- return '%s.derived(%s)' % (654- self.get_context_ref(),655- self.dump_local_context(frame),656- )657-658- def parameter_is_undeclared(self, target):659- """Checks if a given target is an undeclared parameter."""660- if not self._param_def_block:661- return False662- return target in self._param_def_block[-1]663-664- def push_assign_tracking(self):665- """Pushes a new layer for assignment tracking."""666- self._assign_stack.append(set())667-668- def pop_assign_tracking(self, frame):669- """Pops the topmost level for assignment tracking and updates the670- context variables if necessary.671- """672- vars = self._assign_stack.pop()673- if not frame.toplevel or not vars:674- return675- public_names = [x for x in vars if x[:1] != '_']676- if len(vars) == 1:677- name = next(iter(vars))678- ref = frame.symbols.ref(name)679- self.writeline('context.vars[%r] = %s' % (name, ref))680- else:681- self.writeline('context.vars.update({')682- for idx, name in enumerate(vars):683- if idx:684- self.write(', ')685- ref = frame.symbols.ref(name)686- self.write('%r: %s' % (name, ref))687- self.write('})')688- if public_names:689- if len(public_names) == 1:690- self.writeline('context.exported_vars.add(%r)' %691- public_names[0])692- else:693- self.writeline('context.exported_vars.update((%s))' %694- ', '.join(imap(repr, public_names)))695-696- # -- Statement Visitors697-698- def visit_Template(self, node, frame=None):699- assert frame is None, 'no root frame allowed'700- eval_ctx = EvalContext(self.environment, self.name)701-702- from jinja2.runtime import __all__ as exported703- self.writeline('from __future__ import %s' % ', '.join(code_features))704- self.writeline('from jinja2.runtime import ' + ', '.join(exported))705-706- if self.environment.is_async:707- self.writeline('from jinja2.asyncsupport import auto_await, '708- 'auto_aiter, AsyncLoopContext')709-710- # if we want a deferred initialization we cannot move the711- # environment into a local name712- envenv = not self.defer_init and ', environment=environment' or ''713-714- # do we have an extends tag at all? If not, we can save some715- # overhead by just not processing any inheritance code.716- have_extends = node.find(nodes.Extends) is not None717-718- # find all blocks719- for block in node.find_all(nodes.Block):720- if block.name in self.blocks:721- self.fail('block %r defined twice' % block.name, block.lineno)722- self.blocks[block.name] = block723-724- # find all imports and import them725- for import_ in node.find_all(nodes.ImportedName):726- if import_.importname not in self.import_aliases:727- imp = import_.importname728- self.import_aliases[imp] = alias = self.temporary_identifier()729- if '.' in imp:730- module, obj = imp.rsplit('.', 1)731- self.writeline('from %s import %s as %s' %732- (module, obj, alias))733- else:734- self.writeline('import %s as %s' % (imp, alias))735-736- # add the load name737- self.writeline('name = %r' % self.name)738-739- # generate the root render function.740- self.writeline('%s(context, missing=missing%s):' %741- (self.func('root'), envenv), extra=1)742- self.indent()743- self.write_commons()744-745- # process the root746- frame = Frame(eval_ctx)747- if 'self' in find_undeclared(node.body, ('self',)):748- ref = frame.symbols.declare_parameter('self')749- self.writeline('%s = TemplateReference(context)' % ref)750- frame.symbols.analyze_node(node)751- frame.toplevel = frame.rootlevel = True752- frame.require_output_check = have_extends and not self.has_known_extends753- if have_extends:754- self.writeline('parent_template = None')755- self.enter_frame(frame)756- self.pull_dependencies(node.body)757- self.blockvisit(node.body, frame)758- self.leave_frame(frame, with_python_scope=True)759- self.outdent()760-761- # make sure that the parent root is called.762- if have_extends:763- if not self.has_known_extends:764- self.indent()765- self.writeline('if parent_template is not None:')766- self.indent()767- if supports_yield_from and not self.environment.is_async:768- self.writeline('yield from parent_template.'769- 'root_render_func(context)')770- else:771- self.writeline('%sfor event in parent_template.'772- 'root_render_func(context):' %773- (self.environment.is_async and 'async ' or ''))774- self.indent()775- self.writeline('yield event')776- self.outdent()777- self.outdent(1 + (not self.has_known_extends))778-779- # at this point we now have the blocks collected and can visit them too.780- for name, block in iteritems(self.blocks):781- self.writeline('%s(context, missing=missing%s):' %782- (self.func('block_' + name), envenv),783- block, 1)784- self.indent()785- self.write_commons()786- # It's important that we do not make this frame a child of the787- # toplevel template. This would cause a variety of788- # interesting issues with identifier tracking.789- block_frame = Frame(eval_ctx)790- undeclared = find_undeclared(block.body, ('self', 'super'))791- if 'self' in undeclared:792- ref = block_frame.symbols.declare_parameter('self')793- self.writeline('%s = TemplateReference(context)' % ref)794- if 'super' in undeclared:795- ref = block_frame.symbols.declare_parameter('super')796- self.writeline('%s = context.super(%r, '797- 'block_%s)' % (ref, name, name))798- block_frame.symbols.analyze_node(block)799- block_frame.block = name800- self.enter_frame(block_frame)801- self.pull_dependencies(block.body)802- self.blockvisit(block.body, block_frame)803- self.leave_frame(block_frame, with_python_scope=True)804- self.outdent()805-806- self.writeline('blocks = {%s}' % ', '.join('%r: block_%s' % (x, x)807- for x in self.blocks),808- extra=1)809-810- # add a function that returns the debug info811- self.writeline('debug_info = %r' % '&'.join('%s=%s' % x for x812- in self.debug_info))813-814- def visit_Block(self, node, frame):815- """Call a block and register it for the template."""816- level = 0817- if frame.toplevel:818- # if we know that we are a child template, there is no need to819- # check if we are one820- if self.has_known_extends:821- return822- if self.extends_so_far > 0:823- self.writeline('if parent_template is None:')824- self.indent()825- level += 1826-827- if node.scoped:828- context = self.derive_context(frame)829- else:830- context = self.get_context_ref()831-832- if supports_yield_from and not self.environment.is_async and \833- frame.buffer is None:834- self.writeline('yield from context.blocks[%r][0](%s)' % (835- node.name, context), node)836- else:837- loop = self.environment.is_async and 'async for' or 'for'838- self.writeline('%s event in context.blocks[%r][0](%s):' % (839- loop, node.name, context), node)840- self.indent()841- self.simple_write('event', frame)842- self.outdent()843-844- self.outdent(level)845-846- def visit_Extends(self, node, frame):847- """Calls the extender."""848- if not frame.toplevel:849- self.fail('cannot use extend from a non top-level scope',850- node.lineno)851-852- # if the number of extends statements in general is zero so853- # far, we don't have to add a check if something extended854- # the template before this one.855- if self.extends_so_far > 0:856-857- # if we have a known extends we just add a template runtime858- # error into the generated code. We could catch that at compile859- # time too, but i welcome it not to confuse users by throwing the860- # same error at different times just "because we can".861- if not self.has_known_extends:862- self.writeline('if parent_template is not None:')863- self.indent()864- self.writeline('raise TemplateRuntimeError(%r)' %865- 'extended multiple times')866-867- # if we have a known extends already we don't need that code here868- # as we know that the template execution will end here.869- if self.has_known_extends:870- raise CompilerExit()871- else:872- self.outdent()873-874- self.writeline('parent_template = environment.get_template(', node)875- self.visit(node.template, frame)876- self.write(', %r)' % self.name)877- self.writeline('for name, parent_block in parent_template.'878- 'blocks.%s():' % dict_item_iter)879- self.indent()880- self.writeline('context.blocks.setdefault(name, []).'881- 'append(parent_block)')882- self.outdent()883-884- # if this extends statement was in the root level we can take885- # advantage of that information and simplify the generated code886- # in the top level from this point onwards887- if frame.rootlevel:888- self.has_known_extends = True889-890- # and now we have one more891- self.extends_so_far += 1892-893- def visit_Include(self, node, frame):894- """Handles includes."""895- if node.ignore_missing:896- self.writeline('try:')897- self.indent()898-899- func_name = 'get_or_select_template'900- if isinstance(node.template, nodes.Const):901- if isinstance(node.template.value, string_types):902- func_name = 'get_template'903- elif isinstance(node.template.value, (tuple, list)):904- func_name = 'select_template'905- elif isinstance(node.template, (nodes.Tuple, nodes.List)):906- func_name = 'select_template'907-908- self.writeline('template = environment.%s(' % func_name, node)909- self.visit(node.template, frame)910- self.write(', %r)' % self.name)911- if node.ignore_missing:912- self.outdent()913- self.writeline('except TemplateNotFound:')914- self.indent()915- self.writeline('pass')916- self.outdent()917- self.writeline('else:')918- self.indent()919-920- skip_event_yield = False921- if node.with_context:922- loop = self.environment.is_async and 'async for' or 'for'923- self.writeline('%s event in template.root_render_func('924- 'template.new_context(context.get_all(), True, '925- '%s)):' % (loop, self.dump_local_context(frame)))926- elif self.environment.is_async:927- self.writeline('for event in (await '928- 'template._get_default_module_async())'929- '._body_stream:')930- else:931- if supports_yield_from:932- self.writeline('yield from template._get_default_module()'933- '._body_stream')934- skip_event_yield = True935- else:936- self.writeline('for event in template._get_default_module()'937- '._body_stream:')938-939- if not skip_event_yield:940- self.indent()941- self.simple_write('event', frame)942- self.outdent()943-944- if node.ignore_missing:945- self.outdent()946-947- def visit_Import(self, node, frame):948- """Visit regular imports."""949- self.writeline('%s = ' % frame.symbols.ref(node.target), node)950- if frame.toplevel:951- self.write('context.vars[%r] = ' % node.target)952- if self.environment.is_async:953- self.write('await ')954- self.write('environment.get_template(')955- self.visit(node.template, frame)956- self.write(', %r).' % self.name)957- if node.with_context:958- self.write('make_module%s(context.get_all(), True, %s)'959- % (self.environment.is_async and '_async' or '',960- self.dump_local_context(frame)))961- elif self.environment.is_async:962- self.write('_get_default_module_async()')963- else:964- self.write('_get_default_module()')965- if frame.toplevel and not node.target.startswith('_'):966- self.writeline('context.exported_vars.discard(%r)' % node.target)967-968- def visit_FromImport(self, node, frame):969- """Visit named imports."""970- self.newline(node)971- self.write('included_template = %senvironment.get_template('972- % (self.environment.is_async and 'await ' or ''))973- self.visit(node.template, frame)974- self.write(', %r).' % self.name)975- if node.with_context:976- self.write('make_module%s(context.get_all(), True, %s)'977- % (self.environment.is_async and '_async' or '',978- self.dump_local_context(frame)))979- elif self.environment.is_async:980- self.write('_get_default_module_async()')981- else:982- self.write('_get_default_module()')983-984- var_names = []985- discarded_names = []986- for name in node.names:987- if isinstance(name, tuple):988- name, alias = name989- else:990- alias = name991- self.writeline('%s = getattr(included_template, '992- '%r, missing)' % (frame.symbols.ref(alias), name))993- self.writeline('if %s is missing:' % frame.symbols.ref(alias))994- self.indent()995- self.writeline('%s = undefined(%r %% '996- 'included_template.__name__, '997- 'name=%r)' %998- (frame.symbols.ref(alias),999- 'the template %%r (imported on %s) does '1000- 'not export the requested name %s' % (1001- self.position(node),1002- repr(name)1003- ), name))1004- self.outdent()1005- if frame.toplevel:1006- var_names.append(alias)1007- if not alias.startswith('_'):1008- discarded_names.append(alias)1009-1010- if var_names:1011- if len(var_names) == 1:1012- name = var_names[0]1013- self.writeline('context.vars[%r] = %s' %1014- (name, frame.symbols.ref(name)))1015- else:1016- self.writeline('context.vars.update({%s})' % ', '.join(1017- '%r: %s' % (name, frame.symbols.ref(name)) for name in var_names1018- ))1019- if discarded_names:1020- if len(discarded_names) == 1:1021- self.writeline('context.exported_vars.discard(%r)' %1022- discarded_names[0])1023- else:1024- self.writeline('context.exported_vars.difference_'1025- 'update((%s))' % ', '.join(imap(repr, discarded_names)))1026-1027- def visit_For(self, node, frame):1028- loop_frame = frame.inner()1029- test_frame = frame.inner()1030- else_frame = frame.inner()1031-1032- # try to figure out if we have an extended loop. An extended loop1033- # is necessary if the loop is in recursive mode if the special loop1034- # variable is accessed in the body.1035- extended_loop = node.recursive or 'loop' in \1036- find_undeclared(node.iter_child_nodes(1037- only=('body',)), ('loop',))1038-1039- loop_ref = None1040- if extended_loop:1041- loop_ref = loop_frame.symbols.declare_parameter('loop')1042-1043- loop_frame.symbols.analyze_node(node, for_branch='body')1044- if node.else_:1045- else_frame.symbols.analyze_node(node, for_branch='else')1046-1047- if node.test:1048- loop_filter_func = self.temporary_identifier()1049- test_frame.symbols.analyze_node(node, for_branch='test')1050- self.writeline('%s(fiter):' % self.func(loop_filter_func), node.test)1051- self.indent()1052- self.enter_frame(test_frame)1053- self.writeline(self.environment.is_async and 'async for ' or 'for ')1054- self.visit(node.target, loop_frame)1055- self.write(' in ')1056- self.write(self.environment.is_async and 'auto_aiter(fiter)' or 'fiter')1057- self.write(':')1058- self.indent()1059- self.writeline('if ', node.test)1060- self.visit(node.test, test_frame)1061- self.write(':')1062- self.indent()1063- self.writeline('yield ')1064- self.visit(node.target, loop_frame)1065- self.outdent(3)1066- self.leave_frame(test_frame, with_python_scope=True)1067-1068- # if we don't have an recursive loop we have to find the shadowed1069- # variables at that point. Because loops can be nested but the loop1070- # variable is a special one we have to enforce aliasing for it.1071- if node.recursive:1072- self.writeline('%s(reciter, loop_render_func, depth=0):' %1073- self.func('loop'), node)1074- self.indent()1075- self.buffer(loop_frame)1076-1077- # Use the same buffer for the else frame1078- else_frame.buffer = loop_frame.buffer1079-1080- # make sure the loop variable is a special one and raise a template1081- # assertion error if a loop tries to write to loop1082- if extended_loop:1083- self.writeline('%s = missing' % loop_ref)1084-1085- for name in node.find_all(nodes.Name):1086- if name.ctx == 'store' and name.name == 'loop':1087- self.fail('Can\'t assign to special loop variable '1088- 'in for-loop target', name.lineno)1089-1090- if node.else_:1091- iteration_indicator = self.temporary_identifier()1092- self.writeline('%s = 1' % iteration_indicator)1093-1094- self.writeline(self.environment.is_async and 'async for ' or 'for ', node)1095- self.visit(node.target, loop_frame)1096- if extended_loop:1097- if self.environment.is_async:1098- self.write(', %s in AsyncLoopContext(' % loop_ref)1099- else:1100- self.write(', %s in LoopContext(' % loop_ref)1101- else:1102- self.write(' in ')1103-1104- if node.test:1105- self.write('%s(' % loop_filter_func)1106- if node.recursive:1107- self.write('reciter')1108- else:1109- if self.environment.is_async and not extended_loop:1110- self.write('auto_aiter(')1111- self.visit(node.iter, frame)1112- if self.environment.is_async and not extended_loop:1113- self.write(')')1114- if node.test:1115- self.write(')')1116-1117- if node.recursive:1118- self.write(', undefined, loop_render_func, depth):')1119- else:1120- self.write(extended_loop and ', undefined):' or ':')1121-1122- self.indent()1123- self.enter_frame(loop_frame)1124-1125- self.blockvisit(node.body, loop_frame)1126- if node.else_:1127- self.writeline('%s = 0' % iteration_indicator)1128- self.outdent()1129- self.leave_frame(loop_frame, with_python_scope=node.recursive1130- and not node.else_)1131-1132- if node.else_:1133- self.writeline('if %s:' % iteration_indicator)1134- self.indent()1135- self.enter_frame(else_frame)1136- self.blockvisit(node.else_, else_frame)1137- self.leave_frame(else_frame)1138- self.outdent()1139-1140- # if the node was recursive we have to return the buffer contents1141- # and start the iteration code1142- if node.recursive:1143- self.return_buffer_contents(loop_frame)1144- self.outdent()1145- self.start_write(frame, node)1146- if self.environment.is_async:1147- self.write('await ')1148- self.write('loop(')1149- if self.environment.is_async:1150- self.write('auto_aiter(')1151- self.visit(node.iter, frame)1152- if self.environment.is_async:1153- self.write(')')1154- self.write(', loop)')1155- self.end_write(frame)1156-1157- def visit_If(self, node, frame):1158- if_frame = frame.soft()1159- self.writeline('if ', node)1160- self.visit(node.test, if_frame)1161- self.write(':')1162- self.indent()1163- self.blockvisit(node.body, if_frame)1164- self.outdent()1165- for elif_ in node.elif_:1166- self.writeline('elif ', elif_)1167- self.visit(elif_.test, if_frame)1168- self.write(':')1169- self.indent()1170- self.blockvisit(elif_.body, if_frame)1171- self.outdent()1172- if node.else_:1173- self.writeline('else:')1174- self.indent()1175- self.blockvisit(node.else_, if_frame)1176- self.outdent()1177-1178- def visit_Macro(self, node, frame):1179- macro_frame, macro_ref = self.macro_body(node, frame)1180- self.newline()1181- if frame.toplevel:1182- if not node.name.startswith('_'):1183- self.write('context.exported_vars.add(%r)' % node.name)1184- ref = frame.symbols.ref(node.name)1185- self.writeline('context.vars[%r] = ' % node.name)1186- self.write('%s = ' % frame.symbols.ref(node.name))1187- self.macro_def(macro_ref, macro_frame)1188-1189- def visit_CallBlock(self, node, frame):1190- call_frame, macro_ref = self.macro_body(node, frame)1191- self.writeline('caller = ')1192- self.macro_def(macro_ref, call_frame)1193- self.start_write(frame, node)1194- self.visit_Call(node.call, frame, forward_caller=True)1195- self.end_write(frame)1196-1197- def visit_FilterBlock(self, node, frame):1198- filter_frame = frame.inner()1199- filter_frame.symbols.analyze_node(node)1200- self.enter_frame(filter_frame)1201- self.buffer(filter_frame)1202- self.blockvisit(node.body, filter_frame)1203- self.start_write(frame, node)1204- self.visit_Filter(node.filter, filter_frame)1205- self.end_write(frame)1206- self.leave_frame(filter_frame)1207-1208- def visit_With(self, node, frame):1209- with_frame = frame.inner()1210- with_frame.symbols.analyze_node(node)1211- self.enter_frame(with_frame)1212- for idx, (target, expr) in enumerate(izip(node.targets, node.values)):1213- self.newline()1214- self.visit(target, with_frame)1215- self.write(' = ')1216- self.visit(expr, frame)1217- self.blockvisit(node.body, with_frame)1218- self.leave_frame(with_frame)1219-1220- def visit_ExprStmt(self, node, frame):1221- self.newline(node)1222- self.visit(node.node, frame)1223-1224- _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1225- #: The default finalize function if the environment isn't configured1226- #: with one. Or if the environment has one, this is called on that1227- #: function's output for constants.1228- _default_finalize = text_type1229- _finalize = None1230-1231- def _make_finalize(self):1232- """Build the finalize function to be used on constants and at1233- runtime. Cached so it's only created once for all output nodes.1234-1235- Returns a ``namedtuple`` with the following attributes:1236-1237- ``const``1238- A function to finalize constant data at compile time.1239-1240- ``src``1241- Source code to output around nodes to be evaluated at1242- runtime.1243- """1244- if self._finalize is not None:1245- return self._finalize1246-1247- finalize = default = self._default_finalize1248- src = None1249-1250- if self.environment.finalize:1251- src = "environment.finalize("1252- env_finalize = self.environment.finalize1253-1254- def finalize(value):1255- return default(env_finalize(value))1256-1257- if getattr(env_finalize, "contextfunction", False):1258- src += "context, "1259- finalize = None1260- elif getattr(env_finalize, "evalcontextfunction", False):1261- src += "context.eval_ctx, "1262- finalize = None1263- elif getattr(env_finalize, "environmentfunction", False):1264- src += "environment, "1265-1266- def finalize(value):1267- return default(env_finalize(self.environment, value))1268-1269- self._finalize = self._FinalizeInfo(finalize, src)1270- return self._finalize1271-1272- def _output_const_repr(self, group):1273- """Given a group of constant values converted from ``Output``1274- child nodes, produce a string to write to the template module1275- source.1276- """1277- return repr(concat(group))1278-1279- def _output_child_to_const(self, node, frame, finalize):1280- """Try to optimize a child of an ``Output`` node by trying to1281- convert it to constant, finalized data at compile time.1282-1283- If :exc:`Impossible` is raised, the node is not constant and1284- will be evaluated at runtime. Any other exception will also be1285- evaluated at runtime for easier debugging.1286- """1287- const = node.as_const(frame.eval_ctx)1288-1289- if frame.eval_ctx.autoescape:1290- const = escape(const)1291-1292- # Template data doesn't go through finalize.1293- if isinstance(node, nodes.TemplateData):1294- return text_type(const)1295-1296- return finalize.const(const)1297-1298- def _output_child_pre(self, node, frame, finalize):1299- """Output extra source code before visiting a child of an1300- ``Output`` node.1301- """1302- if frame.eval_ctx.volatile:1303- self.write("(escape if context.eval_ctx.autoescape else to_string)(")1304- elif frame.eval_ctx.autoescape:1305- self.write("escape(")1306- else:1307- self.write("to_string(")1308-1309- if finalize.src is not None:1310- self.write(finalize.src)1311-1312- def _output_child_post(self, node, frame, finalize):1313- """Output extra source code after visiting a child of an1314- ``Output`` node.1315- """1316- self.write(")")1317-1318- if finalize.src is not None:1319- self.write(")")1320-1321- def visit_Output(self, node, frame):1322- # If an extends is active, don't render outside a block.1323- if frame.require_output_check:1324- # A top-level extends is known to exist at compile time.1325- if self.has_known_extends:1326- return1327-1328- self.writeline("if parent_template is None:")1329- self.indent()1330-1331- finalize = self._make_finalize()1332- body = []1333-1334- # Evaluate constants at compile time if possible. Each item in1335- # body will be either a list of static data or a node to be1336- # evaluated at runtime.1337- for child in node.nodes:1338- try:1339- if not (1340- # If the finalize function requires runtime context,1341- # constants can't be evaluated at compile time.1342- finalize.const1343- # Unless it's basic template data that won't be1344- # finalized anyway.1345- or isinstance(child, nodes.TemplateData)1346- ):1347- raise nodes.Impossible()1348-1349- const = self._output_child_to_const(child, frame, finalize)1350- except (nodes.Impossible, Exception):1351- # The node was not constant and needs to be evaluated at1352- # runtime. Or another error was raised, which is easier1353- # to debug at runtime.1354- body.append(child)1355- continue1356-1357- if body and isinstance(body[-1], list):1358- body[-1].append(const)1359- else:1360- body.append([const])1361-1362- if frame.buffer is not None:1363- if len(body) == 1:1364- self.writeline("%s.append(" % frame.buffer)1365- else:1366- self.writeline("%s.extend((" % frame.buffer)1367-1368- self.indent()1369-1370- for item in body:1371- if isinstance(item, list):1372- # A group of constant data to join and output.1373- val = self._output_const_repr(item)1374-1375- if frame.buffer is None:1376- self.writeline("yield " + val)1377- else:1378- self.writeline(val + ",")1379- else:1380- if frame.buffer is None:1381- self.writeline("yield ", item)1382- else:1383- self.newline(item)1384-1385- # A node to be evaluated at runtime.1386- self._output_child_pre(item, frame, finalize)1387- self.visit(item, frame)1388- self._output_child_post(item, frame, finalize)1389-1390- if frame.buffer is not None:1391- self.write(",")1392-1393- if frame.buffer is not None:1394- self.outdent()1395- self.writeline(")" if len(body) == 1 else "))")1396-1397- if frame.require_output_check:1398- self.outdent()1399-1400- def visit_Assign(self, node, frame):1401- self.push_assign_tracking()1402- self.newline(node)1403- self.visit(node.target, frame)1404- self.write(' = ')1405- self.visit(node.node, frame)1406- self.pop_assign_tracking(frame)1407-1408- def visit_AssignBlock(self, node, frame):1409- self.push_assign_tracking()1410- block_frame = frame.inner()1411- # This is a special case. Since a set block always captures we1412- # will disable output checks. This way one can use set blocks1413- # toplevel even in extended templates.1414- block_frame.require_output_check = False1415- block_frame.symbols.analyze_node(node)1416- self.enter_frame(block_frame)1417- self.buffer(block_frame)1418- self.blockvisit(node.body, block_frame)1419- self.newline(node)1420- self.visit(node.target, frame)1421- self.write(' = (Markup if context.eval_ctx.autoescape '1422- 'else identity)(')1423- if node.filter is not None:1424- self.visit_Filter(node.filter, block_frame)1425- else:1426- self.write('concat(%s)' % block_frame.buffer)1427- self.write(')')1428- self.pop_assign_tracking(frame)1429- self.leave_frame(block_frame)1430-1431- # -- Expression Visitors1432-1433- def visit_Name(self, node, frame):1434- if node.ctx == 'store' and frame.toplevel:1435- if self._assign_stack:1436- self._assign_stack[-1].add(node.name)1437- ref = frame.symbols.ref(node.name)1438-1439- # If we are looking up a variable we might have to deal with the1440- # case where it's undefined. We can skip that case if the load1441- # instruction indicates a parameter which are always defined.1442- if node.ctx == 'load':1443- load = frame.symbols.find_load(ref)1444- if not (load is not None and load[0] == VAR_LOAD_PARAMETER and \1445- not self.parameter_is_undeclared(ref)):1446- self.write('(undefined(name=%r) if %s is missing else %s)' %1447- (node.name, ref, ref))1448- return1449-1450- self.write(ref)1451-1452- def visit_NSRef(self, node, frame):1453- # NSRefs can only be used to store values; since they use the normal1454- # `foo.bar` notation they will be parsed as a normal attribute access1455- # when used anywhere but in a `set` context1456- ref = frame.symbols.ref(node.name)1457- self.writeline('if not isinstance(%s, Namespace):' % ref)1458- self.indent()1459- self.writeline('raise TemplateRuntimeError(%r)' %1460- 'cannot assign attribute on non-namespace object')1461- self.outdent()1462- self.writeline('%s[%r]' % (ref, node.attr))1463-1464- def visit_Const(self, node, frame):1465- val = node.as_const(frame.eval_ctx)1466- if isinstance(val, float):1467- self.write(str(val))1468- else:1469- self.write(repr(val))1470-1471- def visit_TemplateData(self, node, frame):1472- try:1473- self.write(repr(node.as_const(frame.eval_ctx)))1474- except nodes.Impossible:1475- self.write('(Markup if context.eval_ctx.autoescape else identity)(%r)'1476- % node.data)1477-1478- def visit_Tuple(self, node, frame):1479- self.write('(')1480- idx = -11481- for idx, item in enumerate(node.items):1482- if idx:1483- self.write(', ')1484- self.visit(item, frame)1485- self.write(idx == 0 and ',)' or ')')1486-1487- def visit_List(self, node, frame):1488- self.write('[')1489- for idx, item in enumerate(node.items):1490- if idx:1491- self.write(', ')1492- self.visit(item, frame)1493- self.write(']')1494-1495- def visit_Dict(self, node, frame):1496- self.write('{')1497- for idx, item in enumerate(node.items):1498- if idx:1499- self.write(', ')1500- self.visit(item.key, frame)1501- self.write(': ')1502- self.visit(item.value, frame)1503- self.write('}')1504-1505- def binop(operator, interceptable=True):1506- @optimizeconst1507- def visitor(self, node, frame):1508- if self.environment.sandboxed and \1509- operator in self.environment.intercepted_binops:1510- self.write('environment.call_binop(context, %r, ' % operator)1511- self.visit(node.left, frame)1512- self.write(', ')1513- self.visit(node.right, frame)1514- else:1515- self.write('(')1516- self.visit(node.left, frame)1517- self.write(' %s ' % operator)1518- self.visit(node.right, frame)1519- self.write(')')1520- return visitor1521-1522- def uaop(operator, interceptable=True):1523- @optimizeconst1524- def visitor(self, node, frame):1525- if self.environment.sandboxed and \1526- operator in self.environment.intercepted_unops:1527- self.write('environment.call_unop(context, %r, ' % operator)1528- self.visit(node.node, frame)1529- else:1530- self.write('(' + operator)1531- self.visit(node.node, frame)1532- self.write(')')1533- return visitor1534-1535- visit_Add = binop('+')1536- visit_Sub = binop('-')1537- visit_Mul = binop('*')1538- visit_Div = binop('/')1539- visit_FloorDiv = binop('//')1540- visit_Pow = binop('**')1541- visit_Mod = binop('%')1542- visit_And = binop('and', interceptable=False)1543- visit_Or = binop('or', interceptable=False)1544- visit_Pos = uaop('+')1545- visit_Neg = uaop('-')1546- visit_Not = uaop('not ', interceptable=False)1547- del binop, uaop1548-1549- @optimizeconst1550- def visit_Concat(self, node, frame):1551- if frame.eval_ctx.volatile:1552- func_name = '(context.eval_ctx.volatile and' \1553- ' markup_join or unicode_join)'1554- elif frame.eval_ctx.autoescape:1555- func_name = 'markup_join'1556- else:1557- func_name = 'unicode_join'1558- self.write('%s((' % func_name)1559- for arg in node.nodes:1560- self.visit(arg, frame)1561- self.write(', ')1562- self.write('))')1563-1564- @optimizeconst1565- def visit_Compare(self, node, frame):1566- self.write('(')1567- self.visit(node.expr, frame)1568- for op in node.ops:1569- self.visit(op, frame)1570- self.write(')')1571-1572- def visit_Operand(self, node, frame):1573- self.write(' %s ' % operators[node.op])1574- self.visit(node.expr, frame)1575-1576- @optimizeconst1577- def visit_Getattr(self, node, frame):1578- if self.environment.is_async:1579- self.write("await auto_await(")1580-1581- self.write('environment.getattr(')1582- self.visit(node.node, frame)1583- self.write(', %r)' % node.attr)1584-1585- if self.environment.is_async:1586- self.write(")")1587-1588- @optimizeconst1589- def visit_Getitem(self, node, frame):1590- # slices bypass the environment getitem method.1591- if isinstance(node.arg, nodes.Slice):1592- self.visit(node.node, frame)1593- self.write('[')1594- self.visit(node.arg, frame)1595- self.write(']')1596- else:1597- if self.environment.is_async:1598- self.write("await auto_await(")1599-1600- self.write('environment.getitem(')1601- self.visit(node.node, frame)1602- self.write(', ')1603- self.visit(node.arg, frame)1604- self.write(')')1605-1606- if self.environment.is_async:1607- self.write(")")1608-1609- def visit_Slice(self, node, frame):1610- if node.start is not None:1611- self.visit(node.start, frame)1612- self.write(':')1613- if node.stop is not None:1614- self.visit(node.stop, frame)1615- if node.step is not None:1616- self.write(':')1617- self.visit(node.step, frame)1618-1619- @optimizeconst1620- def visit_Filter(self, node, frame):1621- if self.environment.is_async:1622- self.write('await auto_await(')1623- self.write(self.filters[node.name] + '(')1624- func = self.environment.filters.get(node.name)1625- if func is None:1626- self.fail('no filter named %r' % node.name, node.lineno)1627- if getattr(func, 'contextfilter', False):1628- self.write('context, ')1629- elif getattr(func, 'evalcontextfilter', False):1630- self.write('context.eval_ctx, ')1631- elif getattr(func, 'environmentfilter', False):1632- self.write('environment, ')1633-1634- # if the filter node is None we are inside a filter block1635- # and want to write to the current buffer1636- if node.node is not None:1637- self.visit(node.node, frame)1638- elif frame.eval_ctx.volatile:1639- self.write('(context.eval_ctx.autoescape and'1640- ' Markup(concat(%s)) or concat(%s))' %1641- (frame.buffer, frame.buffer))1642- elif frame.eval_ctx.autoescape:1643- self.write('Markup(concat(%s))' % frame.buffer)1644- else:1645- self.write('concat(%s)' % frame.buffer)1646- self.signature(node, frame)1647- self.write(')')1648- if self.environment.is_async:1649- self.write(')')1650-1651- @optimizeconst1652- def visit_Test(self, node, frame):1653- self.write(self.tests[node.name] + '(')1654- if node.name not in self.environment.tests:1655- self.fail('no test named %r' % node.name, node.lineno)1656- self.visit(node.node, frame)1657- self.signature(node, frame)1658- self.write(')')1659-1660- @optimizeconst1661- def visit_CondExpr(self, node, frame):1662- def write_expr2():1663- if node.expr2 is not None:1664- return self.visit(node.expr2, frame)1665- self.write('cond_expr_undefined(%r)' % ('the inline if-'1666- 'expression on %s evaluated to false and '1667- 'no else section was defined.' % self.position(node)))1668-1669- self.write('(')1670- self.visit(node.expr1, frame)1671- self.write(' if ')1672- self.visit(node.test, frame)1673- self.write(' else ')1674- write_expr2()1675- self.write(')')1676-1677- @optimizeconst1678- def visit_Call(self, node, frame, forward_caller=False):1679- if self.environment.is_async:1680- self.write('await auto_await(')1681- if self.environment.sandboxed:1682- self.write('environment.call(context, ')1683- else:1684- self.write('context.call(')1685- self.visit(node.node, frame)1686- extra_kwargs = forward_caller and {'caller': 'caller'} or None1687- self.signature(node, frame, extra_kwargs)1688- self.write(')')1689- if self.environment.is_async:1690- self.write(')')1691-1692- def visit_Keyword(self, node, frame):1693- self.write(node.key + '=')1694- self.visit(node.value, frame)1695-1696- # -- Unused nodes for extensions1697-1698- def visit_MarkSafe(self, node, frame):1699- self.write('Markup(')1700- self.visit(node.expr, frame)1701- self.write(')')1702-1703- def visit_MarkSafeIfAutoescape(self, node, frame):1704- self.write('(context.eval_ctx.autoescape and Markup or identity)(')1705- self.visit(node.expr, frame)1706- self.write(')')1707-1708- def visit_EnvironmentAttribute(self, node, frame):1709- self.write('environment.' + node.name)1710-1711- def visit_ExtensionAttribute(self, node, frame):1712- self.write('environment.extensions[%r].%s' % (node.identifier, node.name))1713-1714- def visit_ImportedName(self, node, frame):1715- self.write(self.import_aliases[node.importname])1716-1717- def visit_InternalName(self, node, frame):1718- self.write(node.name)1719-1720- def visit_ContextReference(self, node, frame):1721- self.write('context')1722-1723- def visit_DerivedContextReference(self, node, frame):1724- self.write(self.derive_context(frame))1725-1726- def visit_Continue(self, node, frame):1727- self.writeline('continue', node)1728-1729- def visit_Break(self, node, frame):1730- self.writeline('break', node)1731-1732- def visit_Scope(self, node, frame):1733- scope_frame = frame.inner()1734- scope_frame.symbols.analyze_node(node)1735- self.enter_frame(scope_frame)1736- self.blockvisit(node.body, scope_frame)1737- self.leave_frame(scope_frame)1738-1739- def visit_OverlayScope(self, node, frame):1740- ctx = self.temporary_identifier()1741- self.writeline('%s = %s' % (ctx, self.derive_context(frame)))1742- self.writeline('%s.vars = ' % ctx)1743- self.visit(node.context, frame)1744- self.push_context_reference(ctx)1745-1746- scope_frame = frame.inner(isolated=True)1747- scope_frame.symbols.analyze_node(node)1748- self.enter_frame(scope_frame)1749- self.blockvisit(node.body, scope_frame)1750- self.leave_frame(scope_frame)1751- self.pop_context_reference()1752-1753- def visit_EvalContextModifier(self, node, frame):1754- for keyword in node.options:1755- self.writeline('context.eval_ctx.%s = ' % keyword.key)1756- self.visit(keyword.value, frame)1757- try:1758- val = keyword.value.as_const(frame.eval_ctx)1759- except nodes.Impossible:1760- frame.eval_ctx.volatile = True1761- else:1762- setattr(frame.eval_ctx, keyword.key, val)1763-1764- def visit_ScopedEvalContextModifier(self, node, frame):1765- old_ctx_name = self.temporary_identifier()1766- saved_ctx = frame.eval_ctx.save()1767- self.writeline('%s = context.eval_ctx.save()' % old_ctx_name)1768- self.visit_EvalContextModifier(node, frame)1769- for child in node.body:1770- self.visit(child, frame)1771- frame.eval_ctx.revert(saved_ctx)1772- self.writeline('context.eval_ctx.revert(%s)' % old_ctx_name)deleted:jinja2/constants.py-32 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja.constants4- ~~~~~~~~~~~~~~~5-6- Various constants.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-12-13-#: list of lorem ipsum words used by the lipsum() helper function14-LOREM_IPSUM_WORDS = u'''\15-a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at16-auctor augue bibendum blandit class commodo condimentum congue consectetuer17-consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus18-diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend19-elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames20-faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac21-hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum22-justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem23-luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie24-mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non25-nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque26-penatibus per pharetra phasellus placerat platea porta porttitor posuere27-potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus28-ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit29-sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor30-tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices31-ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus32-viverra volutpat vulputate'''deleted:jinja2/debug.py-266 removed
1-import sys2-from types import CodeType3-4-from jinja2 import TemplateSyntaxError5-from jinja2._compat import PYPY6-from jinja2.utils import internal_code7-from jinja2.utils import missing8-9-10-def rewrite_traceback_stack(source=None):11- """Rewrite the current exception to replace any tracebacks from12- within compiled template code with tracebacks that look like they13- came from the template source.14-15- This must be called within an ``except`` block.16-17- :param exc_info: A :meth:`sys.exc_info` tuple. If not provided,18- the current ``exc_info`` is used.19- :param source: For ``TemplateSyntaxError``, the original source if20- known.21- :return: A :meth:`sys.exc_info` tuple that can be re-raised.22- """23- exc_type, exc_value, tb = sys.exc_info()24-25- if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:26- exc_value.translated = True27- exc_value.source = source28-29- try:30- # Remove the old traceback on Python 3, otherwise the frames31- # from the compiler still show up.32- exc_value.with_traceback(None)33- except AttributeError:34- pass35-36- # Outside of runtime, so the frame isn't executing template37- # code, but it still needs to point at the template.38- tb = fake_traceback(39- exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno40- )41- else:42- # Skip the frame for the render function.43- tb = tb.tb_next44-45- stack = []46-47- # Build the stack of traceback object, replacing any in template48- # code with the source file and line information.49- while tb is not None:50- # Skip frames decorated with @internalcode. These are internal51- # calls that aren't useful in template debugging output.52- if tb.tb_frame.f_code in internal_code:53- tb = tb.tb_next54- continue55-56- template = tb.tb_frame.f_globals.get("__jinja_template__")57-58- if template is not None:59- lineno = template.get_corresponding_lineno(tb.tb_lineno)60- fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)61- stack.append(fake_tb)62- else:63- stack.append(tb)64-65- tb = tb.tb_next66-67- tb_next = None68-69- # Assign tb_next in reverse to avoid circular references.70- for tb in reversed(stack):71- tb_next = tb_set_next(tb, tb_next)72-73- return exc_type, exc_value, tb_next74-75-76-def fake_traceback(exc_value, tb, filename, lineno):77- """Produce a new traceback object that looks like it came from the78- template source instead of the compiled code. The filename, line79- number, and location name will point to the template, and the local80- variables will be the current template context.81-82- :param exc_value: The original exception to be re-raised to create83- the new traceback.84- :param tb: The original traceback to get the local variables and85- code info from.86- :param filename: The template filename.87- :param lineno: The line number in the template source.88- """89- if tb is not None:90- # Replace the real locals with the context that would be91- # available at that point in the template.92- locals = get_template_locals(tb.tb_frame.f_locals)93- locals.pop("__jinja_exception__", None)94- else:95- locals = {}96-97- globals = {98- "__name__": filename,99- "__file__": filename,100- "__jinja_exception__": exc_value,101- }102- # Raise an exception at the correct line number.103- code = compile('\n' * (lineno - 1) + "raise __jinja_exception__", filename, "exec")104-105- # Build a new code object that points to the template file and106- # replaces the location with a block name.107- try:108- location = "template"109-110- if tb is not None:111- function = tb.tb_frame.f_code.co_name112-113- if function == "root":114- location = "top-level template code"115- elif function.startswith("block_"):116- location = 'block "%s"' % function[6:]117-118- # Collect arguments for the new code object. CodeType only119- # accepts positional arguments, and arguments were inserted in120- # new Python versions.121- code_args = []122-123- for attr in (124- "argcount",125- "posonlyargcount", # Python 3.8126- "kwonlyargcount", # Python 3127- "nlocals",128- "stacksize",129- "flags",130- "code", # codestring131- "consts", # constants132- "names",133- "varnames",134- ("filename", filename),135- ("name", location),136- "firstlineno",137- "lnotab",138- "freevars",139- "cellvars",140- ):141- if isinstance(attr, tuple):142- # Replace with given value.143- code_args.append(attr[1])144- continue145-146- try:147- # Copy original value if it exists.148- code_args.append(getattr(code, "co_" + attr))149- except AttributeError:150- # Some arguments were added later.151- continue152-153- code = CodeType(*code_args)154- except Exception:155- # Some environments such as Google App Engine don't support156- # modifying code objects.157- pass158-159- # Execute the new code, which is guaranteed to raise, and return160- # the new traceback without this frame.161- try:162- exec(code, globals, locals)163- except:164- return sys.exc_info()[2].tb_next165-166-167-def get_template_locals(real_locals):168- """Based on the runtime locals, get the context that would be169- available at that point in the template.170- """171- # Start with the current template context.172- ctx = real_locals.get("context")173-174- if ctx:175- data = ctx.get_all().copy()176- else:177- data = {}178-179- # Might be in a derived context that only sets local variables180- # rather than pushing a context. Local variables follow the scheme181- # l_depth_name. Find the highest-depth local that has a value for182- # each name.183- local_overrides = {}184-185- for name, value in real_locals.items():186- if not name.startswith("l_") or value is missing:187- # Not a template variable, or no longer relevant.188- continue189-190- try:191- _, depth, name = name.split("_", 2)192- depth = int(depth)193- except ValueError:194- continue195-196- cur_depth = local_overrides.get(name, (-1,))[0]197-198- if cur_depth < depth:199- local_overrides[name] = (depth, value)200-201- # Modify the context with any derived context.202- for name, (_, value) in local_overrides.items():203- if value is missing:204- data.pop(name, None)205- else:206- data[name] = value207-208- return data209-210-211-if sys.version_info >= (3, 7):212- # tb_next is directly assignable as of Python 3.7213- def tb_set_next(tb, tb_next):214- tb.tb_next = tb_next215- return tb216-elif PYPY:217- # PyPy might have special support, and won't work with ctypes.218- try:219- import tputil220- except ImportError:221- # Without tproxy support, use the original traceback.222- def tb_set_next(tb, tb_next):223- return tb224- else:225- # With tproxy support, create a proxy around the traceback that226- # returns the new tb_next.227- def tb_set_next(tb, tb_next):228- def controller(op):229- if op.opname == "__getattribute__" and op.args[0] == "tb_next":230- return tb_next231-232- return op.delegate()233-234- return tputil.make_proxy(controller, obj=tb)235-else:236- # Use ctypes to assign tb_next at the C level since it's read-only237- # from Python.238- import ctypes239-240- class _CTraceback(ctypes.Structure):241- _fields_ = [242- # Extra PyObject slots when compiled with Py_TRACE_REFS.243- (244- "PyObject_HEAD",245- ctypes.c_byte * (32 if hasattr(sys, "getobjects") else 16),246- ),247- # Only care about tb_next as an object, not a traceback.248- ("tb_next", ctypes.py_object),249- ]250-251- def tb_set_next(tb, tb_next):252- c_tb = _CTraceback.from_address(id(tb))253-254- # Clear out the old tb_next.255- if tb.tb_next is not None:256- c_tb_next = ctypes.py_object(tb.tb_next)257- c_tb.tb_next = ctypes.py_object()258- ctypes.pythonapi.Py_DecRef(c_tb_next)259-260- # Assign the new tb_next.261- if tb_next is not None:262- c_tb_next = ctypes.py_object(tb_next)263- ctypes.pythonapi.Py_IncRef(c_tb_next)264- c_tb.tb_next = c_tb_next265-266- return tbdeleted:jinja2/defaults.py-56 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.defaults4- ~~~~~~~~~~~~~~~5-6- Jinja default filters and tags.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-from jinja2._compat import range_type12-from jinja2.utils import generate_lorem_ipsum, Cycler, Joiner, Namespace13-14-15-# defaults for the parser / lexer16-BLOCK_START_STRING = '{%'17-BLOCK_END_STRING = '%}'18-VARIABLE_START_STRING = '{{'19-VARIABLE_END_STRING = '}}'20-COMMENT_START_STRING = '{#'21-COMMENT_END_STRING = '#}'22-LINE_STATEMENT_PREFIX = None23-LINE_COMMENT_PREFIX = None24-TRIM_BLOCKS = False25-LSTRIP_BLOCKS = False26-NEWLINE_SEQUENCE = '\n'27-KEEP_TRAILING_NEWLINE = False28-29-30-# default filters, tests and namespace31-from jinja2.filters import FILTERS as DEFAULT_FILTERS32-from jinja2.tests import TESTS as DEFAULT_TESTS33-DEFAULT_NAMESPACE = {34- 'range': range_type,35- 'dict': dict,36- 'lipsum': generate_lorem_ipsum,37- 'cycler': Cycler,38- 'joiner': Joiner,39- 'namespace': Namespace40-}41-42-43-# default policies44-DEFAULT_POLICIES = {45- 'compiler.ascii_str': True,46- 'urlize.rel': 'noopener',47- 'urlize.target': None,48- 'truncate.leeway': 5,49- 'json.dumps_function': None,50- 'json.dumps_kwargs': {'sort_keys': True},51- 'ext.i18n.trimmed': False,52-}53-54-55-# export all constants56-__all__ = tuple(x for x in locals().keys() if x.isupper())deleted:jinja2/environment.py-1264 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.environment4- ~~~~~~~~~~~~~~~~~~5-6- Provides a class that holds runtime and parsing time options.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import sys13-import weakref14-from functools import reduce, partial15-from jinja2 import nodes16-from jinja2.defaults import BLOCK_START_STRING, \17- BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \18- COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \19- LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \20- DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE, \21- DEFAULT_POLICIES, KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS22-from jinja2.lexer import get_lexer, TokenStream23-from jinja2.parser import Parser24-from jinja2.nodes import EvalContext25-from jinja2.compiler import generate, CodeGenerator26-from jinja2.runtime import Undefined, new_context, Context27-from jinja2.exceptions import TemplateSyntaxError, TemplateNotFound, \28- TemplatesNotFound, TemplateRuntimeError, UndefinedError29-from jinja2.utils import import_string, LRUCache, Markup, missing, \30- concat, consume, internalcode, have_async_gen31-from jinja2._compat import imap, ifilter, string_types, iteritems, \32- text_type, reraise, implements_iterator, implements_to_string, \33- encode_filename, PY2, PYPY34-35-36-# for direct template usage we have up to ten living environments37-_spontaneous_environments = LRUCache(10)38-39-40-def get_spontaneous_environment(cls, *args):41- """Return a new spontaneous environment. A spontaneous environment42- is used for templates created directly rather than through an43- existing environment.44-45- :param cls: Environment class to create.46- :param args: Positional arguments passed to environment.47- """48- key = (cls, args)49-50- try:51- return _spontaneous_environments[key]52- except KeyError:53- _spontaneous_environments[key] = env = cls(*args)54- env.shared = True55- return env56-57-58-def create_cache(size):59- """Return the cache class for the given size."""60- if size == 0:61- return None62- if size < 0:63- return {}64- return LRUCache(size)65-66-67-def copy_cache(cache):68- """Create an empty copy of the given cache."""69- if cache is None:70- return None71- elif type(cache) is dict:72- return {}73- return LRUCache(cache.capacity)74-75-76-def load_extensions(environment, extensions):77- """Load the extensions from the list and bind it to the environment.78- Returns a dict of instantiated environments.79- """80- result = {}81- for extension in extensions:82- if isinstance(extension, string_types):83- extension = import_string(extension)84- result[extension.identifier] = extension(environment)85- return result86-87-88-def fail_for_missing_callable(string, name):89- msg = string % name90- if isinstance(name, Undefined):91- try:92- name._fail_with_undefined_error()93- except Exception as e:94- msg = '%s (%s; did you forget to quote the callable name?)' % (msg, e)95- raise TemplateRuntimeError(msg)96-97-98-def _environment_sanity_check(environment):99- """Perform a sanity check on the environment."""100- assert issubclass(environment.undefined, Undefined), 'undefined must ' \101- 'be a subclass of undefined because filters depend on it.'102- assert environment.block_start_string != \103- environment.variable_start_string != \104- environment.comment_start_string, 'block, variable and comment ' \105- 'start strings must be different'106- assert environment.newline_sequence in ('\r', '\r\n', '\n'), \107- 'newline_sequence set to unknown line ending string.'108- return environment109-110-111-class Environment(object):112- r"""The core component of Jinja is the `Environment`. It contains113- important shared variables like configuration, filters, tests,114- globals and others. Instances of this class may be modified if115- they are not shared and if no template was loaded so far.116- Modifications on environments after the first template was loaded117- will lead to surprising effects and undefined behavior.118-119- Here are the possible initialization parameters:120-121- `block_start_string`122- The string marking the beginning of a block. Defaults to ``'{%'``.123-124- `block_end_string`125- The string marking the end of a block. Defaults to ``'%}'``.126-127- `variable_start_string`128- The string marking the beginning of a print statement.129- Defaults to ``'{{'``.130-131- `variable_end_string`132- The string marking the end of a print statement. Defaults to133- ``'}}'``.134-135- `comment_start_string`136- The string marking the beginning of a comment. Defaults to ``'{#'``.137-138- `comment_end_string`139- The string marking the end of a comment. Defaults to ``'#}'``.140-141- `line_statement_prefix`142- If given and a string, this will be used as prefix for line based143- statements. See also :ref:`line-statements`.144-145- `line_comment_prefix`146- If given and a string, this will be used as prefix for line based147- comments. See also :ref:`line-statements`.148-149- .. versionadded:: 2.2150-151- `trim_blocks`152- If this is set to ``True`` the first newline after a block is153- removed (block, not variable tag!). Defaults to `False`.154-155- `lstrip_blocks`156- If this is set to ``True`` leading spaces and tabs are stripped157- from the start of a line to a block. Defaults to `False`.158-159- `newline_sequence`160- The sequence that starts a newline. Must be one of ``'\r'``,161- ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a162- useful default for Linux and OS X systems as well as web163- applications.164-165- `keep_trailing_newline`166- Preserve the trailing newline when rendering templates.167- The default is ``False``, which causes a single newline,168- if present, to be stripped from the end of the template.169-170- .. versionadded:: 2.7171-172- `extensions`173- List of Jinja extensions to use. This can either be import paths174- as strings or extension classes. For more information have a175- look at :ref:`the extensions documentation <jinja-extensions>`.176-177- `optimized`178- should the optimizer be enabled? Default is ``True``.179-180- `undefined`181- :class:`Undefined` or a subclass of it that is used to represent182- undefined values in the template.183-184- `finalize`185- A callable that can be used to process the result of a variable186- expression before it is output. For example one can convert187- ``None`` implicitly into an empty string here.188-189- `autoescape`190- If set to ``True`` the XML/HTML autoescaping feature is enabled by191- default. For more details about autoescaping see192- :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also193- be a callable that is passed the template name and has to194- return ``True`` or ``False`` depending on autoescape should be195- enabled by default.196-197- .. versionchanged:: 2.4198- `autoescape` can now be a function199-200- `loader`201- The template loader for this environment.202-203- `cache_size`204- The size of the cache. Per default this is ``400`` which means205- that if more than 400 templates are loaded the loader will clean206- out the least recently used template. If the cache size is set to207- ``0`` templates are recompiled all the time, if the cache size is208- ``-1`` the cache will not be cleaned.209-210- .. versionchanged:: 2.8211- The cache size was increased to 400 from a low 50.212-213- `auto_reload`214- Some loaders load templates from locations where the template215- sources may change (ie: file system or database). If216- ``auto_reload`` is set to ``True`` (default) every time a template is217- requested the loader checks if the source changed and if yes, it218- will reload the template. For higher performance it's possible to219- disable that.220-221- `bytecode_cache`222- If set to a bytecode cache object, this object will provide a223- cache for the internal Jinja bytecode so that templates don't224- have to be parsed if they were not changed.225-226- See :ref:`bytecode-cache` for more information.227-228- `enable_async`229- If set to true this enables async template execution which allows230- you to take advantage of newer Python features. This requires231- Python 3.6 or later.232- """233-234- #: if this environment is sandboxed. Modifying this variable won't make235- #: the environment sandboxed though. For a real sandboxed environment236- #: have a look at jinja2.sandbox. This flag alone controls the code237- #: generation by the compiler.238- sandboxed = False239-240- #: True if the environment is just an overlay241- overlayed = False242-243- #: the environment this environment is linked to if it is an overlay244- linked_to = None245-246- #: shared environments have this set to `True`. A shared environment247- #: must not be modified248- shared = False249-250- #: the class that is used for code generation. See251- #: :class:`~jinja2.compiler.CodeGenerator` for more information.252- code_generator_class = CodeGenerator253-254- #: the context class thatis used for templates. See255- #: :class:`~jinja2.runtime.Context` for more information.256- context_class = Context257-258- def __init__(self,259- block_start_string=BLOCK_START_STRING,260- block_end_string=BLOCK_END_STRING,261- variable_start_string=VARIABLE_START_STRING,262- variable_end_string=VARIABLE_END_STRING,263- comment_start_string=COMMENT_START_STRING,264- comment_end_string=COMMENT_END_STRING,265- line_statement_prefix=LINE_STATEMENT_PREFIX,266- line_comment_prefix=LINE_COMMENT_PREFIX,267- trim_blocks=TRIM_BLOCKS,268- lstrip_blocks=LSTRIP_BLOCKS,269- newline_sequence=NEWLINE_SEQUENCE,270- keep_trailing_newline=KEEP_TRAILING_NEWLINE,271- extensions=(),272- optimized=True,273- undefined=Undefined,274- finalize=None,275- autoescape=False,276- loader=None,277- cache_size=400,278- auto_reload=True,279- bytecode_cache=None,280- enable_async=False):281- # !!Important notice!!282- # The constructor accepts quite a few arguments that should be283- # passed by keyword rather than position. However it's important to284- # not change the order of arguments because it's used at least285- # internally in those cases:286- # - spontaneous environments (i18n extension and Template)287- # - unittests288- # If parameter changes are required only add parameters at the end289- # and don't change the arguments (or the defaults!) of the arguments290- # existing already.291-292- # lexer / parser information293- self.block_start_string = block_start_string294- self.block_end_string = block_end_string295- self.variable_start_string = variable_start_string296- self.variable_end_string = variable_end_string297- self.comment_start_string = comment_start_string298- self.comment_end_string = comment_end_string299- self.line_statement_prefix = line_statement_prefix300- self.line_comment_prefix = line_comment_prefix301- self.trim_blocks = trim_blocks302- self.lstrip_blocks = lstrip_blocks303- self.newline_sequence = newline_sequence304- self.keep_trailing_newline = keep_trailing_newline305-306- # runtime information307- self.undefined = undefined308- self.optimized = optimized309- self.finalize = finalize310- self.autoescape = autoescape311-312- # defaults313- self.filters = DEFAULT_FILTERS.copy()314- self.tests = DEFAULT_TESTS.copy()315- self.globals = DEFAULT_NAMESPACE.copy()316-317- # set the loader provided318- self.loader = loader319- self.cache = create_cache(cache_size)320- self.bytecode_cache = bytecode_cache321- self.auto_reload = auto_reload322-323- # configurable policies324- self.policies = DEFAULT_POLICIES.copy()325-326- # load extensions327- self.extensions = load_extensions(self, extensions)328-329- self.enable_async = enable_async330- self.is_async = self.enable_async and have_async_gen331- if self.is_async:332- import jinja2.asyncsupport # runs patch_all() once333-334- _environment_sanity_check(self)335-336- def add_extension(self, extension):337- """Adds an extension after the environment was created.338-339- .. versionadded:: 2.5340- """341- self.extensions.update(load_extensions(self, [extension]))342-343- def extend(self, **attributes):344- """Add the items to the instance of the environment if they do not exist345- yet. This is used by :ref:`extensions <writing-extensions>` to register346- callbacks and configuration values without breaking inheritance.347- """348- for key, value in iteritems(attributes):349- if not hasattr(self, key):350- setattr(self, key, value)351-352- def overlay(self, block_start_string=missing, block_end_string=missing,353- variable_start_string=missing, variable_end_string=missing,354- comment_start_string=missing, comment_end_string=missing,355- line_statement_prefix=missing, line_comment_prefix=missing,356- trim_blocks=missing, lstrip_blocks=missing,357- extensions=missing, optimized=missing,358- undefined=missing, finalize=missing, autoescape=missing,359- loader=missing, cache_size=missing, auto_reload=missing,360- bytecode_cache=missing):361- """Create a new overlay environment that shares all the data with the362- current environment except for cache and the overridden attributes.363- Extensions cannot be removed for an overlayed environment. An overlayed364- environment automatically gets all the extensions of the environment it365- is linked to plus optional extra extensions.366-367- Creating overlays should happen after the initial environment was set368- up completely. Not all attributes are truly linked, some are just369- copied over so modifications on the original environment may not shine370- through.371- """372- args = dict(locals())373- del args['self'], args['cache_size'], args['extensions']374-375- rv = object.__new__(self.__class__)376- rv.__dict__.update(self.__dict__)377- rv.overlayed = True378- rv.linked_to = self379-380- for key, value in iteritems(args):381- if value is not missing:382- setattr(rv, key, value)383-384- if cache_size is not missing:385- rv.cache = create_cache(cache_size)386- else:387- rv.cache = copy_cache(self.cache)388-389- rv.extensions = {}390- for key, value in iteritems(self.extensions):391- rv.extensions[key] = value.bind(rv)392- if extensions is not missing:393- rv.extensions.update(load_extensions(rv, extensions))394-395- return _environment_sanity_check(rv)396-397- lexer = property(get_lexer, doc="The lexer for this environment.")398-399- def iter_extensions(self):400- """Iterates over the extensions by priority."""401- return iter(sorted(self.extensions.values(),402- key=lambda x: x.priority))403-404- def getitem(self, obj, argument):405- """Get an item or attribute of an object but prefer the item."""406- try:407- return obj[argument]408- except (AttributeError, TypeError, LookupError):409- if isinstance(argument, string_types):410- try:411- attr = str(argument)412- except Exception:413- pass414- else:415- try:416- return getattr(obj, attr)417- except AttributeError:418- pass419- return self.undefined(obj=obj, name=argument)420-421- def getattr(self, obj, attribute):422- """Get an item or attribute of an object but prefer the attribute.423- Unlike :meth:`getitem` the attribute *must* be a bytestring.424- """425- try:426- return getattr(obj, attribute)427- except AttributeError:428- pass429- try:430- return obj[attribute]431- except (TypeError, LookupError, AttributeError):432- return self.undefined(obj=obj, name=attribute)433-434- def call_filter(self, name, value, args=None, kwargs=None,435- context=None, eval_ctx=None):436- """Invokes a filter on a value the same way the compiler does it.437-438- Note that on Python 3 this might return a coroutine in case the439- filter is running from an environment in async mode and the filter440- supports async execution. It's your responsibility to await this441- if needed.442-443- .. versionadded:: 2.7444- """445- func = self.filters.get(name)446- if func is None:447- fail_for_missing_callable('no filter named %r', name)448- args = [value] + list(args or ())449- if getattr(func, 'contextfilter', False):450- if context is None:451- raise TemplateRuntimeError('Attempted to invoke context '452- 'filter without context')453- args.insert(0, context)454- elif getattr(func, 'evalcontextfilter', False):455- if eval_ctx is None:456- if context is not None:457- eval_ctx = context.eval_ctx458- else:459- eval_ctx = EvalContext(self)460- args.insert(0, eval_ctx)461- elif getattr(func, 'environmentfilter', False):462- args.insert(0, self)463- return func(*args, **(kwargs or {}))464-465- def call_test(self, name, value, args=None, kwargs=None):466- """Invokes a test on a value the same way the compiler does it.467-468- .. versionadded:: 2.7469- """470- func = self.tests.get(name)471- if func is None:472- fail_for_missing_callable('no test named %r', name)473- return func(value, *(args or ()), **(kwargs or {}))474-475- @internalcode476- def parse(self, source, name=None, filename=None):477- """Parse the sourcecode and return the abstract syntax tree. This478- tree of nodes is used by the compiler to convert the template into479- executable source- or bytecode. This is useful for debugging or to480- extract information from templates.481-482- If you are :ref:`developing Jinja extensions <writing-extensions>`483- this gives you a good overview of the node tree generated.484- """485- try:486- return self._parse(source, name, filename)487- except TemplateSyntaxError:488- self.handle_exception(source=source)489-490- def _parse(self, source, name, filename):491- """Internal parsing function used by `parse` and `compile`."""492- return Parser(self, source, name, encode_filename(filename)).parse()493-494- def lex(self, source, name=None, filename=None):495- """Lex the given sourcecode and return a generator that yields496- tokens as tuples in the form ``(lineno, token_type, value)``.497- This can be useful for :ref:`extension development <writing-extensions>`498- and debugging templates.499-500- This does not perform preprocessing. If you want the preprocessing501- of the extensions to be applied you have to filter source through502- the :meth:`preprocess` method.503- """504- source = text_type(source)505- try:506- return self.lexer.tokeniter(source, name, filename)507- except TemplateSyntaxError:508- self.handle_exception(source=source)509-510- def preprocess(self, source, name=None, filename=None):511- """Preprocesses the source with all extensions. This is automatically512- called for all parsing and compiling methods but *not* for :meth:`lex`513- because there you usually only want the actual source tokenized.514- """515- return reduce(lambda s, e: e.preprocess(s, name, filename),516- self.iter_extensions(), text_type(source))517-518- def _tokenize(self, source, name, filename=None, state=None):519- """Called by the parser to do the preprocessing and filtering520- for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.521- """522- source = self.preprocess(source, name, filename)523- stream = self.lexer.tokenize(source, name, filename, state)524- for ext in self.iter_extensions():525- stream = ext.filter_stream(stream)526- if not isinstance(stream, TokenStream):527- stream = TokenStream(stream, name, filename)528- return stream529-530- def _generate(self, source, name, filename, defer_init=False):531- """Internal hook that can be overridden to hook a different generate532- method in.533-534- .. versionadded:: 2.5535- """536- return generate(source, self, name, filename, defer_init=defer_init,537- optimized=self.optimized)538-539- def _compile(self, source, filename):540- """Internal hook that can be overridden to hook a different compile541- method in.542-543- .. versionadded:: 2.5544- """545- return compile(source, filename, 'exec')546-547- @internalcode548- def compile(self, source, name=None, filename=None, raw=False,549- defer_init=False):550- """Compile a node or template source code. The `name` parameter is551- the load name of the template after it was joined using552- :meth:`join_path` if necessary, not the filename on the file system.553- the `filename` parameter is the estimated filename of the template on554- the file system. If the template came from a database or memory this555- can be omitted.556-557- The return value of this method is a python code object. If the `raw`558- parameter is `True` the return value will be a string with python559- code equivalent to the bytecode returned otherwise. This method is560- mainly used internally.561-562- `defer_init` is use internally to aid the module code generator. This563- causes the generated code to be able to import without the global564- environment variable to be set.565-566- .. versionadded:: 2.4567- `defer_init` parameter added.568- """569- source_hint = None570- try:571- if isinstance(source, string_types):572- source_hint = source573- source = self._parse(source, name, filename)574- source = self._generate(source, name, filename,575- defer_init=defer_init)576- if raw:577- return source578- if filename is None:579- filename = '<template>'580- else:581- filename = encode_filename(filename)582- return self._compile(source, filename)583- except TemplateSyntaxError:584- self.handle_exception(source=source_hint)585-586- def compile_expression(self, source, undefined_to_none=True):587- """A handy helper method that returns a callable that accepts keyword588- arguments that appear as variables in the expression. If called it589- returns the result of the expression.590-591- This is useful if applications want to use the same rules as Jinja592- in template "configuration files" or similar situations.593-594- Example usage:595-596- >>> env = Environment()597- >>> expr = env.compile_expression('foo == 42')598- >>> expr(foo=23)599- False600- >>> expr(foo=42)601- True602-603- Per default the return value is converted to `None` if the604- expression returns an undefined value. This can be changed605- by setting `undefined_to_none` to `False`.606-607- >>> env.compile_expression('var')() is None608- True609- >>> env.compile_expression('var', undefined_to_none=False)()610- Undefined611-612- .. versionadded:: 2.1613- """614- parser = Parser(self, source, state='variable')615- try:616- expr = parser.parse_expression()617- if not parser.stream.eos:618- raise TemplateSyntaxError('chunk after expression',619- parser.stream.current.lineno,620- None, None)621- expr.set_environment(self)622- except TemplateSyntaxError:623- if sys.exc_info() is not None:624- self.handle_exception(source=source)625-626- body = [nodes.Assign(nodes.Name('result', 'store'), expr, lineno=1)]627- template = self.from_string(nodes.Template(body, lineno=1))628- return TemplateExpression(template, undefined_to_none)629-630- def compile_templates(self, target, extensions=None, filter_func=None,631- zip='deflated', log_function=None,632- ignore_errors=True, py_compile=False):633- """Finds all the templates the loader can find, compiles them634- and stores them in `target`. If `zip` is `None`, instead of in a635- zipfile, the templates will be stored in a directory.636- By default a deflate zip algorithm is used. To switch to637- the stored algorithm, `zip` can be set to ``'stored'``.638-639- `extensions` and `filter_func` are passed to :meth:`list_templates`.640- Each template returned will be compiled to the target folder or641- zipfile.642-643- By default template compilation errors are ignored. In case a644- log function is provided, errors are logged. If you want template645- syntax errors to abort the compilation you can set `ignore_errors`646- to `False` and you will get an exception on syntax errors.647-648- If `py_compile` is set to `True` .pyc files will be written to the649- target instead of standard .py files. This flag does not do anything650- on pypy and Python 3 where pyc files are not picked up by itself and651- don't give much benefit.652-653- .. versionadded:: 2.4654- """655- from jinja2.loaders import ModuleLoader656-657- if log_function is None:658- log_function = lambda x: None659-660- if py_compile:661- if not PY2 or PYPY:662- from warnings import warn663- warn(Warning('py_compile has no effect on pypy or Python 3'))664- py_compile = False665- else:666- import imp667- import marshal668- py_header = imp.get_magic() + \669- u'\xff\xff\xff\xff'.encode('iso-8859-15')670-671- # Python 3.3 added a source filesize to the header672- if sys.version_info >= (3, 3):673- py_header += u'\x00\x00\x00\x00'.encode('iso-8859-15')674-675- def write_file(filename, data):676- if zip:677- info = ZipInfo(filename)678- info.external_attr = 0o755 << 16679- zip_file.writestr(info, data)680- else:681- if isinstance(data, text_type):682- data = data.encode("utf8")683-684- with open(os.path.join(target, filename), "wb") as f:685- f.write(data)686-687- if zip is not None:688- from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED689- zip_file = ZipFile(target, 'w', dict(deflated=ZIP_DEFLATED,690- stored=ZIP_STORED)[zip])691- log_function('Compiling into Zip archive "%s"' % target)692- else:693- if not os.path.isdir(target):694- os.makedirs(target)695- log_function('Compiling into folder "%s"' % target)696-697- try:698- for name in self.list_templates(extensions, filter_func):699- source, filename, _ = self.loader.get_source(self, name)700- try:701- code = self.compile(source, name, filename, True, True)702- except TemplateSyntaxError as e:703- if not ignore_errors:704- raise705- log_function('Could not compile "%s": %s' % (name, e))706- continue707-708- filename = ModuleLoader.get_module_filename(name)709-710- if py_compile:711- c = self._compile(code, encode_filename(filename))712- write_file(filename + 'c', py_header +713- marshal.dumps(c))714- log_function('Byte-compiled "%s" as %s' %715- (name, filename + 'c'))716- else:717- write_file(filename, code)718- log_function('Compiled "%s" as %s' % (name, filename))719- finally:720- if zip:721- zip_file.close()722-723- log_function('Finished compiling templates')724-725- def list_templates(self, extensions=None, filter_func=None):726- """Returns a list of templates for this environment. This requires727- that the loader supports the loader's728- :meth:`~BaseLoader.list_templates` method.729-730- If there are other files in the template folder besides the731- actual templates, the returned list can be filtered. There are two732- ways: either `extensions` is set to a list of file extensions for733- templates, or a `filter_func` can be provided which is a callable that734- is passed a template name and should return `True` if it should end up735- in the result list.736-737- If the loader does not support that, a :exc:`TypeError` is raised.738-739- .. versionadded:: 2.4740- """741- x = self.loader.list_templates()742- if extensions is not None:743- if filter_func is not None:744- raise TypeError('either extensions or filter_func '745- 'can be passed, but not both')746- filter_func = lambda x: '.' in x and \747- x.rsplit('.', 1)[1] in extensions748- if filter_func is not None:749- x = list(ifilter(filter_func, x))750- return x751-752- def handle_exception(self, source=None):753- """Exception handling helper. This is used internally to either raise754- rewritten exceptions or return a rendered traceback for the template.755- """756- from jinja2.debug import rewrite_traceback_stack757- reraise(*rewrite_traceback_stack(source=source))758-759- def join_path(self, template, parent):760- """Join a template with the parent. By default all the lookups are761- relative to the loader root so this method returns the `template`762- parameter unchanged, but if the paths should be relative to the763- parent template, this function can be used to calculate the real764- template name.765-766- Subclasses may override this method and implement template path767- joining here.768- """769- return template770-771- @internalcode772- def _load_template(self, name, globals):773- if self.loader is None:774- raise TypeError('no loader for this environment specified')775- cache_key = (weakref.ref(self.loader), name)776- if self.cache is not None:777- template = self.cache.get(cache_key)778- if template is not None and (not self.auto_reload or779- template.is_up_to_date):780- return template781- template = self.loader.load(self, name, globals)782- if self.cache is not None:783- self.cache[cache_key] = template784- return template785-786- @internalcode787- def get_template(self, name, parent=None, globals=None):788- """Load a template from the loader. If a loader is configured this789- method asks the loader for the template and returns a :class:`Template`.790- If the `parent` parameter is not `None`, :meth:`join_path` is called791- to get the real template name before loading.792-793- The `globals` parameter can be used to provide template wide globals.794- These variables are available in the context at render time.795-796- If the template does not exist a :exc:`TemplateNotFound` exception is797- raised.798-799- .. versionchanged:: 2.4800- If `name` is a :class:`Template` object it is returned from the801- function unchanged.802- """803- if isinstance(name, Template):804- return name805- if parent is not None:806- name = self.join_path(name, parent)807- return self._load_template(name, self.make_globals(globals))808-809- @internalcode810- def select_template(self, names, parent=None, globals=None):811- """Works like :meth:`get_template` but tries a number of templates812- before it fails. If it cannot find any of the templates, it will813- raise a :exc:`TemplatesNotFound` exception.814-815- .. versionchanged:: 2.11816- If names is :class:`Undefined`, an :exc:`UndefinedError` is817- raised instead. If no templates were found and names818- contains :class:`Undefined`, the message is more helpful.819-820- .. versionchanged:: 2.4821- If `names` contains a :class:`Template` object it is returned822- from the function unchanged.823-824- .. versionadded:: 2.3825- """826- if isinstance(names, Undefined):827- names._fail_with_undefined_error()828-829- if not names:830- raise TemplatesNotFound(message=u'Tried to select from an empty list '831- u'of templates.')832- globals = self.make_globals(globals)833- for name in names:834- if isinstance(name, Template):835- return name836- if parent is not None:837- name = self.join_path(name, parent)838- try:839- return self._load_template(name, globals)840- except (TemplateNotFound, UndefinedError):841- pass842- raise TemplatesNotFound(names)843-844- @internalcode845- def get_or_select_template(self, template_name_or_list,846- parent=None, globals=None):847- """Does a typecheck and dispatches to :meth:`select_template`848- if an iterable of template names is given, otherwise to849- :meth:`get_template`.850-851- .. versionadded:: 2.3852- """853- if isinstance(template_name_or_list, (string_types, Undefined)):854- return self.get_template(template_name_or_list, parent, globals)855- elif isinstance(template_name_or_list, Template):856- return template_name_or_list857- return self.select_template(template_name_or_list, parent, globals)858-859- def from_string(self, source, globals=None, template_class=None):860- """Load a template from a string. This parses the source given and861- returns a :class:`Template` object.862- """863- globals = self.make_globals(globals)864- cls = template_class or self.template_class865- return cls.from_code(self, self.compile(source), globals, None)866-867- def make_globals(self, d):868- """Return a dict for the globals."""869- if not d:870- return self.globals871- return dict(self.globals, **d)872-873-874-class Template(object):875- """The central template object. This class represents a compiled template876- and is used to evaluate it.877-878- Normally the template object is generated from an :class:`Environment` but879- it also has a constructor that makes it possible to create a template880- instance directly using the constructor. It takes the same arguments as881- the environment constructor but it's not possible to specify a loader.882-883- Every template object has a few methods and members that are guaranteed884- to exist. However it's important that a template object should be885- considered immutable. Modifications on the object are not supported.886-887- Template objects created from the constructor rather than an environment888- do have an `environment` attribute that points to a temporary environment889- that is probably shared with other templates created with the constructor890- and compatible settings.891-892- >>> template = Template('Hello {{ name }}!')893- >>> template.render(name='John Doe') == u'Hello John Doe!'894- True895- >>> stream = template.stream(name='John Doe')896- >>> next(stream) == u'Hello John Doe!'897- True898- >>> next(stream)899- Traceback (most recent call last):900- ...901- StopIteration902- """903-904- #: Type of environment to create when creating a template directly905- #: rather than through an existing environment.906- environment_class = Environment907-908- def __new__(cls, source,909- block_start_string=BLOCK_START_STRING,910- block_end_string=BLOCK_END_STRING,911- variable_start_string=VARIABLE_START_STRING,912- variable_end_string=VARIABLE_END_STRING,913- comment_start_string=COMMENT_START_STRING,914- comment_end_string=COMMENT_END_STRING,915- line_statement_prefix=LINE_STATEMENT_PREFIX,916- line_comment_prefix=LINE_COMMENT_PREFIX,917- trim_blocks=TRIM_BLOCKS,918- lstrip_blocks=LSTRIP_BLOCKS,919- newline_sequence=NEWLINE_SEQUENCE,920- keep_trailing_newline=KEEP_TRAILING_NEWLINE,921- extensions=(),922- optimized=True,923- undefined=Undefined,924- finalize=None,925- autoescape=False,926- enable_async=False):927- env = get_spontaneous_environment(928- cls.environment_class,929- block_start_string, block_end_string, variable_start_string,930- variable_end_string, comment_start_string, comment_end_string,931- line_statement_prefix, line_comment_prefix, trim_blocks,932- lstrip_blocks, newline_sequence, keep_trailing_newline,933- frozenset(extensions), optimized, undefined, finalize, autoescape,934- None, 0, False, None, enable_async)935- return env.from_string(source, template_class=cls)936-937- @classmethod938- def from_code(cls, environment, code, globals, uptodate=None):939- """Creates a template object from compiled code and the globals. This940- is used by the loaders and environment to create a template object.941- """942- namespace = {943- 'environment': environment,944- '__file__': code.co_filename945- }946- exec(code, namespace)947- rv = cls._from_namespace(environment, namespace, globals)948- rv._uptodate = uptodate949- return rv950-951- @classmethod952- def from_module_dict(cls, environment, module_dict, globals):953- """Creates a template object from a module. This is used by the954- module loader to create a template object.955-956- .. versionadded:: 2.4957- """958- return cls._from_namespace(environment, module_dict, globals)959-960- @classmethod961- def _from_namespace(cls, environment, namespace, globals):962- t = object.__new__(cls)963- t.environment = environment964- t.globals = globals965- t.name = namespace['name']966- t.filename = namespace['__file__']967- t.blocks = namespace['blocks']968-969- # render function and module970- t.root_render_func = namespace['root']971- t._module = None972-973- # debug and loader helpers974- t._debug_info = namespace['debug_info']975- t._uptodate = None976-977- # store the reference978- namespace['environment'] = environment979- namespace['__jinja_template__'] = t980-981- return t982-983- def render(self, *args, **kwargs):984- """This method accepts the same arguments as the `dict` constructor:985- A dict, a dict subclass or some keyword arguments. If no arguments986- are given the context will be empty. These two calls do the same::987-988- template.render(knights='that say nih')989- template.render({'knights': 'that say nih'})990-991- This will return the rendered template as unicode string.992- """993- vars = dict(*args, **kwargs)994- try:995- return concat(self.root_render_func(self.new_context(vars)))996- except Exception:997- self.environment.handle_exception()998-999- def render_async(self, *args, **kwargs):1000- """This works similar to :meth:`render` but returns a coroutine1001- that when awaited returns the entire rendered template string. This1002- requires the async feature to be enabled.1003-1004- Example usage::1005-1006- await template.render_async(knights='that say nih; asynchronously')1007- """1008- # see asyncsupport for the actual implementation1009- raise NotImplementedError('This feature is not available for this '1010- 'version of Python')1011-1012- def stream(self, *args, **kwargs):1013- """Works exactly like :meth:`generate` but returns a1014- :class:`TemplateStream`.1015- """1016- return TemplateStream(self.generate(*args, **kwargs))1017-1018- def generate(self, *args, **kwargs):1019- """For very large templates it can be useful to not render the whole1020- template at once but evaluate each statement after another and yield1021- piece for piece. This method basically does exactly that and returns1022- a generator that yields one item after another as unicode strings.1023-1024- It accepts the same arguments as :meth:`render`.1025- """1026- vars = dict(*args, **kwargs)1027- try:1028- for event in self.root_render_func(self.new_context(vars)):1029- yield event1030- except Exception:1031- yield self.environment.handle_exception()1032-1033- def generate_async(self, *args, **kwargs):1034- """An async version of :meth:`generate`. Works very similarly but1035- returns an async iterator instead.1036- """1037- # see asyncsupport for the actual implementation1038- raise NotImplementedError('This feature is not available for this '1039- 'version of Python')1040-1041- def new_context(self, vars=None, shared=False, locals=None):1042- """Create a new :class:`Context` for this template. The vars1043- provided will be passed to the template. Per default the globals1044- are added to the context. If shared is set to `True` the data1045- is passed as is to the context without adding the globals.1046-1047- `locals` can be a dict of local variables for internal usage.1048- """1049- return new_context(self.environment, self.name, self.blocks,1050- vars, shared, self.globals, locals)1051-1052- def make_module(self, vars=None, shared=False, locals=None):1053- """This method works like the :attr:`module` attribute when called1054- without arguments but it will evaluate the template on every call1055- rather than caching it. It's also possible to provide1056- a dict which is then used as context. The arguments are the same1057- as for the :meth:`new_context` method.1058- """1059- return TemplateModule(self, self.new_context(vars, shared, locals))1060-1061- def make_module_async(self, vars=None, shared=False, locals=None):1062- """As template module creation can invoke template code for1063- asynchronous executions this method must be used instead of the1064- normal :meth:`make_module` one. Likewise the module attribute1065- becomes unavailable in async mode.1066- """1067- # see asyncsupport for the actual implementation1068- raise NotImplementedError('This feature is not available for this '1069- 'version of Python')1070-1071- @internalcode1072- def _get_default_module(self):1073- if self._module is not None:1074- return self._module1075- self._module = rv = self.make_module()1076- return rv1077-1078- @property1079- def module(self):1080- """The template as module. This is used for imports in the1081- template runtime but is also useful if one wants to access1082- exported template variables from the Python layer:1083-1084- >>> t = Template('{% macro foo() %}42{% endmacro %}23')1085- >>> str(t.module)1086- '23'1087- >>> t.module.foo() == u'42'1088- True1089-1090- This attribute is not available if async mode is enabled.1091- """1092- return self._get_default_module()1093-1094- def get_corresponding_lineno(self, lineno):1095- """Return the source line number of a line number in the1096- generated bytecode as they are not in sync.1097- """1098- for template_line, code_line in reversed(self.debug_info):1099- if code_line <= lineno:1100- return template_line1101- return 11102-1103- @property1104- def is_up_to_date(self):1105- """If this variable is `False` there is a newer version available."""1106- if self._uptodate is None:1107- return True1108- return self._uptodate()1109-1110- @property1111- def debug_info(self):1112- """The debug info mapping."""1113- if self._debug_info:1114- return [tuple(imap(int, x.split('='))) for x in1115- self._debug_info.split('&')]1116- return []1117-1118- def __repr__(self):1119- if self.name is None:1120- name = 'memory:%x' % id(self)1121- else:1122- name = repr(self.name)1123- return '<%s %s>' % (self.__class__.__name__, name)1124-1125-1126-@implements_to_string1127-class TemplateModule(object):1128- """Represents an imported template. All the exported names of the1129- template are available as attributes on this object. Additionally1130- converting it into an unicode- or bytestrings renders the contents.1131- """1132-1133- def __init__(self, template, context, body_stream=None):1134- if body_stream is None:1135- if context.environment.is_async:1136- raise RuntimeError('Async mode requires a body stream '1137- 'to be passed to a template module. Use '1138- 'the async methods of the API you are '1139- 'using.')1140- body_stream = list(template.root_render_func(context))1141- self._body_stream = body_stream1142- self.__dict__.update(context.get_exported())1143- self.__name__ = template.name1144-1145- def __html__(self):1146- return Markup(concat(self._body_stream))1147-1148- def __str__(self):1149- return concat(self._body_stream)1150-1151- def __repr__(self):1152- if self.__name__ is None:1153- name = 'memory:%x' % id(self)1154- else:1155- name = repr(self.__name__)1156- return '<%s %s>' % (self.__class__.__name__, name)1157-1158-1159-class TemplateExpression(object):1160- """The :meth:`jinja2.Environment.compile_expression` method returns an1161- instance of this object. It encapsulates the expression-like access1162- to the template with an expression it wraps.1163- """1164-1165- def __init__(self, template, undefined_to_none):1166- self._template = template1167- self._undefined_to_none = undefined_to_none1168-1169- def __call__(self, *args, **kwargs):1170- context = self._template.new_context(dict(*args, **kwargs))1171- consume(self._template.root_render_func(context))1172- rv = context.vars['result']1173- if self._undefined_to_none and isinstance(rv, Undefined):1174- rv = None1175- return rv1176-1177-1178-@implements_iterator1179-class TemplateStream(object):1180- """A template stream works pretty much like an ordinary python generator1181- but it can buffer multiple items to reduce the number of total iterations.1182- Per default the output is unbuffered which means that for every unbuffered1183- instruction in the template one unicode string is yielded.1184-1185- If buffering is enabled with a buffer size of 5, five items are combined1186- into a new unicode string. This is mainly useful if you are streaming1187- big templates to a client via WSGI which flushes after each iteration.1188- """1189-1190- def __init__(self, gen):1191- self._gen = gen1192- self.disable_buffering()1193-1194- def dump(self, fp, encoding=None, errors='strict'):1195- """Dump the complete stream into a file or file-like object.1196- Per default unicode strings are written, if you want to encode1197- before writing specify an `encoding`.1198-1199- Example usage::1200-1201- Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1202- """1203- close = False1204- if isinstance(fp, string_types):1205- if encoding is None:1206- encoding = 'utf-8'1207- fp = open(fp, 'wb')1208- close = True1209- try:1210- if encoding is not None:1211- iterable = (x.encode(encoding, errors) for x in self)1212- else:1213- iterable = self1214- if hasattr(fp, 'writelines'):1215- fp.writelines(iterable)1216- else:1217- for item in iterable:1218- fp.write(item)1219- finally:1220- if close:1221- fp.close()1222-1223- def disable_buffering(self):1224- """Disable the output buffering."""1225- self._next = partial(next, self._gen)1226- self.buffered = False1227-1228- def _buffered_generator(self, size):1229- buf = []1230- c_size = 01231- push = buf.append1232-1233- while 1:1234- try:1235- while c_size < size:1236- c = next(self._gen)1237- push(c)1238- if c:1239- c_size += 11240- except StopIteration:1241- if not c_size:1242- return1243- yield concat(buf)1244- del buf[:]1245- c_size = 01246-1247- def enable_buffering(self, size=5):1248- """Enable buffering. Buffer `size` items before yielding them."""1249- if size <= 1:1250- raise ValueError('buffer size too small')1251-1252- self.buffered = True1253- self._next = partial(next, self._buffered_generator(size))1254-1255- def __iter__(self):1256- return self1257-1258- def __next__(self):1259- return self._next()1260-1261-1262-# hook in default template class. if anyone reads this comment: ignore that1263-# it's possible to use custom templates ;-)1264-Environment.template_class = Templatedeleted:jinja2/exceptions.py-179 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.exceptions4- ~~~~~~~~~~~~~~~~~5-6- Jinja exceptions.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-from jinja2._compat import imap, text_type, PY2, implements_to_string12-13-14-class TemplateError(Exception):15- """Baseclass for all template errors."""16-17- if PY2:18- def __init__(self, message=None):19- if message is not None:20- message = text_type(message).encode('utf-8')21- Exception.__init__(self, message)22-23- @property24- def message(self):25- if self.args:26- message = self.args[0]27- if message is not None:28- return message.decode('utf-8', 'replace')29-30- def __unicode__(self):31- return self.message or u''32- else:33- def __init__(self, message=None):34- Exception.__init__(self, message)35-36- @property37- def message(self):38- if self.args:39- message = self.args[0]40- if message is not None:41- return message42-43-44-@implements_to_string45-class TemplateNotFound(IOError, LookupError, TemplateError):46- """Raised if a template does not exist.47-48- .. versionchanged:: 2.1149- If the given name is :class:`Undefined` and no message was50- provided, an :exc:`UndefinedError` is raised.51- """52-53- # looks weird, but removes the warning descriptor that just54- # bogusly warns us about message being deprecated55- message = None56-57- def __init__(self, name, message=None):58- IOError.__init__(self, name)59-60- if message is None:61- from jinja2.runtime import Undefined62-63- if isinstance(name, Undefined):64- name._fail_with_undefined_error()65-66- message = name67-68- self.message = message69- self.name = name70- self.templates = [name]71-72- def __str__(self):73- return self.message74-75-76-class TemplatesNotFound(TemplateNotFound):77- """Like :class:`TemplateNotFound` but raised if multiple templates78- are selected. This is a subclass of :class:`TemplateNotFound`79- exception, so just catching the base exception will catch both.80-81- .. versionchanged:: 2.1182- If a name in the list of names is :class:`Undefined`, a message83- about it being undefined is shown rather than the empty string.84-85- .. versionadded:: 2.286- """87-88- def __init__(self, names=(), message=None):89- if message is None:90- from jinja2.runtime import Undefined91-92- parts = []93-94- for name in names:95- if isinstance(name, Undefined):96- parts.append(name._undefined_message)97- else:98- parts.append(name)99-100- message = u'none of the templates given were found: ' + \101- u', '.join(imap(text_type, parts))102- TemplateNotFound.__init__(self, names and names[-1] or None, message)103- self.templates = list(names)104-105-106-@implements_to_string107-class TemplateSyntaxError(TemplateError):108- """Raised to tell the user that there is a problem with the template."""109-110- def __init__(self, message, lineno, name=None, filename=None):111- TemplateError.__init__(self, message)112- self.lineno = lineno113- self.name = name114- self.filename = filename115- self.source = None116-117- # this is set to True if the debug.translate_syntax_error118- # function translated the syntax error into a new traceback119- self.translated = False120-121- def __str__(self):122- # for translated errors we only return the message123- if self.translated:124- return self.message125-126- # otherwise attach some stuff127- location = 'line %d' % self.lineno128- name = self.filename or self.name129- if name:130- location = 'File "%s", %s' % (name, location)131- lines = [self.message, ' ' + location]132-133- # if the source is set, add the line to the output134- if self.source is not None:135- try:136- line = self.source.splitlines()[self.lineno - 1]137- except IndexError:138- line = None139- if line:140- lines.append(' ' + line.strip())141-142- return u'\n'.join(lines)143-144- def __reduce__(self):145- # https://bugs.python.org/issue1692335 Exceptions that take146- # multiple required arguments have problems with pickling.147- # Without this, raises TypeError: __init__() missing 1 required148- # positional argument: 'lineno'149- return self.__class__, (self.message, self.lineno, self.name, self.filename)150-151-152-class TemplateAssertionError(TemplateSyntaxError):153- """Like a template syntax error, but covers cases where something in the154- template caused an error at compile time that wasn't necessarily caused155- by a syntax error. However it's a direct subclass of156- :exc:`TemplateSyntaxError` and has the same attributes.157- """158-159-160-class TemplateRuntimeError(TemplateError):161- """A generic runtime error in the template engine. Under some situations162- Jinja may raise this exception.163- """164-165-166-class UndefinedError(TemplateRuntimeError):167- """Raised if a template tries to operate on :class:`Undefined`."""168-169-170-class SecurityError(TemplateRuntimeError):171- """Raised if a template tries to do something insecure if the172- sandbox is enabled.173- """174-175-176-class FilterArgumentError(TemplateRuntimeError):177- """This error is raised if a filter was called with inappropriate178- arguments179- """deleted:jinja2/ext.py-682 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.ext4- ~~~~~~~~~~5-6- Jinja extensions allow adding custom tags and behavior. The7- following extensions are included:8-9- - An 18n support ``{% trans %}`` tag.10- - A ``{% do %}`` tag.11- - Loop control ``{% break %}`` and ``{% continue %}`` tags.12- - A ``{% debug %}`` tag.13-14- :copyright: (c) 2017 by the Jinja Team.15- :license: BSD.16-"""17-import pprint18-import re19-from sys import version_info20-21-from jinja2 import nodes22-from jinja2.defaults import BLOCK_START_STRING, \23- BLOCK_END_STRING, VARIABLE_START_STRING, VARIABLE_END_STRING, \24- COMMENT_START_STRING, COMMENT_END_STRING, LINE_STATEMENT_PREFIX, \25- LINE_COMMENT_PREFIX, TRIM_BLOCKS, NEWLINE_SEQUENCE, \26- KEEP_TRAILING_NEWLINE, LSTRIP_BLOCKS27-from jinja2.environment import Environment28-from jinja2.nodes import ContextReference29-from jinja2.runtime import concat30-from jinja2.exceptions import TemplateAssertionError, TemplateSyntaxError31-from jinja2.utils import contextfunction, import_string, Markup32-from jinja2._compat import with_metaclass, string_types, iteritems33-from markupsafe import escape34-35-36-# the only real useful gettext functions for a Jinja template. Note37-# that ugettext must be assigned to gettext as Jinja doesn't support38-# non unicode strings.39-GETTEXT_FUNCTIONS = ('_', 'gettext', 'ngettext')40-41-42-class ExtensionRegistry(type):43- """Gives the extension an unique identifier."""44-45- def __new__(cls, name, bases, d):46- rv = type.__new__(cls, name, bases, d)47- rv.identifier = rv.__module__ + '.' + rv.__name__48- return rv49-50-51-class Extension(with_metaclass(ExtensionRegistry, object)):52- """Extensions can be used to add extra functionality to the Jinja template53- system at the parser level. Custom extensions are bound to an environment54- but may not store environment specific data on `self`. The reason for55- this is that an extension can be bound to another environment (for56- overlays) by creating a copy and reassigning the `environment` attribute.57-58- As extensions are created by the environment they cannot accept any59- arguments for configuration. One may want to work around that by using60- a factory function, but that is not possible as extensions are identified61- by their import name. The correct way to configure the extension is62- storing the configuration values on the environment. Because this way the63- environment ends up acting as central configuration storage the64- attributes may clash which is why extensions have to ensure that the names65- they choose for configuration are not too generic. ``prefix`` for example66- is a terrible name, ``fragment_cache_prefix`` on the other hand is a good67- name as includes the name of the extension (fragment cache).68- """69-70- #: if this extension parses this is the list of tags it's listening to.71- tags = set()72-73- #: the priority of that extension. This is especially useful for74- #: extensions that preprocess values. A lower value means higher75- #: priority.76- #:77- #: .. versionadded:: 2.478- priority = 10079-80- def __init__(self, environment):81- self.environment = environment82-83- def bind(self, environment):84- """Create a copy of this extension bound to another environment."""85- rv = object.__new__(self.__class__)86- rv.__dict__.update(self.__dict__)87- rv.environment = environment88- return rv89-90- def preprocess(self, source, name, filename=None):91- """This method is called before the actual lexing and can be used to92- preprocess the source. The `filename` is optional. The return value93- must be the preprocessed source.94- """95- return source96-97- def filter_stream(self, stream):98- """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used99- to filter tokens returned. This method has to return an iterable of100- :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a101- :class:`~jinja2.lexer.TokenStream`.102-103- In the `ext` folder of the Jinja source distribution there is a file104- called `inlinegettext.py` which implements a filter that utilizes this105- method.106- """107- return stream108-109- def parse(self, parser):110- """If any of the :attr:`tags` matched this method is called with the111- parser as first argument. The token the parser stream is pointing at112- is the name token that matched. This method has to return one or a113- list of multiple nodes.114- """115- raise NotImplementedError()116-117- def attr(self, name, lineno=None):118- """Return an attribute node for the current extension. This is useful119- to pass constants on extensions to generated template code.120-121- ::122-123- self.attr('_my_attribute', lineno=lineno)124- """125- return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)126-127- def call_method(self, name, args=None, kwargs=None, dyn_args=None,128- dyn_kwargs=None, lineno=None):129- """Call a method of the extension. This is a shortcut for130- :meth:`attr` + :class:`jinja2.nodes.Call`.131- """132- if args is None:133- args = []134- if kwargs is None:135- kwargs = []136- return nodes.Call(self.attr(name, lineno=lineno), args, kwargs,137- dyn_args, dyn_kwargs, lineno=lineno)138-139-140-@contextfunction141-def _gettext_alias(__context, *args, **kwargs):142- return __context.call(__context.resolve('gettext'), *args, **kwargs)143-144-145-def _make_new_gettext(func):146- @contextfunction147- def gettext(__context, __string, **variables):148- rv = __context.call(func, __string)149- if __context.eval_ctx.autoescape:150- rv = Markup(rv)151- # Always treat as a format string, even if there are no152- # variables. This makes translation strings more consistent153- # and predictable. This requires escaping154- return rv % variables155- return gettext156-157-158-def _make_new_ngettext(func):159- @contextfunction160- def ngettext(__context, __singular, __plural, __num, **variables):161- variables.setdefault('num', __num)162- rv = __context.call(func, __singular, __plural, __num)163- if __context.eval_ctx.autoescape:164- rv = Markup(rv)165- # Always treat as a format string, see gettext comment above.166- return rv % variables167- return ngettext168-169-170-class InternationalizationExtension(Extension):171- """This extension adds gettext support to Jinja."""172- tags = {'trans'}173-174- # TODO: the i18n extension is currently reevaluating values in a few175- # situations. Take this example:176- # {% trans count=something() %}{{ count }} foo{% pluralize177- # %}{{ count }} fooss{% endtrans %}178- # something is called twice here. One time for the gettext value and179- # the other time for the n-parameter of the ngettext function.180-181- def __init__(self, environment):182- Extension.__init__(self, environment)183- environment.globals['_'] = _gettext_alias184- environment.extend(185- install_gettext_translations=self._install,186- install_null_translations=self._install_null,187- install_gettext_callables=self._install_callables,188- uninstall_gettext_translations=self._uninstall,189- extract_translations=self._extract,190- newstyle_gettext=False191- )192-193- def _install(self, translations, newstyle=None):194- gettext = getattr(translations, 'ugettext', None)195- if gettext is None:196- gettext = translations.gettext197- ngettext = getattr(translations, 'ungettext', None)198- if ngettext is None:199- ngettext = translations.ngettext200- self._install_callables(gettext, ngettext, newstyle)201-202- def _install_null(self, newstyle=None):203- self._install_callables(204- lambda x: x,205- lambda s, p, n: (n != 1 and (p,) or (s,))[0],206- newstyle207- )208-209- def _install_callables(self, gettext, ngettext, newstyle=None):210- if newstyle is not None:211- self.environment.newstyle_gettext = newstyle212- if self.environment.newstyle_gettext:213- gettext = _make_new_gettext(gettext)214- ngettext = _make_new_ngettext(ngettext)215- self.environment.globals.update(216- gettext=gettext,217- ngettext=ngettext218- )219-220- def _uninstall(self, translations):221- for key in 'gettext', 'ngettext':222- self.environment.globals.pop(key, None)223-224- def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):225- if isinstance(source, string_types):226- source = self.environment.parse(source)227- return extract_from_ast(source, gettext_functions)228-229- def parse(self, parser):230- """Parse a translatable tag."""231- lineno = next(parser.stream).lineno232- num_called_num = False233-234- # find all the variables referenced. Additionally a variable can be235- # defined in the body of the trans block too, but this is checked at236- # a later state.237- plural_expr = None238- plural_expr_assignment = None239- variables = {}240- trimmed = None241- while parser.stream.current.type != 'block_end':242- if variables:243- parser.stream.expect('comma')244-245- # skip colon for python compatibility246- if parser.stream.skip_if('colon'):247- break248-249- name = parser.stream.expect('name')250- if name.value in variables:251- parser.fail('translatable variable %r defined twice.' %252- name.value, name.lineno,253- exc=TemplateAssertionError)254-255- # expressions256- if parser.stream.current.type == 'assign':257- next(parser.stream)258- variables[name.value] = var = parser.parse_expression()259- elif trimmed is None and name.value in ('trimmed', 'notrimmed'):260- trimmed = name.value == 'trimmed'261- continue262- else:263- variables[name.value] = var = nodes.Name(name.value, 'load')264-265- if plural_expr is None:266- if isinstance(var, nodes.Call):267- plural_expr = nodes.Name('_trans', 'load')268- variables[name.value] = plural_expr269- plural_expr_assignment = nodes.Assign(270- nodes.Name('_trans', 'store'), var)271- else:272- plural_expr = var273- num_called_num = name.value == 'num'274-275- parser.stream.expect('block_end')276-277- plural = None278- have_plural = False279- referenced = set()280-281- # now parse until endtrans or pluralize282- singular_names, singular = self._parse_block(parser, True)283- if singular_names:284- referenced.update(singular_names)285- if plural_expr is None:286- plural_expr = nodes.Name(singular_names[0], 'load')287- num_called_num = singular_names[0] == 'num'288-289- # if we have a pluralize block, we parse that too290- if parser.stream.current.test('name:pluralize'):291- have_plural = True292- next(parser.stream)293- if parser.stream.current.type != 'block_end':294- name = parser.stream.expect('name')295- if name.value not in variables:296- parser.fail('unknown variable %r for pluralization' %297- name.value, name.lineno,298- exc=TemplateAssertionError)299- plural_expr = variables[name.value]300- num_called_num = name.value == 'num'301- parser.stream.expect('block_end')302- plural_names, plural = self._parse_block(parser, False)303- next(parser.stream)304- referenced.update(plural_names)305- else:306- next(parser.stream)307-308- # register free names as simple name expressions309- for var in referenced:310- if var not in variables:311- variables[var] = nodes.Name(var, 'load')312-313- if not have_plural:314- plural_expr = None315- elif plural_expr is None:316- parser.fail('pluralize without variables', lineno)317-318- if trimmed is None:319- trimmed = self.environment.policies['ext.i18n.trimmed']320- if trimmed:321- singular = self._trim_whitespace(singular)322- if plural:323- plural = self._trim_whitespace(plural)324-325- node = self._make_node(singular, plural, variables, plural_expr,326- bool(referenced),327- num_called_num and have_plural)328- node.set_lineno(lineno)329- if plural_expr_assignment is not None:330- return [plural_expr_assignment, node]331- else:332- return node333-334- def _trim_whitespace(self, string, _ws_re=re.compile(r'\s*\n\s*')):335- return _ws_re.sub(' ', string.strip())336-337- def _parse_block(self, parser, allow_pluralize):338- """Parse until the next block tag with a given name."""339- referenced = []340- buf = []341- while 1:342- if parser.stream.current.type == 'data':343- buf.append(parser.stream.current.value.replace('%', '%%'))344- next(parser.stream)345- elif parser.stream.current.type == 'variable_begin':346- next(parser.stream)347- name = parser.stream.expect('name').value348- referenced.append(name)349- buf.append('%%(%s)s' % name)350- parser.stream.expect('variable_end')351- elif parser.stream.current.type == 'block_begin':352- next(parser.stream)353- if parser.stream.current.test('name:endtrans'):354- break355- elif parser.stream.current.test('name:pluralize'):356- if allow_pluralize:357- break358- parser.fail('a translatable section can have only one '359- 'pluralize section')360- parser.fail('control structures in translatable sections are '361- 'not allowed')362- elif parser.stream.eos:363- parser.fail('unclosed translation block')364- else:365- assert False, 'internal parser error'366-367- return referenced, concat(buf)368-369- def _make_node(self, singular, plural, variables, plural_expr,370- vars_referenced, num_called_num):371- """Generates a useful node from the data provided."""372- # no variables referenced? no need to escape for old style373- # gettext invocations only if there are vars.374- if not vars_referenced and not self.environment.newstyle_gettext:375- singular = singular.replace('%%', '%')376- if plural:377- plural = plural.replace('%%', '%')378-379- # singular only:380- if plural_expr is None:381- gettext = nodes.Name('gettext', 'load')382- node = nodes.Call(gettext, [nodes.Const(singular)],383- [], None, None)384-385- # singular and plural386- else:387- ngettext = nodes.Name('ngettext', 'load')388- node = nodes.Call(ngettext, [389- nodes.Const(singular),390- nodes.Const(plural),391- plural_expr392- ], [], None, None)393-394- # in case newstyle gettext is used, the method is powerful395- # enough to handle the variable expansion and autoescape396- # handling itself397- if self.environment.newstyle_gettext:398- for key, value in iteritems(variables):399- # the function adds that later anyways in case num was400- # called num, so just skip it.401- if num_called_num and key == 'num':402- continue403- node.kwargs.append(nodes.Keyword(key, value))404-405- # otherwise do that here406- else:407- # mark the return value as safe if we are in an408- # environment with autoescaping turned on409- node = nodes.MarkSafeIfAutoescape(node)410- if variables:411- node = nodes.Mod(node, nodes.Dict([412- nodes.Pair(nodes.Const(key), value)413- for key, value in variables.items()414- ]))415- return nodes.Output([node])416-417-418-class ExprStmtExtension(Extension):419- """Adds a `do` tag to Jinja that works like the print statement just420- that it doesn't print the return value.421- """422- tags = set(['do'])423-424- def parse(self, parser):425- node = nodes.ExprStmt(lineno=next(parser.stream).lineno)426- node.node = parser.parse_tuple()427- return node428-429-430-class LoopControlExtension(Extension):431- """Adds break and continue to the template engine."""432- tags = set(['break', 'continue'])433-434- def parse(self, parser):435- token = next(parser.stream)436- if token.value == 'break':437- return nodes.Break(lineno=token.lineno)438- return nodes.Continue(lineno=token.lineno)439-440-441-class WithExtension(Extension):442- pass443-444-445-class AutoEscapeExtension(Extension):446- pass447-448-449-class DebugExtension(Extension):450- """A ``{% debug %}`` tag that dumps the available variables,451- filters, and tests.452-453- .. code-block:: html+jinja454-455- <pre>{% debug %}</pre>456-457- .. code-block:: text458-459- {'context': {'cycler': <class 'jinja2.utils.Cycler'>,460- ...,461- 'namespace': <class 'jinja2.utils.Namespace'>},462- 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',463- ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],464- 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',465- ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}466-467- .. versionadded:: 2.11.0468- """469- tags = {'debug'}470-471- def parse(self, parser):472- lineno = parser.stream.expect("name:debug").lineno473- context = ContextReference()474- result = self.call_method("_render", [context], lineno=lineno)475- return nodes.Output([result], lineno=lineno)476-477- def _render(self, context):478- result = {479- "context": context.get_all(),480- "filters": sorted(self.environment.filters.keys()),481- "tests": sorted(self.environment.tests.keys()),482- }483-484- # Set the depth since the intent is to show the top few names.485- if version_info[:2] >= (3, 4):486- return pprint.pformat(result, depth=3, compact=True)487- else:488- return pprint.pformat(result, depth=3)489-490-491-def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS,492- babel_style=True):493- """Extract localizable strings from the given template node. Per494- default this function returns matches in babel style that means non string495- parameters as well as keyword arguments are returned as `None`. This496- allows Babel to figure out what you really meant if you are using497- gettext functions that allow keyword arguments for placeholder expansion.498- If you don't want that behavior set the `babel_style` parameter to `False`499- which causes only strings to be returned and parameters are always stored500- in tuples. As a consequence invalid gettext calls (calls without a single501- string parameter or string parameters after non-string parameters) are502- skipped.503-504- This example explains the behavior:505-506- >>> from jinja2 import Environment507- >>> env = Environment()508- >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')509- >>> list(extract_from_ast(node))510- [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]511- >>> list(extract_from_ast(node, babel_style=False))512- [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]513-514- For every string found this function yields a ``(lineno, function,515- message)`` tuple, where:516-517- * ``lineno`` is the number of the line on which the string was found,518- * ``function`` is the name of the ``gettext`` function used (if the519- string was extracted from embedded Python code), and520- * ``message`` is the string itself (a ``unicode`` object, or a tuple521- of ``unicode`` objects for functions with multiple string arguments).522-523- This extraction function operates on the AST and is because of that unable524- to extract any comments. For comment support you have to use the babel525- extraction interface or extract comments yourself.526- """527- for node in node.find_all(nodes.Call):528- if not isinstance(node.node, nodes.Name) or \529- node.node.name not in gettext_functions:530- continue531-532- strings = []533- for arg in node.args:534- if isinstance(arg, nodes.Const) and \535- isinstance(arg.value, string_types):536- strings.append(arg.value)537- else:538- strings.append(None)539-540- for arg in node.kwargs:541- strings.append(None)542- if node.dyn_args is not None:543- strings.append(None)544- if node.dyn_kwargs is not None:545- strings.append(None)546-547- if not babel_style:548- strings = tuple(x for x in strings if x is not None)549- if not strings:550- continue551- else:552- if len(strings) == 1:553- strings = strings[0]554- else:555- strings = tuple(strings)556- yield node.lineno, node.node.name, strings557-558-559-class _CommentFinder(object):560- """Helper class to find comments in a token stream. Can only561- find comments for gettext calls forwards. Once the comment562- from line 4 is found, a comment for line 1 will not return a563- usable value.564- """565-566- def __init__(self, tokens, comment_tags):567- self.tokens = tokens568- self.comment_tags = comment_tags569- self.offset = 0570- self.last_lineno = 0571-572- def find_backwards(self, offset):573- try:574- for _, token_type, token_value in \575- reversed(self.tokens[self.offset:offset]):576- if token_type in ('comment', 'linecomment'):577- try:578- prefix, comment = token_value.split(None, 1)579- except ValueError:580- continue581- if prefix in self.comment_tags:582- return [comment.rstrip()]583- return []584- finally:585- self.offset = offset586-587- def find_comments(self, lineno):588- if not self.comment_tags or self.last_lineno > lineno:589- return []590- for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset:]):591- if token_lineno > lineno:592- return self.find_backwards(self.offset + idx)593- return self.find_backwards(len(self.tokens))594-595-596-def babel_extract(fileobj, keywords, comment_tags, options):597- """Babel extraction method for Jinja templates.598-599- .. versionchanged:: 2.3600- Basic support for translation comments was added. If `comment_tags`601- is now set to a list of keywords for extraction, the extractor will602- try to find the best preceding comment that begins with one of the603- keywords. For best results, make sure to not have more than one604- gettext call in one line of code and the matching comment in the605- same line or the line before.606-607- .. versionchanged:: 2.5.1608- The `newstyle_gettext` flag can be set to `True` to enable newstyle609- gettext calls.610-611- .. versionchanged:: 2.7612- A `silent` option can now be provided. If set to `False` template613- syntax errors are propagated instead of being ignored.614-615- :param fileobj: the file-like object the messages should be extracted from616- :param keywords: a list of keywords (i.e. function names) that should be617- recognized as translation functions618- :param comment_tags: a list of translator tags to search for and include619- in the results.620- :param options: a dictionary of additional options (optional)621- :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.622- (comments will be empty currently)623- """624- extensions = set()625- for extension in options.get('extensions', '').split(','):626- extension = extension.strip()627- if not extension:628- continue629- extensions.add(import_string(extension))630- if InternationalizationExtension not in extensions:631- extensions.add(InternationalizationExtension)632-633- def getbool(options, key, default=False):634- return options.get(key, str(default)).lower() in \635- ('1', 'on', 'yes', 'true')636-637- silent = getbool(options, 'silent', True)638- environment = Environment(639- options.get('block_start_string', BLOCK_START_STRING),640- options.get('block_end_string', BLOCK_END_STRING),641- options.get('variable_start_string', VARIABLE_START_STRING),642- options.get('variable_end_string', VARIABLE_END_STRING),643- options.get('comment_start_string', COMMENT_START_STRING),644- options.get('comment_end_string', COMMENT_END_STRING),645- options.get('line_statement_prefix') or LINE_STATEMENT_PREFIX,646- options.get('line_comment_prefix') or LINE_COMMENT_PREFIX,647- getbool(options, 'trim_blocks', TRIM_BLOCKS),648- getbool(options, 'lstrip_blocks', LSTRIP_BLOCKS),649- NEWLINE_SEQUENCE,650- getbool(options, 'keep_trailing_newline', KEEP_TRAILING_NEWLINE),651- frozenset(extensions),652- cache_size=0,653- auto_reload=False654- )655-656- if getbool(options, 'trimmed'):657- environment.policies['ext.i18n.trimmed'] = True658- if getbool(options, 'newstyle_gettext'):659- environment.newstyle_gettext = True660-661- source = fileobj.read().decode(options.get('encoding', 'utf-8'))662- try:663- node = environment.parse(source)664- tokens = list(environment.lex(environment.preprocess(source)))665- except TemplateSyntaxError as e:666- if not silent:667- raise668- # skip templates with syntax errors669- return670-671- finder = _CommentFinder(tokens, comment_tags)672- for lineno, func, message in extract_from_ast(node, keywords):673- yield lineno, func, message, finder.find_comments(lineno)674-675-676-#: nicer import names677-i18n = InternationalizationExtension678-do = ExprStmtExtension679-loopcontrols = LoopControlExtension680-with_ = WithExtension681-autoescape = AutoEscapeExtension682-debug = DebugExtensiondeleted:jinja2/filters.py-1361 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.filters4- ~~~~~~~~~~~~~~5-6- Bundled jinja filters.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-import re12-import math13-import random14-import warnings15-16-from itertools import groupby, chain17-from collections import namedtuple18-from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode, \19- unicode_urlencode, htmlsafe_json_dumps20-from jinja2.runtime import Undefined21-from jinja2.exceptions import FilterArgumentError22-from jinja2._compat import imap, string_types, text_type, iteritems, abc23-24-25-_word_re = re.compile(r'\w+', re.UNICODE)26-_word_beginning_split_re = re.compile(r'([-\s\(\{\[\<]+)', re.UNICODE)27-28-29-def contextfilter(f):30- """Decorator for marking context dependent filters. The current31- :class:`Context` will be passed as first argument.32- """33- f.contextfilter = True34- return f35-36-37-def evalcontextfilter(f):38- """Decorator for marking eval-context dependent filters. An eval39- context object is passed as first argument. For more information40- about the eval context, see :ref:`eval-context`.41-42- .. versionadded:: 2.443- """44- f.evalcontextfilter = True45- return f46-47-48-def environmentfilter(f):49- """Decorator for marking environment dependent filters. The current50- :class:`Environment` is passed to the filter as first argument.51- """52- f.environmentfilter = True53- return f54-55-56-def ignore_case(value):57- """For use as a postprocessor for :func:`make_attrgetter`. Converts strings58- to lowercase and returns other types as-is."""59- return value.lower() if isinstance(value, string_types) else value60-61-62-def make_attrgetter(environment, attribute, postprocess=None, default=None):63- """Returns a callable that looks up the given attribute from a64- passed object with the rules of the environment. Dots are allowed65- to access attributes of attributes. Integer parts in paths are66- looked up as integers.67- """68- attribute = _prepare_attribute_parts(attribute)69-70- def attrgetter(item):71- for part in attribute:72- item = environment.getitem(item, part)73-74- if default and isinstance(item, Undefined):75- item = default76-77- if postprocess is not None:78- item = postprocess(item)79-80- return item81-82- return attrgetter83-84-85-def make_multi_attrgetter(environment, attribute, postprocess=None):86- """Returns a callable that looks up the given comma separated87- attributes from a passed object with the rules of the environment.88- Dots are allowed to access attributes of each attribute. Integer89- parts in paths are looked up as integers.90-91- The value returned by the returned callable is a list of extracted92- attribute values.93-94- Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.95- """96- attribute_parts = attribute.split(',') if isinstance(attribute, string_types) else [attribute]97- attribute = [_prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts]98-99- def attrgetter(item):100- items = [None] * len(attribute)101- for i, attribute_part in enumerate(attribute):102- item_i = item103- for part in attribute_part:104- item_i = environment.getitem(item_i, part)105-106- if postprocess is not None:107- item_i = postprocess(item_i)108-109- items[i] = item_i110- return items111-112- return attrgetter113-114-115-def _prepare_attribute_parts(attr):116- if attr is None:117- return []118- elif isinstance(attr, string_types):119- return [int(x) if x.isdigit() else x for x in attr.split('.')]120- else:121- return [attr]122-123-124-def do_forceescape(value):125- """Enforce HTML escaping. This will probably double escape variables."""126- if hasattr(value, '__html__'):127- value = value.__html__()128- return escape(text_type(value))129-130-131-def do_urlencode(value):132- """Quote data for use in a URL path or query using UTF-8.133-134- Basic wrapper around :func:`urllib.parse.quote` when given a135- string, or :func:`urllib.parse.urlencode` for a dict or iterable.136-137- :param value: Data to quote. A string will be quoted directly. A138- dict or iterable of ``(key, value)`` pairs will be joined as a139- query string.140-141- When given a string, "/" is not quoted. HTTP servers treat "/" and142- "%2F" equivalently in paths. If you need quoted slashes, use the143- ``|replace("/", "%2F")`` filter.144-145- .. versionadded:: 2.7146- """147- if isinstance(value, string_types) or not isinstance(value, abc.Iterable):148- return unicode_urlencode(value)149-150- if isinstance(value, dict):151- items = iteritems(value)152- else:153- items = iter(value)154-155- return u"&".join(156- "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))157- for k, v in items158- )159-160-161-@evalcontextfilter162-def do_replace(eval_ctx, s, old, new, count=None):163- """Return a copy of the value with all occurrences of a substring164- replaced with a new one. The first argument is the substring165- that should be replaced, the second is the replacement string.166- If the optional third argument ``count`` is given, only the first167- ``count`` occurrences are replaced:168-169- .. sourcecode:: jinja170-171- {{ "Hello World"|replace("Hello", "Goodbye") }}172- -> Goodbye World173-174- {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}175- -> d'oh, d'oh, aaargh176- """177- if count is None:178- count = -1179- if not eval_ctx.autoescape:180- return text_type(s).replace(text_type(old), text_type(new), count)181- if hasattr(old, '__html__') or hasattr(new, '__html__') and \182- not hasattr(s, '__html__'):183- s = escape(s)184- else:185- s = soft_unicode(s)186- return s.replace(soft_unicode(old), soft_unicode(new), count)187-188-189-def do_upper(s):190- """Convert a value to uppercase."""191- return soft_unicode(s).upper()192-193-194-def do_lower(s):195- """Convert a value to lowercase."""196- return soft_unicode(s).lower()197-198-199-@evalcontextfilter200-def do_xmlattr(_eval_ctx, d, autospace=True):201- """Create an SGML/XML attribute string based on the items in a dict.202- All values that are neither `none` nor `undefined` are automatically203- escaped:204-205- .. sourcecode:: html+jinja206-207- <ul{{ {'class': 'my_list', 'missing': none,208- 'id': 'list-%d'|format(variable)}|xmlattr }}>209- ...210- </ul>211-212- Results in something like this:213-214- .. sourcecode:: html215-216- <ul class="my_list" id="list-42">217- ...218- </ul>219-220- As you can see it automatically prepends a space in front of the item221- if the filter returned something unless the second parameter is false.222- """223- rv = u' '.join(224- u'%s="%s"' % (escape(key), escape(value))225- for key, value in iteritems(d)226- if value is not None and not isinstance(value, Undefined)227- )228- if autospace and rv:229- rv = u' ' + rv230- if _eval_ctx.autoescape:231- rv = Markup(rv)232- return rv233-234-235-def do_capitalize(s):236- """Capitalize a value. The first character will be uppercase, all others237- lowercase.238- """239- return soft_unicode(s).capitalize()240-241-242-def do_title(s):243- """Return a titlecased version of the value. I.e. words will start with244- uppercase letters, all remaining characters are lowercase.245- """246- return ''.join(247- [item[0].upper() + item[1:].lower()248- for item in _word_beginning_split_re.split(soft_unicode(s))249- if item])250-251-252-def do_dictsort(value, case_sensitive=False, by='key', reverse=False):253- """Sort a dict and yield (key, value) pairs. Because python dicts are254- unsorted you may want to use this function to order them by either255- key or value:256-257- .. sourcecode:: jinja258-259- {% for item in mydict|dictsort %}260- sort the dict by key, case insensitive261-262- {% for item in mydict|dictsort(reverse=true) %}263- sort the dict by key, case insensitive, reverse order264-265- {% for item in mydict|dictsort(true) %}266- sort the dict by key, case sensitive267-268- {% for item in mydict|dictsort(false, 'value') %}269- sort the dict by value, case insensitive270- """271- if by == 'key':272- pos = 0273- elif by == 'value':274- pos = 1275- else:276- raise FilterArgumentError(277- 'You can only sort by either "key" or "value"'278- )279-280- def sort_func(item):281- value = item[pos]282-283- if not case_sensitive:284- value = ignore_case(value)285-286- return value287-288- return sorted(value.items(), key=sort_func, reverse=reverse)289-290-291-@environmentfilter292-def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):293- """Sort an iterable using Python's :func:`sorted`.294-295- .. sourcecode:: jinja296-297- {% for city in cities|sort %}298- ...299- {% endfor %}300-301- :param reverse: Sort descending instead of ascending.302- :param case_sensitive: When sorting strings, sort upper and lower303- case separately.304- :param attribute: When sorting objects or dicts, an attribute or305- key to sort by. Can use dot notation like ``"address.city"``.306- Can be a list of attributes like ``"age,name"``.307-308- The sort is stable, it does not change the relative order of309- elements that compare equal. This makes it is possible to chain310- sorts on different attributes and ordering.311-312- .. sourcecode:: jinja313-314- {% for user in users|sort(attribute="name")|sort(reverse=true, attribute="age") %}315- ...316- {% endfor %}317-318- As a shortcut to chaining when the direction is the same for all319- attributes, pass a comma separate list of attributes.320-321- .. sourcecode:: jinja322-323- {% for user users|sort(attribute="age,name") %}324- ...325- {% endfor %}326-327- .. versionchanged:: 2.11.0328- The ``attribute`` parameter can be a comma separated list of329- attributes, e.g. ``"age,name"``.330-331- .. versionchanged:: 2.6332- The ``attribute`` parameter was added.333- """334- key_func = make_multi_attrgetter(335- environment, attribute,336- postprocess=ignore_case if not case_sensitive else None337- )338- return sorted(value, key=key_func, reverse=reverse)339-340-341-@environmentfilter342-def do_unique(environment, value, case_sensitive=False, attribute=None):343- """Returns a list of unique items from the given iterable.344-345- .. sourcecode:: jinja346-347- {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}348- -> ['foo', 'bar', 'foobar']349-350- The unique items are yielded in the same order as their first occurrence in351- the iterable passed to the filter.352-353- :param case_sensitive: Treat upper and lower case strings as distinct.354- :param attribute: Filter objects with unique values for this attribute.355- """356- getter = make_attrgetter(357- environment, attribute,358- postprocess=ignore_case if not case_sensitive else None359- )360- seen = set()361-362- for item in value:363- key = getter(item)364-365- if key not in seen:366- seen.add(key)367- yield item368-369-370-def _min_or_max(environment, value, func, case_sensitive, attribute):371- it = iter(value)372-373- try:374- first = next(it)375- except StopIteration:376- return environment.undefined('No aggregated item, sequence was empty.')377-378- key_func = make_attrgetter(379- environment,380- attribute,381- postprocess=ignore_case if not case_sensitive else None382- )383- return func(chain([first], it), key=key_func)384-385-386-@environmentfilter387-def do_min(environment, value, case_sensitive=False, attribute=None):388- """Return the smallest item from the sequence.389-390- .. sourcecode:: jinja391-392- {{ [1, 2, 3]|min }}393- -> 1394-395- :param case_sensitive: Treat upper and lower case strings as distinct.396- :param attribute: Get the object with the min value of this attribute.397- """398- return _min_or_max(environment, value, min, case_sensitive, attribute)399-400-401-@environmentfilter402-def do_max(environment, value, case_sensitive=False, attribute=None):403- """Return the largest item from the sequence.404-405- .. sourcecode:: jinja406-407- {{ [1, 2, 3]|max }}408- -> 3409-410- :param case_sensitive: Treat upper and lower case strings as distinct.411- :param attribute: Get the object with the max value of this attribute.412- """413- return _min_or_max(environment, value, max, case_sensitive, attribute)414-415-416-def do_default(value, default_value=u'', boolean=False):417- """If the value is undefined it will return the passed default value,418- otherwise the value of the variable:419-420- .. sourcecode:: jinja421-422- {{ my_variable|default('my_variable is not defined') }}423-424- This will output the value of ``my_variable`` if the variable was425- defined, otherwise ``'my_variable is not defined'``. If you want426- to use default with variables that evaluate to false you have to427- set the second parameter to `true`:428-429- .. sourcecode:: jinja430-431- {{ ''|default('the string was empty', true) }}432-433- .. versionchanged:: 2.11434- It's now possible to configure the :class:`~jinja2.Environment` with435- :class:`~jinja2.ChainableUndefined` to make the `default` filter work436- on nested elements and attributes that may contain undefined values437- in the chain without getting an :exc:`~jinja2.UndefinedError`.438- """439- if isinstance(value, Undefined) or (boolean and not value):440- return default_value441- return value442-443-444-@evalcontextfilter445-def do_join(eval_ctx, value, d=u'', 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-450- .. sourcecode:: jinja451-452- {{ [1, 2, 3]|join('|') }}453- -> 1|2|3454-455- {{ [1, 2, 3]|join }}456- -> 123457-458- It is also possible to join certain attributes of an object:459-460- .. sourcecode:: jinja461-462- {{ users|join(', ', attribute='username') }}463-464- .. versionadded:: 2.6465- The `attribute` parameter was added.466- """467- if attribute is not None:468- value = imap(make_attrgetter(eval_ctx.environment, attribute), value)469-470- # no automatic escaping? joining is a lot easier then471- if not eval_ctx.autoescape:472- return text_type(d).join(imap(text_type, value))473-474- # 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__'):477- value = list(value)478- do_escape = False479- for idx, item in enumerate(value):480- if hasattr(item, '__html__'):481- do_escape = True482- else:483- value[idx] = text_type(item)484- if do_escape:485- d = escape(d)486- else:487- d = text_type(d)488- return d.join(value)489-490- # no html involved, to normal joining491- return soft_unicode(d).join(imap(soft_unicode, value))492-493-494-def do_center(value, width=80):495- """Centers the value in a field of a given width."""496- return text_type(value).center(width)497-498-499-@environmentfilter500-def do_first(environment, seq):501- """Return the first item of a sequence."""502- try:503- return next(iter(seq))504- except StopIteration:505- return environment.undefined('No first item, sequence was empty.')506-507-508-@environmentfilter509-def do_last(environment, seq):510- """511- Return the last item of a sequence.512-513- Note: Does not work with generators. You may want to explicitly convert it to a list:514-515- .. sourcecode:: jinja516-517- {{ data | selectattr('name', '==', 'Jinja') | list | last }}518- """519- try:520- return next(iter(reversed(seq)))521- except StopIteration:522- return environment.undefined('No last item, sequence was empty.')523-524-525-@contextfilter526-def do_random(context, seq):527- """Return a random item from the sequence."""528- try:529- return random.choice(seq)530- except IndexError:531- return context.environment.undefined('No random item, sequence was empty.')532-533-534-def do_filesizeformat(value, binary=False):535- """Format the value like a 'human-readable' file size (i.e. 13 kB,536- 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,537- Giga, etc.), if the second parameter is set to `True` the binary538- prefixes are used (Mebi, Gibi).539- """540- bytes = float(value)541- base = binary and 1024 or 1000542- prefixes = [543- (binary and 'KiB' or 'kB'),544- (binary and 'MiB' or 'MB'),545- (binary and 'GiB' or 'GB'),546- (binary and 'TiB' or 'TB'),547- (binary and 'PiB' or 'PB'),548- (binary and 'EiB' or 'EB'),549- (binary and 'ZiB' or 'ZB'),550- (binary and 'YiB' or 'YB')551- ]552- if bytes == 1:553- return '1 Byte'554- elif bytes < base:555- return '%d Bytes' % bytes556- else:557- for i, prefix in enumerate(prefixes):558- unit = base ** (i + 2)559- if bytes < unit:560- return '%.1f %s' % ((base * bytes / unit), prefix)561- return '%.1f %s' % ((base * bytes / unit), prefix)562-563-564-def do_pprint(value, verbose=False):565- """Pretty print a variable. Useful for debugging.566-567- With Jinja 1.2 onwards you can pass it a parameter. If this parameter568- is truthy the output will be more verbose (this requires `pretty`)569- """570- return pformat(value, verbose=verbose)571-572-573-@evalcontextfilter574-def do_urlize(eval_ctx, value, trim_url_limit=None, nofollow=False,575- target=None, rel=None):576- """Converts URLs in plain text into clickable links.577-578- If you pass the filter an additional integer it will shorten the urls579- to that number. Also a third argument exists that makes the urls580- "nofollow":581-582- .. sourcecode:: jinja583-584- {{ mytext|urlize(40, true) }}585- links are shortened to 40 chars and defined with rel="nofollow"586-587- If *target* is specified, the ``target`` attribute will be added to the588- ``<a>`` tag:589-590- .. sourcecode:: jinja591-592- {{ mytext|urlize(40, target='_blank') }}593-594- .. versionchanged:: 2.8+595- The *target* parameter was added.596- """597- policies = eval_ctx.environment.policies598- rel = set((rel or '').split() or [])599- if nofollow:600- rel.add('nofollow')601- rel.update((policies['urlize.rel'] or '').split())602- if target is None:603- target = policies['urlize.target']604- rel = ' '.join(sorted(rel)) or None605- rv = urlize(value, trim_url_limit, rel=rel, target=target)606- if eval_ctx.autoescape:607- rv = Markup(rv)608- return rv609-610-611-def do_indent(612- s, width=4, first=False, blank=False, indentfirst=None613-):614- """Return a copy of the string with each line indented by 4 spaces. The615- first line and blank lines are not indented by default.616-617- :param width: Number of spaces to indent by.618- :param first: Don't skip indenting the first line.619- :param blank: Don't skip indenting empty lines.620-621- .. versionchanged:: 2.10622- Blank lines are not indented by default.623-624- Rename the ``indentfirst`` argument to ``first``.625- """626- if indentfirst is not None:627- warnings.warn(DeprecationWarning(628- 'The "indentfirst" argument is renamed to "first".'629- ), stacklevel=2)630- first = indentfirst631-632- indention = u' ' * width633- newline = u'\n'634-635- if isinstance(s, Markup):636- indention = Markup(indention)637- newline = Markup(newline)638-639- s += newline # this quirk is necessary for splitlines method640-641- if blank:642- rv = (newline + indention).join(s.splitlines())643- else:644- lines = s.splitlines()645- rv = lines.pop(0)646-647- if lines:648- rv += newline + newline.join(649- indention + line if line else line for line in lines650- )651-652- if first:653- rv = indention + rv654-655- return rv656-657-658-@environmentfilter659-def do_truncate(env, s, length=255, killwords=False, end='...', leeway=None):660- """Return a truncated copy of the string. The length is specified661- with the first parameter which defaults to ``255``. If the second662- parameter is ``true`` the filter will cut the text at length. Otherwise663- it will discard the last word. If the text was in fact664- truncated it will append an ellipsis sign (``"..."``). If you want a665- different ellipsis sign than ``"..."`` you can specify it using the666- third parameter. Strings that only exceed the length by the tolerance667- margin given in the fourth parameter will not be truncated.668-669- .. sourcecode:: jinja670-671- {{ "foo bar baz qux"|truncate(9) }}672- -> "foo..."673- {{ "foo bar baz qux"|truncate(9, True) }}674- -> "foo ba..."675- {{ "foo bar baz qux"|truncate(11) }}676- -> "foo bar baz qux"677- {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}678- -> "foo bar..."679-680- The default leeway on newer Jinja versions is 5 and was 0 before but681- can be reconfigured globally.682- """683- if leeway is None:684- leeway = env.policies['truncate.leeway']685- assert length >= len(end), 'expected length >= %s, got %s' % (len(end), length)686- assert leeway >= 0, 'expected leeway >= 0, got %s' % leeway687- if len(s) <= length + leeway:688- return s689- if killwords:690- return s[:length - len(end)] + end691- result = s[:length - len(end)].rsplit(' ', 1)[0]692- return result + end693-694-695-@environmentfilter696-def do_wordwrap(697- environment,698- s,699- width=79,700- break_long_words=True,701- wrapstring=None,702- break_on_hyphens=True,703-):704- """Wrap a string to the given width. Existing newlines are treated705- as paragraphs to be wrapped separately.706-707- :param s: Original text to wrap.708- :param width: Maximum length of wrapped lines.709- :param break_long_words: If a word is longer than ``width``, break710- it across lines.711- :param break_on_hyphens: If a word contains hyphens, it may be split712- across lines.713- :param wrapstring: String to join each wrapped line. Defaults to714- :attr:`Environment.newline_sequence`.715-716- .. versionchanged:: 2.11717- Existing newlines are treated as paragraphs wrapped separately.718-719- .. versionchanged:: 2.11720- Added the ``break_on_hyphens`` parameter.721-722- .. versionchanged:: 2.7723- Added the ``wrapstring`` parameter.724- """725-726- import textwrap727-728- if not wrapstring:729- wrapstring = environment.newline_sequence730-731- # textwrap.wrap doesn't consider existing newlines when wrapping.732- # If the string has a newline before width, wrap will still insert733- # a newline at width, resulting in a short line. Instead, split and734- # wrap each paragraph individually.735- return wrapstring.join(736- [737- wrapstring.join(738- textwrap.wrap(739- line,740- width=width,741- expand_tabs=False,742- replace_whitespace=False,743- break_long_words=break_long_words,744- break_on_hyphens=break_on_hyphens,745- )746- )747- for line in s.splitlines()748- ]749- )750-751-752-def do_wordcount(s):753- """Count the words in that string."""754- return len(_word_re.findall(s))755-756-757-def do_int(value, default=0, base=10):758- """Convert the value into an integer. If the759- conversion doesn't work it will return ``0``. You can760- override this default using the first parameter. You761- can also override the default base (10) in the second762- parameter, which handles input with prefixes such as763- 0b, 0o and 0x for bases 2, 8 and 16 respectively.764- The base is ignored for decimal numbers and non-string values.765- """766- try:767- if isinstance(value, string_types):768- return int(value, base)769- return int(value)770- except (TypeError, ValueError):771- # this quirk is necessary so that "42.23"|int gives 42.772- try:773- return int(float(value))774- except (TypeError, ValueError):775- return default776-777-778-def do_float(value, default=0.0):779- """Convert the value into a floating point number. If the780- conversion doesn't work it will return ``0.0``. You can781- override this default using the first parameter.782- """783- try:784- return float(value)785- except (TypeError, ValueError):786- return default787-788-789-def do_format(value, *args, **kwargs):790- """Apply the given values to a `printf-style`_ format string, like791- ``string % values``.792-793- .. sourcecode:: jinja794-795- {{ "%s, %s!"|format(greeting, name) }}796- Hello, World!797-798- In most cases it should be more convenient and efficient to use the799- ``%`` operator or :meth:`str.format`.800-801- .. code-block:: text802-803- {{ "%s, %s!" % (greeting, name) }}804- {{ "{}, {}!".format(greeting, name) }}805-806- .. _printf-style: https://docs.python.org/library/stdtypes.html807- #printf-style-string-formatting808- """809- if args and kwargs:810- raise FilterArgumentError('can\'t handle positional and keyword '811- 'arguments at the same time')812- return soft_unicode(value) % (kwargs or args)813-814-815-def do_trim(value, chars=None):816- """Strip leading and trailing characters, by default whitespace."""817- return soft_unicode(value).strip(chars)818-819-820-def do_striptags(value):821- """Strip SGML/XML tags and replace adjacent whitespace by one space.822- """823- if hasattr(value, '__html__'):824- value = value.__html__()825- return Markup(text_type(value)).striptags()826-827-828-def do_slice(value, slices, fill_with=None):829- """Slice an iterator and return a list of lists containing830- those items. Useful if you want to create a div containing831- three ul tags that represent columns:832-833- .. sourcecode:: html+jinja834-835- <div class="columnwrapper">836- {%- for column in items|slice(3) %}837- <ul class="column-{{ loop.index }}">838- {%- for item in column %}839- <li>{{ item }}</li>840- {%- endfor %}841- </ul>842- {%- endfor %}843- </div>844-845- If you pass it a second argument it's used to fill missing846- values on the last iteration.847- """848- seq = list(value)849- length = len(seq)850- items_per_slice = length // slices851- slices_with_extra = length % slices852- offset = 0853- for slice_number in range(slices):854- start = offset + slice_number * items_per_slice855- if slice_number < slices_with_extra:856- offset += 1857- end = offset + (slice_number + 1) * items_per_slice858- tmp = seq[start:end]859- if fill_with is not None and slice_number >= slices_with_extra:860- tmp.append(fill_with)861- yield tmp862-863-864-def do_batch(value, linecount, fill_with=None):865- """866- A filter that batches items. It works pretty much like `slice`867- just the other way round. It returns a list of lists with the868- given number of items. If you provide a second parameter this869- is used to fill up missing items. See this example:870-871- .. sourcecode:: html+jinja872-873- <table>874- {%- for row in items|batch(3, ' ') %}875- <tr>876- {%- for column in row %}877- <td>{{ column }}</td>878- {%- endfor %}879- </tr>880- {%- endfor %}881- </table>882- """883- tmp = []884- for item in value:885- if len(tmp) == linecount:886- yield tmp887- tmp = []888- tmp.append(item)889- if tmp:890- if fill_with is not None and len(tmp) < linecount:891- tmp += [fill_with] * (linecount - len(tmp))892- yield tmp893-894-895-def do_round(value, precision=0, method='common'):896- """Round the number to a given precision. The first897- parameter specifies the precision (default is ``0``), the898- second the rounding method:899-900- - ``'common'`` rounds either up or down901- - ``'ceil'`` always rounds up902- - ``'floor'`` always rounds down903-904- If you don't specify a method ``'common'`` is used.905-906- .. sourcecode:: jinja907-908- {{ 42.55|round }}909- -> 43.0910- {{ 42.55|round(1, 'floor') }}911- -> 42.5912-913- Note that even if rounded to 0 precision, a float is returned. If914- you need a real integer, pipe it through `int`:915-916- .. sourcecode:: jinja917-918- {{ 42.55|round|int }}919- -> 43920- """921- if not method in ('common', 'ceil', 'floor'):922- raise FilterArgumentError('method must be common, ceil or floor')923- if method == 'common':924- return round(value, precision)925- func = getattr(math, method)926- return func(value * (10 ** precision)) / (10 ** precision)927-928-929-# Use a regular tuple repr here. This is what we did in the past and we930-# really want to hide this custom type as much as possible. In particular931-# we do not want to accidentally expose an auto generated repr in case932-# people start to print this out in comments or something similar for933-# debugging.934-_GroupTuple = namedtuple('_GroupTuple', ['grouper', 'list'])935-_GroupTuple.__repr__ = tuple.__repr__936-_GroupTuple.__str__ = tuple.__str__937-938-939-@environmentfilter940-def do_groupby(environment, value, attribute):941- """Group a sequence of objects by an attribute using Python's942- :func:`itertools.groupby`. The attribute can use dot notation for943- nested access, like ``"address.city"``. Unlike Python's ``groupby``,944- the values are sorted first so only one group is returned for each945- unique value.946-947- For example, a list of ``User`` objects with a ``city`` attribute948- can be rendered in groups. In this example, ``grouper`` refers to949- the ``city`` value of the group.950-951- .. sourcecode:: html+jinja952-953- <ul>{% for city, items in users|groupby("city") %}954- <li>{{ city }}955- <ul>{% for user in items %}956- <li>{{ user.name }}957- {% endfor %}</ul>958- </li>959- {% endfor %}</ul>960-961- ``groupby`` yields namedtuples of ``(grouper, list)``, which962- can be used instead of the tuple unpacking above. ``grouper`` is the963- value of the attribute, and ``list`` is the items with that value.964-965- .. sourcecode:: html+jinja966-967- <ul>{% for group in users|groupby("city") %}968- <li>{{ group.grouper }}: {{ group.list|join(", ") }}969- {% endfor %}</ul>970-971- .. versionchanged:: 2.6972- The attribute supports dot notation for nested access.973- """974- expr = make_attrgetter(environment, attribute)975- return [_GroupTuple(key, list(values)) for key, values976- in groupby(sorted(value, key=expr), expr)]977-978-979-@environmentfilter980-def do_sum(environment, iterable, attribute=None, start=0):981- """Returns the sum of a sequence of numbers plus the value of parameter982- 'start' (which defaults to 0). When the sequence is empty it returns983- start.984-985- It is also possible to sum up only certain attributes:986-987- .. sourcecode:: jinja988-989- Total: {{ items|sum(attribute='price') }}990-991- .. versionchanged:: 2.6992- The `attribute` parameter was added to allow suming up over993- attributes. Also the `start` parameter was moved on to the right.994- """995- if attribute is not None:996- iterable = imap(make_attrgetter(environment, attribute), iterable)997- return sum(iterable, start)998-999-1000-def do_list(value):1001- """Convert the value into a list. If it was a string the returned list1002- will be a list of characters.1003- """1004- return list(value)1005-1006-1007-def do_mark_safe(value):1008- """Mark the value as safe which means that in an environment with automatic1009- escaping enabled this variable will not be escaped.1010- """1011- return Markup(value)1012-1013-1014-def do_mark_unsafe(value):1015- """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1016- return text_type(value)1017-1018-1019-def do_reverse(value):1020- """Reverse the object or return an iterator that iterates over it the other1021- way round.1022- """1023- if isinstance(value, string_types):1024- return value[::-1]1025- try:1026- return reversed(value)1027- except TypeError:1028- try:1029- rv = list(value)1030- rv.reverse()1031- return rv1032- except TypeError:1033- raise FilterArgumentError('argument must be iterable')1034-1035-1036-@environmentfilter1037-def do_attr(environment, obj, name):1038- """Get an attribute of an object. ``foo|attr("bar")`` works like1039- ``foo.bar`` just that always an attribute is returned and items are not1040- looked up.1041-1042- See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.1043- """1044- try:1045- name = str(name)1046- except UnicodeError:1047- pass1048- else:1049- try:1050- value = getattr(obj, name)1051- except AttributeError:1052- pass1053- else:1054- if environment.sandboxed and not \1055- environment.is_safe_attribute(obj, name, value):1056- return environment.unsafe_undefined(obj, name)1057- return value1058- return environment.undefined(obj=obj, name=name)1059-1060-1061-@contextfilter1062-def do_map(*args, **kwargs):1063- """Applies a filter on a sequence of objects or looks up an attribute.1064- This is useful when dealing with lists of objects but you are really1065- only interested in a certain value of it.1066-1067- The basic usage is mapping on an attribute. Imagine you have a list1068- of users but you are only interested in a list of usernames:1069-1070- .. sourcecode:: jinja1071-1072- Users on this page: {{ users|map(attribute='username')|join(', ') }}1073-1074- You can specify a ``default`` value to use if an object in the list1075- does not have the given attribute.1076-1077- .. sourcecode:: jinja1078-1079- {{ users|map(attribute="username", default="Anonymous")|join(", ") }}1080-1081- Alternatively you can let it invoke a filter by passing the name of the1082- filter and the arguments afterwards. A good example would be applying a1083- text conversion filter on a sequence:1084-1085- .. sourcecode:: jinja1086-1087- Users on this page: {{ titles|map('lower')|join(', ') }}1088-1089- Similar to a generator comprehension such as:1090-1091- .. code-block:: python1092-1093- (u.username for u in users)1094- (u.username or "Anonymous" for u in users)1095- (do_lower(x) for x in titles)1096-1097- .. versionchanged:: 2.11.01098- Added the ``default`` parameter.1099-1100- .. versionadded:: 2.71101- """1102- seq, func = prepare_map(args, kwargs)1103- if seq:1104- for item in seq:1105- yield func(item)1106-1107-1108-@contextfilter1109-def do_select(*args, **kwargs):1110- """Filters a sequence of objects by applying a test to each object,1111- and only selecting the objects with the test succeeding.1112-1113- If no test is specified, each object will be evaluated as a boolean.1114-1115- Example usage:1116-1117- .. sourcecode:: jinja1118-1119- {{ numbers|select("odd") }}1120- {{ numbers|select("odd") }}1121- {{ numbers|select("divisibleby", 3) }}1122- {{ numbers|select("lessthan", 42) }}1123- {{ strings|select("equalto", "mystring") }}1124-1125- Similar to a generator comprehension such as:1126-1127- .. code-block:: python1128-1129- (n for n in numbers if test_odd(n))1130- (n for n in numbers if test_divisibleby(n, 3))1131-1132- .. versionadded:: 2.71133- """1134- return select_or_reject(args, kwargs, lambda x: x, False)1135-1136-1137-@contextfilter1138-def do_reject(*args, **kwargs):1139- """Filters a sequence of objects by applying a test to each object,1140- and rejecting the objects with the test succeeding.1141-1142- If no test is specified, each object will be evaluated as a boolean.1143-1144- Example usage:1145-1146- .. sourcecode:: jinja1147-1148- {{ numbers|reject("odd") }}1149-1150- Similar to a generator comprehension such as:1151-1152- .. code-block:: python1153-1154- (n for n in numbers if not test_odd(n))1155-1156- .. versionadded:: 2.71157- """1158- return select_or_reject(args, kwargs, lambda x: not x, False)1159-1160-1161-@contextfilter1162-def do_selectattr(*args, **kwargs):1163- """Filters a sequence of objects by applying a test to the specified1164- attribute of each object, and only selecting the objects with the1165- test succeeding.1166-1167- If no test is specified, the attribute's value will be evaluated as1168- a boolean.1169-1170- Example usage:1171-1172- .. sourcecode:: jinja1173-1174- {{ users|selectattr("is_active") }}1175- {{ users|selectattr("email", "none") }}1176-1177- Similar to a generator comprehension such as:1178-1179- .. code-block:: python1180-1181- (u for user in users if user.is_active)1182- (u for user in users if test_none(user.email))1183-1184- .. versionadded:: 2.71185- """1186- return select_or_reject(args, kwargs, lambda x: x, True)1187-1188-1189-@contextfilter1190-def do_rejectattr(*args, **kwargs):1191- """Filters a sequence of objects by applying a test to the specified1192- attribute of each object, and rejecting the objects with the test1193- succeeding.1194-1195- If no test is specified, the attribute's value will be evaluated as1196- a boolean.1197-1198- .. sourcecode:: jinja1199-1200- {{ users|rejectattr("is_active") }}1201- {{ users|rejectattr("email", "none") }}1202-1203- Similar to a generator comprehension such as:1204-1205- .. code-block:: python1206-1207- (u for user in users if not user.is_active)1208- (u for user in users if not test_none(user.email))1209-1210- .. versionadded:: 2.71211- """1212- return select_or_reject(args, kwargs, lambda x: not x, True)1213-1214-1215-@evalcontextfilter1216-def do_tojson(eval_ctx, value, indent=None):1217- """Dumps a structure to JSON so that it's safe to use in ``<script>``1218- tags. It accepts the same arguments and returns a JSON string. Note that1219- this is available in templates through the ``|tojson`` filter which will1220- also mark the result as safe. Due to how this function escapes certain1221- characters this is safe even if used outside of ``<script>`` tags.1222-1223- The following characters are escaped in strings:1224-1225- - ``<``1226- - ``>``1227- - ``&``1228- - ``'``1229-1230- This makes it safe to embed such strings in any place in HTML with the1231- notable exception of double quoted attributes. In that case single1232- quote your attributes or HTML escape it in addition.1233-1234- The indent parameter can be used to enable pretty printing. Set it to1235- the number of spaces that the structures should be indented with.1236-1237- Note that this filter is for use in HTML contexts only.1238-1239- .. versionadded:: 2.91240- """1241- policies = eval_ctx.environment.policies1242- dumper = policies['json.dumps_function']1243- options = policies['json.dumps_kwargs']1244- if indent is not None:1245- options = dict(options)1246- options['indent'] = indent1247- return htmlsafe_json_dumps(value, dumper=dumper, **options)1248-1249-1250-def prepare_map(args, kwargs):1251- context = args[0]1252- seq = args[1]1253- default = None1254-1255- if len(args) == 2 and 'attribute' in kwargs:1256- attribute = kwargs.pop('attribute')1257- default = kwargs.pop('default', None)1258- if kwargs:1259- raise FilterArgumentError('Unexpected keyword argument %r' %1260- next(iter(kwargs)))1261- func = make_attrgetter(context.environment, attribute, default=default)1262- else:1263- try:1264- name = args[2]1265- args = args[3:]1266- except LookupError:1267- raise FilterArgumentError('map requires a filter argument')1268- func = lambda item: context.environment.call_filter(1269- name, item, args, kwargs, context=context)1270-1271- return seq, func1272-1273-1274-def prepare_select_or_reject(args, kwargs, modfunc, lookup_attr):1275- context = args[0]1276- seq = args[1]1277- if lookup_attr:1278- try:1279- attr = args[2]1280- except LookupError:1281- raise FilterArgumentError('Missing parameter for attribute name')1282- transfunc = make_attrgetter(context.environment, attr)1283- off = 11284- else:1285- off = 01286- transfunc = lambda x: x1287-1288- try:1289- name = args[2 + off]1290- args = args[3 + off:]1291- func = lambda item: context.environment.call_test(1292- name, item, args, kwargs)1293- except LookupError:1294- func = bool1295-1296- return seq, lambda item: modfunc(func(transfunc(item)))1297-1298-1299-def select_or_reject(args, kwargs, modfunc, lookup_attr):1300- seq, func = prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)1301- if seq:1302- for item in seq:1303- if func(item):1304- yield item1305-1306-1307-FILTERS = {1308- 'abs': abs,1309- 'attr': do_attr,1310- 'batch': do_batch,1311- 'capitalize': do_capitalize,1312- 'center': do_center,1313- 'count': len,1314- 'd': do_default,1315- 'default': do_default,1316- 'dictsort': do_dictsort,1317- 'e': escape,1318- 'escape': escape,1319- 'filesizeformat': do_filesizeformat,1320- 'first': do_first,1321- 'float': do_float,1322- 'forceescape': do_forceescape,1323- 'format': do_format,1324- 'groupby': do_groupby,1325- 'indent': do_indent,1326- 'int': do_int,1327- 'join': do_join,1328- 'last': do_last,1329- 'length': len,1330- 'list': do_list,1331- 'lower': do_lower,1332- 'map': do_map,1333- 'min': do_min,1334- 'max': do_max,1335- 'pprint': do_pprint,1336- 'random': do_random,1337- 'reject': do_reject,1338- 'rejectattr': do_rejectattr,1339- 'replace': do_replace,1340- 'reverse': do_reverse,1341- 'round': do_round,1342- 'safe': do_mark_safe,1343- 'select': do_select,1344- 'selectattr': do_selectattr,1345- 'slice': do_slice,1346- 'sort': do_sort,1347- 'string': soft_unicode,1348- 'striptags': do_striptags,1349- 'sum': do_sum,1350- 'title': do_title,1351- 'trim': do_trim,1352- 'truncate': do_truncate,1353- 'unique': do_unique,1354- 'upper': do_upper,1355- 'urlencode': do_urlencode,1356- 'urlize': do_urlize,1357- 'wordcount': do_wordcount,1358- 'wordwrap': do_wordwrap,1359- 'xmlattr': do_xmlattr,1360- 'tojson': do_tojson,1361-}deleted:jinja2/idtracking.py-286 removed
1-from jinja2.visitor import NodeVisitor2-from jinja2._compat import iteritems3-4-5-VAR_LOAD_PARAMETER = 'param'6-VAR_LOAD_RESOLVE = 'resolve'7-VAR_LOAD_ALIAS = 'alias'8-VAR_LOAD_UNDEFINED = 'undefined'9-10-11-def find_symbols(nodes, parent_symbols=None):12- sym = Symbols(parent=parent_symbols)13- visitor = FrameSymbolVisitor(sym)14- for node in nodes:15- visitor.visit(node)16- return sym17-18-19-def symbols_for_node(node, parent_symbols=None):20- sym = Symbols(parent=parent_symbols)21- sym.analyze_node(node)22- return sym23-24-25-class Symbols(object):26-27- def __init__(self, parent=None, level=None):28- if level is None:29- if parent is None:30- level = 031- else:32- level = parent.level + 133- self.level = level34- self.parent = parent35- self.refs = {}36- self.loads = {}37- self.stores = set()38-39- def analyze_node(self, node, **kwargs):40- visitor = RootVisitor(self)41- visitor.visit(node, **kwargs)42-43- def _define_ref(self, name, load=None):44- ident = 'l_%d_%s' % (self.level, name)45- self.refs[name] = ident46- if load is not None:47- self.loads[ident] = load48- return ident49-50- def find_load(self, target):51- if target in self.loads:52- return self.loads[target]53- if self.parent is not None:54- return self.parent.find_load(target)55-56- def find_ref(self, name):57- if name in self.refs:58- return self.refs[name]59- if self.parent is not None:60- return self.parent.find_ref(name)61-62- def ref(self, name):63- rv = self.find_ref(name)64- if rv is None:65- raise AssertionError('Tried to resolve a name to a reference that '66- 'was unknown to the frame (%r)' % name)67- return rv68-69- def copy(self):70- rv = object.__new__(self.__class__)71- rv.__dict__.update(self.__dict__)72- rv.refs = self.refs.copy()73- rv.loads = self.loads.copy()74- rv.stores = self.stores.copy()75- return rv76-77- def store(self, name):78- self.stores.add(name)79-80- # If we have not see the name referenced yet, we need to figure81- # out what to set it to.82- if name not in self.refs:83- # If there is a parent scope we check if the name has a84- # reference there. If it does it means we might have to alias85- # to a variable there.86- if self.parent is not None:87- outer_ref = self.parent.find_ref(name)88- if outer_ref is not None:89- self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref))90- return91-92- # Otherwise we can just set it to undefined.93- self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))94-95- def declare_parameter(self, name):96- self.stores.add(name)97- return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))98-99- def load(self, name):100- target = self.find_ref(name)101- if target is None:102- self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))103-104- def branch_update(self, branch_symbols):105- stores = {}106- for branch in branch_symbols:107- for target in branch.stores:108- if target in self.stores:109- continue110- stores[target] = stores.get(target, 0) + 1111-112- for sym in branch_symbols:113- self.refs.update(sym.refs)114- self.loads.update(sym.loads)115- self.stores.update(sym.stores)116-117- for name, branch_count in iteritems(stores):118- if branch_count == len(branch_symbols):119- continue120- target = self.find_ref(name)121- assert target is not None, 'should not happen'122-123- if self.parent is not None:124- outer_target = self.parent.find_ref(name)125- if outer_target is not None:126- self.loads[target] = (VAR_LOAD_ALIAS, outer_target)127- continue128- self.loads[target] = (VAR_LOAD_RESOLVE, name)129-130- def dump_stores(self):131- rv = {}132- node = self133- while node is not None:134- for name in node.stores:135- if name not in rv:136- rv[name] = self.find_ref(name)137- node = node.parent138- return rv139-140- def dump_param_targets(self):141- rv = set()142- node = self143- while node is not None:144- for target, (instr, _) in iteritems(self.loads):145- if instr == VAR_LOAD_PARAMETER:146- rv.add(target)147- node = node.parent148- return rv149-150-151-class RootVisitor(NodeVisitor):152-153- def __init__(self, symbols):154- self.sym_visitor = FrameSymbolVisitor(symbols)155-156- def _simple_visit(self, node, **kwargs):157- for child in node.iter_child_nodes():158- self.sym_visitor.visit(child)159-160- visit_Template = visit_Block = visit_Macro = visit_FilterBlock = \161- visit_Scope = visit_If = visit_ScopedEvalContextModifier = \162- _simple_visit163-164- def visit_AssignBlock(self, node, **kwargs):165- for child in node.body:166- self.sym_visitor.visit(child)167-168- def visit_CallBlock(self, node, **kwargs):169- for child in node.iter_child_nodes(exclude=('call',)):170- self.sym_visitor.visit(child)171-172- def visit_OverlayScope(self, node, **kwargs):173- for child in node.body:174- self.sym_visitor.visit(child)175-176- def visit_For(self, node, for_branch='body', **kwargs):177- if for_branch == 'body':178- self.sym_visitor.visit(node.target, store_as_param=True)179- branch = node.body180- elif for_branch == 'else':181- branch = node.else_182- elif for_branch == 'test':183- self.sym_visitor.visit(node.target, store_as_param=True)184- if node.test is not None:185- self.sym_visitor.visit(node.test)186- return187- else:188- raise RuntimeError('Unknown for branch')189- for item in branch or ():190- self.sym_visitor.visit(item)191-192- def visit_With(self, node, **kwargs):193- for target in node.targets:194- self.sym_visitor.visit(target)195- for child in node.body:196- self.sym_visitor.visit(child)197-198- def generic_visit(self, node, *args, **kwargs):199- raise NotImplementedError('Cannot find symbols for %r' %200- node.__class__.__name__)201-202-203-class FrameSymbolVisitor(NodeVisitor):204- """A visitor for `Frame.inspect`."""205-206- def __init__(self, symbols):207- self.symbols = symbols208-209- def visit_Name(self, node, store_as_param=False, **kwargs):210- """All assignments to names go through this function."""211- if store_as_param or node.ctx == 'param':212- self.symbols.declare_parameter(node.name)213- elif node.ctx == 'store':214- self.symbols.store(node.name)215- elif node.ctx == 'load':216- self.symbols.load(node.name)217-218- def visit_NSRef(self, node, **kwargs):219- self.symbols.load(node.name)220-221- def visit_If(self, node, **kwargs):222- self.visit(node.test, **kwargs)223-224- original_symbols = self.symbols225-226- def inner_visit(nodes):227- self.symbols = rv = original_symbols.copy()228- for subnode in nodes:229- self.visit(subnode, **kwargs)230- self.symbols = original_symbols231- return rv232-233- body_symbols = inner_visit(node.body)234- elif_symbols = inner_visit(node.elif_)235- else_symbols = inner_visit(node.else_ or ())236-237- self.symbols.branch_update([body_symbols, elif_symbols, else_symbols])238-239- def visit_Macro(self, node, **kwargs):240- self.symbols.store(node.name)241-242- def visit_Import(self, node, **kwargs):243- self.generic_visit(node, **kwargs)244- self.symbols.store(node.target)245-246- def visit_FromImport(self, node, **kwargs):247- self.generic_visit(node, **kwargs)248- for name in node.names:249- if isinstance(name, tuple):250- self.symbols.store(name[1])251- else:252- self.symbols.store(name)253-254- def visit_Assign(self, node, **kwargs):255- """Visit assignments in the correct order."""256- self.visit(node.node, **kwargs)257- self.visit(node.target, **kwargs)258-259- def visit_For(self, node, **kwargs):260- """Visiting stops at for blocks. However the block sequence261- is visited as part of the outer scope.262- """263- self.visit(node.iter, **kwargs)264-265- def visit_CallBlock(self, node, **kwargs):266- self.visit(node.call, **kwargs)267-268- def visit_FilterBlock(self, node, **kwargs):269- self.visit(node.filter, **kwargs)270-271- def visit_With(self, node, **kwargs):272- for target in node.values:273- self.visit(target)274-275- def visit_AssignBlock(self, node, **kwargs):276- """Stop visiting at block assigns."""277- self.visit(node.target, **kwargs)278-279- def visit_Scope(self, node, **kwargs):280- """Stop visiting at scopes."""281-282- def visit_Block(self, node, **kwargs):283- """Stop visiting at blocks."""284-285- def visit_OverlayScope(self, node, **kwargs):286- """Do not visit into overlay scopes."""deleted:jinja2/lexer.py-766 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.lexer4- ~~~~~~~~~~~~5-6- This module implements a Jinja / Python combination lexer. The7- `Lexer` class provided by this module is used to do some preprocessing8- for Jinja.9-10- On the one hand it filters out invalid operators like the bitshift11- operators we don't allow in templates. On the other hand it separates12- template code and python code in expressions.13-14- :copyright: (c) 2017 by the Jinja Team.15- :license: BSD, see LICENSE for more details.16-"""17-import re18-from ast import literal_eval19-from collections import deque20-from operator import itemgetter21-22-from jinja2._compat import implements_iterator, intern, iteritems, text_type23-from jinja2.exceptions import TemplateSyntaxError24-from jinja2.utils import LRUCache25-26-# cache for the lexers. Exists in order to be able to have multiple27-# environments with the same lexer28-_lexer_cache = LRUCache(50)29-30-# static regular expressions31-whitespace_re = re.compile(r'\s+', re.U)32-newline_re = re.compile(r'(\r\n|\r|\n)')33-string_re = re.compile(r"('([^'\\]*(?:\\.[^'\\]*)*)'"34- r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S)35-integer_re = re.compile(r'(\d+_)*\d+')36-float_re = re.compile(37- r"""38- (?<!\.) # doesn't start with a .39- (\d+_)*\d+ # digits, possibly _ separated40- (41- (\.(\d+_)*\d+)? # optional fractional part42- e[+\-]?(\d+_)*\d+ # exponent part43- |44- \.(\d+_)*\d+ # required fractional part45- )46- """,47- re.IGNORECASE | re.VERBOSE,48-)49-50-try:51- # check if this Python supports Unicode identifiers52- compile('föö', '<unknown>', 'eval')53-except SyntaxError:54- # no Unicode support, use ASCII identifiers55- name_re = re.compile(r'[a-zA-Z_][a-zA-Z0-9_]*')56- check_ident = False57-else:58- # Unicode support, build a pattern to match valid characters, and set flag59- # to use str.isidentifier to validate during lexing60- from jinja2 import _identifier61- name_re = re.compile(r'[\w{0}]+'.format(_identifier.pattern))62- check_ident = True63- # remove the pattern from memory after building the regex64- import sys65- del sys.modules['jinja2._identifier']66- import jinja267- del jinja2._identifier68- del _identifier69-70-# internal the tokens and keep references to them71-TOKEN_ADD = intern('add')72-TOKEN_ASSIGN = intern('assign')73-TOKEN_COLON = intern('colon')74-TOKEN_COMMA = intern('comma')75-TOKEN_DIV = intern('div')76-TOKEN_DOT = intern('dot')77-TOKEN_EQ = intern('eq')78-TOKEN_FLOORDIV = intern('floordiv')79-TOKEN_GT = intern('gt')80-TOKEN_GTEQ = intern('gteq')81-TOKEN_LBRACE = intern('lbrace')82-TOKEN_LBRACKET = intern('lbracket')83-TOKEN_LPAREN = intern('lparen')84-TOKEN_LT = intern('lt')85-TOKEN_LTEQ = intern('lteq')86-TOKEN_MOD = intern('mod')87-TOKEN_MUL = intern('mul')88-TOKEN_NE = intern('ne')89-TOKEN_PIPE = intern('pipe')90-TOKEN_POW = intern('pow')91-TOKEN_RBRACE = intern('rbrace')92-TOKEN_RBRACKET = intern('rbracket')93-TOKEN_RPAREN = intern('rparen')94-TOKEN_SEMICOLON = intern('semicolon')95-TOKEN_SUB = intern('sub')96-TOKEN_TILDE = intern('tilde')97-TOKEN_WHITESPACE = intern('whitespace')98-TOKEN_FLOAT = intern('float')99-TOKEN_INTEGER = intern('integer')100-TOKEN_NAME = intern('name')101-TOKEN_STRING = intern('string')102-TOKEN_OPERATOR = intern('operator')103-TOKEN_BLOCK_BEGIN = intern('block_begin')104-TOKEN_BLOCK_END = intern('block_end')105-TOKEN_VARIABLE_BEGIN = intern('variable_begin')106-TOKEN_VARIABLE_END = intern('variable_end')107-TOKEN_RAW_BEGIN = intern('raw_begin')108-TOKEN_RAW_END = intern('raw_end')109-TOKEN_COMMENT_BEGIN = intern('comment_begin')110-TOKEN_COMMENT_END = intern('comment_end')111-TOKEN_COMMENT = intern('comment')112-TOKEN_LINESTATEMENT_BEGIN = intern('linestatement_begin')113-TOKEN_LINESTATEMENT_END = intern('linestatement_end')114-TOKEN_LINECOMMENT_BEGIN = intern('linecomment_begin')115-TOKEN_LINECOMMENT_END = intern('linecomment_end')116-TOKEN_LINECOMMENT = intern('linecomment')117-TOKEN_DATA = intern('data')118-TOKEN_INITIAL = intern('initial')119-TOKEN_EOF = intern('eof')120-121-# bind operators to token types122-operators = {123- '+': TOKEN_ADD,124- '-': TOKEN_SUB,125- '/': TOKEN_DIV,126- '//': TOKEN_FLOORDIV,127- '*': TOKEN_MUL,128- '%': TOKEN_MOD,129- '**': TOKEN_POW,130- '~': TOKEN_TILDE,131- '[': TOKEN_LBRACKET,132- ']': TOKEN_RBRACKET,133- '(': TOKEN_LPAREN,134- ')': TOKEN_RPAREN,135- '{': TOKEN_LBRACE,136- '}': TOKEN_RBRACE,137- '==': TOKEN_EQ,138- '!=': TOKEN_NE,139- '>': TOKEN_GT,140- '>=': TOKEN_GTEQ,141- '<': TOKEN_LT,142- '<=': TOKEN_LTEQ,143- '=': TOKEN_ASSIGN,144- '.': TOKEN_DOT,145- ':': TOKEN_COLON,146- '|': TOKEN_PIPE,147- ',': TOKEN_COMMA,148- ';': TOKEN_SEMICOLON149-}150-151-reverse_operators = dict([(v, k) for k, v in iteritems(operators)])152-assert len(operators) == len(reverse_operators), 'operators dropped'153-operator_re = re.compile('(%s)' % '|'.join(re.escape(x) for x in154- sorted(operators, key=lambda x: -len(x))))155-156-ignored_tokens = frozenset([TOKEN_COMMENT_BEGIN, TOKEN_COMMENT,157- TOKEN_COMMENT_END, TOKEN_WHITESPACE,158- TOKEN_LINECOMMENT_BEGIN, TOKEN_LINECOMMENT_END,159- TOKEN_LINECOMMENT])160-ignore_if_empty = frozenset([TOKEN_WHITESPACE, TOKEN_DATA,161- TOKEN_COMMENT, TOKEN_LINECOMMENT])162-163-164-def _describe_token_type(token_type):165- if token_type in reverse_operators:166- return reverse_operators[token_type]167- return {168- TOKEN_COMMENT_BEGIN: 'begin of comment',169- TOKEN_COMMENT_END: 'end of comment',170- TOKEN_COMMENT: 'comment',171- TOKEN_LINECOMMENT: 'comment',172- TOKEN_BLOCK_BEGIN: 'begin of statement block',173- TOKEN_BLOCK_END: 'end of statement block',174- TOKEN_VARIABLE_BEGIN: 'begin of print statement',175- TOKEN_VARIABLE_END: 'end of print statement',176- TOKEN_LINESTATEMENT_BEGIN: 'begin of line statement',177- TOKEN_LINESTATEMENT_END: 'end of line statement',178- TOKEN_DATA: 'template data / text',179- TOKEN_EOF: 'end of template'180- }.get(token_type, token_type)181-182-183-def describe_token(token):184- """Returns a description of the token."""185- if token.type == TOKEN_NAME:186- return token.value187- return _describe_token_type(token.type)188-189-190-def describe_token_expr(expr):191- """Like `describe_token` but for token expressions."""192- if ':' in expr:193- type, value = expr.split(':', 1)194- if type == TOKEN_NAME:195- return value196- else:197- type = expr198- return _describe_token_type(type)199-200-201-def count_newlines(value):202- """Count the number of newline characters in the string. This is203- useful for extensions that filter a stream.204- """205- return len(newline_re.findall(value))206-207-208-def compile_rules(environment):209- """Compiles all the rules from the environment into a list of rules."""210- e = re.escape211- rules = [212- (len(environment.comment_start_string), TOKEN_COMMENT_BEGIN,213- e(environment.comment_start_string)),214- (len(environment.block_start_string), TOKEN_BLOCK_BEGIN,215- e(environment.block_start_string)),216- (len(environment.variable_start_string), TOKEN_VARIABLE_BEGIN,217- e(environment.variable_start_string))218- ]219-220- if environment.line_statement_prefix is not None:221- rules.append((len(environment.line_statement_prefix), TOKEN_LINESTATEMENT_BEGIN,222- r'^[ \t\v]*' + e(environment.line_statement_prefix)))223- if environment.line_comment_prefix is not None:224- rules.append((len(environment.line_comment_prefix), TOKEN_LINECOMMENT_BEGIN,225- r'(?:^|(?<=\S))[^\S\r\n]*' +226- e(environment.line_comment_prefix)))227-228- return [x[1:] for x in sorted(rules, reverse=True)]229-230-231-class Failure(object):232- """Class that raises a `TemplateSyntaxError` if called.233- Used by the `Lexer` to specify known errors.234- """235-236- def __init__(self, message, cls=TemplateSyntaxError):237- self.message = message238- self.error_class = cls239-240- def __call__(self, lineno, filename):241- raise self.error_class(self.message, lineno, filename)242-243-244-class Token(tuple):245- """Token class."""246- __slots__ = ()247- lineno, type, value = (property(itemgetter(x)) for x in range(3))248-249- def __new__(cls, lineno, type, value):250- return tuple.__new__(cls, (lineno, intern(str(type)), value))251-252- def __str__(self):253- if self.type in reverse_operators:254- return reverse_operators[self.type]255- elif self.type == 'name':256- return self.value257- return self.type258-259- def test(self, expr):260- """Test a token against a token expression. This can either be a261- token type or ``'token_type:token_value'``. This can only test262- against string values and types.263- """264- # here we do a regular string equality check as test_any is usually265- # passed an iterable of not interned strings.266- if self.type == expr:267- return True268- elif ':' in expr:269- return expr.split(':', 1) == [self.type, self.value]270- return False271-272- def test_any(self, *iterable):273- """Test against multiple token expressions."""274- for expr in iterable:275- if self.test(expr):276- return True277- return False278-279- def __repr__(self):280- return 'Token(%r, %r, %r)' % (281- self.lineno,282- self.type,283- self.value284- )285-286-287-@implements_iterator288-class TokenStreamIterator(object):289- """The iterator for tokenstreams. Iterate over the stream290- until the eof token is reached.291- """292-293- def __init__(self, stream):294- self.stream = stream295-296- def __iter__(self):297- return self298-299- def __next__(self):300- token = self.stream.current301- if token.type is TOKEN_EOF:302- self.stream.close()303- raise StopIteration()304- next(self.stream)305- return token306-307-308-@implements_iterator309-class TokenStream(object):310- """A token stream is an iterable that yields :class:`Token`\\s. The311- parser however does not iterate over it but calls :meth:`next` to go312- one token ahead. The current active token is stored as :attr:`current`.313- """314-315- def __init__(self, generator, name, filename):316- self._iter = iter(generator)317- self._pushed = deque()318- self.name = name319- self.filename = filename320- self.closed = False321- self.current = Token(1, TOKEN_INITIAL, '')322- next(self)323-324- def __iter__(self):325- return TokenStreamIterator(self)326-327- def __bool__(self):328- return bool(self._pushed) or self.current.type is not TOKEN_EOF329- __nonzero__ = __bool__ # py2330-331- @property332- def eos(self):333- """Are we at the end of the stream?"""334- return not self335-336- def push(self, token):337- """Push a token back to the stream."""338- self._pushed.append(token)339-340- def look(self):341- """Look at the next token."""342- old_token = next(self)343- result = self.current344- self.push(result)345- self.current = old_token346- return result347-348- def skip(self, n=1):349- """Got n tokens ahead."""350- for x in range(n):351- next(self)352-353- def next_if(self, expr):354- """Perform the token test and return the token if it matched.355- Otherwise the return value is `None`.356- """357- if self.current.test(expr):358- return next(self)359-360- def skip_if(self, expr):361- """Like :meth:`next_if` but only returns `True` or `False`."""362- return self.next_if(expr) is not None363-364- def __next__(self):365- """Go one token ahead and return the old one.366-367- Use the built-in :func:`next` instead of calling this directly.368- """369- rv = self.current370- if self._pushed:371- self.current = self._pushed.popleft()372- elif self.current.type is not TOKEN_EOF:373- try:374- self.current = next(self._iter)375- except StopIteration:376- self.close()377- return rv378-379- def close(self):380- """Close the stream."""381- self.current = Token(self.current.lineno, TOKEN_EOF, '')382- self._iter = None383- self.closed = True384-385- def expect(self, expr):386- """Expect a given token type and return it. This accepts the same387- argument as :meth:`jinja2.lexer.Token.test`.388- """389- if not self.current.test(expr):390- expr = describe_token_expr(expr)391- if self.current.type is TOKEN_EOF:392- raise TemplateSyntaxError('unexpected end of template, '393- 'expected %r.' % expr,394- self.current.lineno,395- self.name, self.filename)396- raise TemplateSyntaxError("expected token %r, got %r" %397- (expr, describe_token(self.current)),398- self.current.lineno,399- self.name, self.filename)400- try:401- return self.current402- finally:403- next(self)404-405-406-def get_lexer(environment):407- """Return a lexer which is probably cached."""408- key = (environment.block_start_string,409- environment.block_end_string,410- environment.variable_start_string,411- environment.variable_end_string,412- environment.comment_start_string,413- environment.comment_end_string,414- environment.line_statement_prefix,415- environment.line_comment_prefix,416- environment.trim_blocks,417- environment.lstrip_blocks,418- environment.newline_sequence,419- environment.keep_trailing_newline)420- lexer = _lexer_cache.get(key)421- if lexer is None:422- lexer = Lexer(environment)423- _lexer_cache[key] = lexer424- return lexer425-426-427-class OptionalLStrip(tuple):428- """A special tuple for marking a point in the state that can have429- lstrip applied.430- """431-432- __slots__ = ()433-434- # Even though it looks like a no-op, creating instances fails435- # without this.436- def __new__(cls, *members, **kwargs):437- return super(OptionalLStrip, cls).__new__(cls, members)438-439-440-class Lexer(object):441- """Class that implements a lexer for a given environment. Automatically442- created by the environment class, usually you don't have to do that.443-444- Note that the lexer is not automatically bound to an environment.445- Multiple environments can share the same lexer.446- """447-448- def __init__(self, environment):449- # shortcuts450- c = lambda x: re.compile(x, re.M | re.S)451- e = re.escape452-453- # lexing rules for tags454- tag_rules = [455- (whitespace_re, TOKEN_WHITESPACE, None),456- (float_re, TOKEN_FLOAT, None),457- (integer_re, TOKEN_INTEGER, None),458- (name_re, TOKEN_NAME, None),459- (string_re, TOKEN_STRING, None),460- (operator_re, TOKEN_OPERATOR, None)461- ]462-463- # assemble the root lexing rule. because "|" is ungreedy464- # we have to sort by length so that the lexer continues working465- # as expected when we have parsing rules like <% for block and466- # <%= for variables. (if someone wants asp like syntax)467- # variables are just part of the rules if variable processing468- # is required.469- root_tag_rules = compile_rules(environment)470-471- # block suffix if trimming is enabled472- block_suffix_re = environment.trim_blocks and '\\n?' or ''473-474- # If lstrip is enabled, it should not be applied if there is any475- # non-whitespace between the newline and block.476- self.lstrip_unless_re = c(r"[^ \t]") if environment.lstrip_blocks else None477-478- self.newline_sequence = environment.newline_sequence479- self.keep_trailing_newline = environment.keep_trailing_newline480-481- # global lexing rules482- self.rules = {483- 'root': [484- # directives485- (c('(.*?)(?:%s)' % '|'.join(486- [r'(?P<raw_begin>%s(\-|\+|)\s*raw\s*(?:\-%s\s*|%s))' % (487- e(environment.block_start_string),488- e(environment.block_end_string),489- e(environment.block_end_string)490- )] + [491- r'(?P<%s>%s(\-|\+|))' % (n, r)492- for n, r in root_tag_rules493- ])), OptionalLStrip(TOKEN_DATA, '#bygroup'), '#bygroup'),494- # data495- (c('.+'), TOKEN_DATA, None)496- ],497- # comments498- TOKEN_COMMENT_BEGIN: [499- (c(r'(.*?)((?:\-%s\s*|%s)%s)' % (500- e(environment.comment_end_string),501- e(environment.comment_end_string),502- block_suffix_re503- )), (TOKEN_COMMENT, TOKEN_COMMENT_END), '#pop'),504- (c('(.)'), (Failure('Missing end of comment tag'),), None)505- ],506- # blocks507- TOKEN_BLOCK_BEGIN: [508- (c(r'(?:\-%s\s*|%s)%s' % (509- e(environment.block_end_string),510- e(environment.block_end_string),511- block_suffix_re512- )), TOKEN_BLOCK_END, '#pop'),513- ] + tag_rules,514- # variables515- TOKEN_VARIABLE_BEGIN: [516- (c(r'\-%s\s*|%s' % (517- e(environment.variable_end_string),518- e(environment.variable_end_string)519- )), TOKEN_VARIABLE_END, '#pop')520- ] + tag_rules,521- # raw block522- TOKEN_RAW_BEGIN: [523- (c(r'(.*?)((?:%s(\-|\+|))\s*endraw\s*(?:\-%s\s*|%s%s))' % (524- e(environment.block_start_string),525- e(environment.block_end_string),526- e(environment.block_end_string),527- block_suffix_re528- )), OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END), '#pop'),529- (c('(.)'), (Failure('Missing end of raw directive'),), None)530- ],531- # line statements532- TOKEN_LINESTATEMENT_BEGIN: [533- (c(r'\s*(\n|$)'), TOKEN_LINESTATEMENT_END, '#pop')534- ] + tag_rules,535- # line comments536- TOKEN_LINECOMMENT_BEGIN: [537- (c(r'(.*?)()(?=\n|$)'), (TOKEN_LINECOMMENT,538- TOKEN_LINECOMMENT_END), '#pop')539- ]540- }541-542- def _normalize_newlines(self, value):543- """Called for strings and template data to normalize it to unicode."""544- return newline_re.sub(self.newline_sequence, value)545-546- def tokenize(self, source, name=None, filename=None, state=None):547- """Calls tokeniter + tokenize and wraps it in a token stream.548- """549- stream = self.tokeniter(source, name, filename, state)550- return TokenStream(self.wrap(stream, name, filename), name, filename)551-552- def wrap(self, stream, name=None, filename=None):553- """This is called with the stream as returned by `tokenize` and wraps554- every token in a :class:`Token` and converts the value.555- """556- for lineno, token, value in stream:557- if token in ignored_tokens:558- continue559- elif token == TOKEN_LINESTATEMENT_BEGIN:560- token = TOKEN_BLOCK_BEGIN561- elif token == TOKEN_LINESTATEMENT_END:562- token = TOKEN_BLOCK_END563- # we are not interested in those tokens in the parser564- elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END):565- continue566- elif token == TOKEN_DATA:567- value = self._normalize_newlines(value)568- elif token == 'keyword':569- token = value570- elif token == TOKEN_NAME:571- value = str(value)572- if check_ident and not value.isidentifier():573- raise TemplateSyntaxError(574- 'Invalid character in identifier',575- lineno, name, filename)576- elif token == TOKEN_STRING:577- # try to unescape string578- try:579- value = self._normalize_newlines(value[1:-1]) \580- .encode('ascii', 'backslashreplace') \581- .decode('unicode-escape')582- except Exception as e:583- msg = str(e).split(':')[-1].strip()584- raise TemplateSyntaxError(msg, lineno, name, filename)585- elif token == TOKEN_INTEGER:586- value = int(value.replace("_", ""))587- elif token == TOKEN_FLOAT:588- # remove all "_" first to support more Python versions589- value = literal_eval(value.replace("_", ""))590- elif token == TOKEN_OPERATOR:591- token = operators[value]592- yield Token(lineno, token, value)593-594- def tokeniter(self, source, name, filename=None, state=None):595- """This method tokenizes the text and returns the tokens in a596- generator. Use this method if you just want to tokenize a template.597- """598- source = text_type(source)599- lines = source.splitlines()600- if self.keep_trailing_newline and source:601- for newline in ('\r\n', '\r', '\n'):602- if source.endswith(newline):603- lines.append('')604- break605- source = '\n'.join(lines)606- pos = 0607- lineno = 1608- stack = ['root']609- if state is not None and state != 'root':610- assert state in ('variable', 'block'), 'invalid state'611- stack.append(state + '_begin')612- statetokens = self.rules[stack[-1]]613- source_length = len(source)614- balancing_stack = []615- lstrip_unless_re = self.lstrip_unless_re616-617- while 1:618- # tokenizer loop619- for regex, tokens, new_state in statetokens:620- m = regex.match(source, pos)621- # if no match we try again with the next rule622- if m is None:623- continue624-625- # we only match blocks and variables if braces / parentheses626- # are balanced. continue parsing with the lower rule which627- # is the operator rule. do this only if the end tags look628- # like operators629- if (630- balancing_stack631- and tokens in (632- TOKEN_VARIABLE_END, TOKEN_BLOCK_END, TOKEN_LINESTATEMENT_END633- )634- ):635- continue636-637- # tuples support more options638- if isinstance(tokens, tuple):639- groups = m.groups()640-641- if isinstance(tokens, OptionalLStrip):642- # Rule supports lstrip. Match will look like643- # text, block type, whitespace control, type, control, ...644- text = groups[0]645-646- # Skipping the text and first type, every other group is the647- # whitespace control for each type. One of the groups will be648- # -, +, or empty string instead of None.649- strip_sign = next(g for g in groups[2::2] if g is not None)650-651- if strip_sign == "-":652- # Strip all whitespace between the text and the tag.653- groups = (text.rstrip(),) + groups[1:]654- elif (655- # Not marked for preserving whitespace.656- strip_sign != "+"657- # lstrip is enabled.658- and lstrip_unless_re is not None659- # Not a variable expression.660- and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)661- ):662- # The start of text between the last newline and the tag.663- l_pos = text.rfind('\n') + 1664-665- # If there's only whitespace between the newline and the666- # tag, strip it.667- if not lstrip_unless_re.search(text, l_pos):668- groups = (text[:l_pos],) + groups[1:]669-670- for idx, token in enumerate(tokens):671- # failure group672- if token.__class__ is Failure:673- raise token(lineno, filename)674- # bygroup is a bit more complex, in that case we675- # yield for the current token the first named676- # group that matched677- elif token == '#bygroup':678- for key, value in iteritems(m.groupdict()):679- if value is not None:680- yield lineno, key, value681- lineno += value.count('\n')682- break683- else:684- raise RuntimeError('%r wanted to resolve '685- 'the token dynamically'686- ' but no group matched'687- % regex)688- # normal group689- else:690- data = groups[idx]691- if data or token not in ignore_if_empty:692- yield lineno, token, data693- lineno += data.count('\n')694-695- # strings as token just are yielded as it.696- else:697- data = m.group()698- # update brace/parentheses balance699- if tokens == TOKEN_OPERATOR:700- if data == '{':701- balancing_stack.append('}')702- elif data == '(':703- balancing_stack.append(')')704- elif data == '[':705- balancing_stack.append(']')706- elif data in ('}', ')', ']'):707- if not balancing_stack:708- raise TemplateSyntaxError('unexpected \'%s\'' %709- data, lineno, name,710- filename)711- expected_op = balancing_stack.pop()712- if expected_op != data:713- raise TemplateSyntaxError('unexpected \'%s\', '714- 'expected \'%s\'' %715- (data, expected_op),716- lineno, name,717- filename)718- # yield items719- if data or tokens not in ignore_if_empty:720- yield lineno, tokens, data721- lineno += data.count('\n')722-723- # fetch new position into new variable so that we can check724- # if there is a internal parsing error which would result725- # in an infinite loop726- pos2 = m.end()727-728- # handle state changes729- if new_state is not None:730- # remove the uppermost state731- if new_state == '#pop':732- stack.pop()733- # resolve the new state by group checking734- elif new_state == '#bygroup':735- for key, value in iteritems(m.groupdict()):736- if value is not None:737- stack.append(key)738- break739- else:740- raise RuntimeError('%r wanted to resolve the '741- 'new state dynamically but'742- ' no group matched' %743- regex)744- # direct state name given745- else:746- stack.append(new_state)747- statetokens = self.rules[stack[-1]]748- # we are still at the same position and no stack change.749- # this means a loop without break condition, avoid that and750- # raise error751- elif pos2 == pos:752- raise RuntimeError('%r yielded empty string without '753- 'stack change' % regex)754- # publish new function and start again755- pos = pos2756- break757- # if loop terminated without break we haven't found a single match758- # either we are at the end of the file or we have a problem759- else:760- # end of text761- if pos >= source_length:762- return763- # something went wrong764- raise TemplateSyntaxError('unexpected char %r at %d' %765- (source[pos], pos), lineno,766- name, filename)deleted:jinja2/loaders.py-567 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.loaders4- ~~~~~~~~~~~~~~5-6- Jinja loader classes.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import pkgutil13-import sys14-import weakref15-from importlib import import_module16-from types import ModuleType17-from os import path18-from hashlib import sha119-from jinja2.exceptions import TemplateNotFound20-from jinja2.utils import open_if_exists, internalcode21-from jinja2._compat import string_types, iteritems, fspath, abc22-23-24-def split_template_path(template):25- """Split a path into segments and perform a sanity check. If it detects26- '..' in the path it will raise a `TemplateNotFound` error.27- """28- pieces = []29- for piece in template.split('/'):30- if path.sep in piece \31- or (path.altsep and path.altsep in piece) or \32- piece == path.pardir:33- raise TemplateNotFound(template)34- elif piece and piece != '.':35- pieces.append(piece)36- return pieces37-38-39-class BaseLoader(object):40- """Baseclass for all loaders. Subclass this and override `get_source` to41- implement a custom loading mechanism. The environment provides a42- `get_template` method that calls the loader's `load` method to get the43- :class:`Template` object.44-45- A very basic example for a loader that looks up templates on the file46- system could look like this::47-48- from jinja2 import BaseLoader, TemplateNotFound49- from os.path import join, exists, getmtime50-51- class MyLoader(BaseLoader):52-53- def __init__(self, path):54- self.path = path55-56- def get_source(self, environment, template):57- path = join(self.path, template)58- if not exists(path):59- raise TemplateNotFound(template)60- mtime = getmtime(path)61- with file(path) as f:62- source = f.read().decode('utf-8')63- return source, path, lambda: mtime == getmtime(path)64- """65-66- #: if set to `False` it indicates that the loader cannot provide access67- #: to the source of templates.68- #:69- #: .. versionadded:: 2.470- has_source_access = True71-72- def get_source(self, environment, template):73- """Get the template source, filename and reload helper for a template.74- It's passed the environment and template name and has to return a75- tuple in the form ``(source, filename, uptodate)`` or raise a76- `TemplateNotFound` error if it can't locate the template.77-78- The source part of the returned tuple must be the source of the79- template as unicode string or a ASCII bytestring. The filename should80- be the name of the file on the filesystem if it was loaded from there,81- otherwise `None`. The filename is used by python for the tracebacks82- if no loader extension is used.83-84- The last item in the tuple is the `uptodate` function. If auto85- reloading is enabled it's always called to check if the template86- changed. No arguments are passed so the function must store the87- old state somewhere (for example in a closure). If it returns `False`88- the template will be reloaded.89- """90- if not self.has_source_access:91- raise RuntimeError('%s cannot provide access to the source' %92- self.__class__.__name__)93- raise TemplateNotFound(template)94-95- def list_templates(self):96- """Iterates over all templates. If the loader does not support that97- it should raise a :exc:`TypeError` which is the default behavior.98- """99- raise TypeError('this loader cannot iterate over all templates')100-101- @internalcode102- def load(self, environment, name, globals=None):103- """Loads a template. This method looks up the template in the cache104- or loads one by calling :meth:`get_source`. Subclasses should not105- override this method as loaders working on collections of other106- loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)107- will not call this method but `get_source` directly.108- """109- code = None110- if globals is None:111- globals = {}112-113- # first we try to get the source for this template together114- # with the filename and the uptodate function.115- source, filename, uptodate = self.get_source(environment, name)116-117- # try to load the code from the bytecode cache if there is a118- # bytecode cache configured.119- bcc = environment.bytecode_cache120- if bcc is not None:121- bucket = bcc.get_bucket(environment, name, filename, source)122- code = bucket.code123-124- # if we don't have code so far (not cached, no longer up to125- # date) etc. we compile the template126- if code is None:127- code = environment.compile(source, name, filename)128-129- # if the bytecode cache is available and the bucket doesn't130- # have a code so far, we give the bucket the new code and put131- # it back to the bytecode cache.132- if bcc is not None and bucket.code is None:133- bucket.code = code134- bcc.set_bucket(bucket)135-136- return environment.template_class.from_code(environment, code,137- globals, uptodate)138-139-140-class FileSystemLoader(BaseLoader):141- """Loads templates from the file system. This loader can find templates142- in folders on the file system and is the preferred way to load them.143-144- The loader takes the path to the templates as string, or if multiple145- locations are wanted a list of them which is then looked up in the146- given order::147-148- >>> loader = FileSystemLoader('/path/to/templates')149- >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])150-151- Per default the template encoding is ``'utf-8'`` which can be changed152- by setting the `encoding` parameter to something else.153-154- To follow symbolic links, set the *followlinks* parameter to ``True``::155-156- >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)157-158- .. versionchanged:: 2.8159- The ``followlinks`` parameter was added.160- """161-162- def __init__(self, searchpath, encoding='utf-8', followlinks=False):163- if (164- not isinstance(searchpath, abc.Iterable)165- or isinstance(searchpath, string_types)166- ):167- searchpath = [searchpath]168-169- # In Python 3.5, os.path.join doesn't support Path. This can be170- # simplified to list(searchpath) when Python 3.5 is dropped.171- self.searchpath = [fspath(p) for p in searchpath]172-173- self.encoding = encoding174- self.followlinks = followlinks175-176- def get_source(self, environment, template):177- pieces = split_template_path(template)178- for searchpath in self.searchpath:179- filename = path.join(searchpath, *pieces)180- f = open_if_exists(filename)181- if f is None:182- continue183- try:184- contents = f.read().decode(self.encoding)185- finally:186- f.close()187-188- mtime = path.getmtime(filename)189-190- def uptodate():191- try:192- return path.getmtime(filename) == mtime193- except OSError:194- return False195- return contents, filename, uptodate196- raise TemplateNotFound(template)197-198- def list_templates(self):199- found = set()200- for searchpath in self.searchpath:201- walk_dir = os.walk(searchpath, followlinks=self.followlinks)202- for dirpath, dirnames, filenames in walk_dir:203- for filename in filenames:204- template = os.path.join(dirpath, filename) \205- [len(searchpath):].strip(os.path.sep) \206- .replace(os.path.sep, '/')207- if template[:2] == './':208- template = template[2:]209- if template not in found:210- found.add(template)211- return sorted(found)212-213-214-class PackageLoader(BaseLoader):215- """Load templates from a directory in a Python package.216-217- :param package_name: Import name of the package that contains the218- template directory.219- :param package_path: Directory within the imported package that220- contains the templates.221- :param encoding: Encoding of template files.222-223- The following example looks up templates in the ``pages`` directory224- within the ``project.ui`` package.225-226- .. code-block:: python227-228- loader = PackageLoader("project.ui", "pages")229-230- Only packages installed as directories (standard pip behavior) or231- zip/egg files (less common) are supported. The Python API for232- introspecting data in packages is too limited to support other233- installation methods the way this loader requires.234-235- There is limited support for :pep:`420` namespace packages. The236- template directory is assumed to only be in one namespace237- contributor. Zip files contributing to a namespace are not238- supported.239-240- .. versionchanged:: 2.11.0241- No longer uses ``setuptools`` as a dependency.242-243- .. versionchanged:: 2.11.0244- Limited PEP 420 namespace package support.245- """246-247- def __init__(self, package_name, package_path="templates", encoding="utf-8"):248- if package_path == os.path.curdir:249- package_path = ""250- elif package_path[:2] == os.path.curdir + os.path.sep:251- package_path = package_path[2:]252-253- package_path = os.path.normpath(package_path).rstrip(os.path.sep)254- self.package_path = package_path255- self.package_name = package_name256- self.encoding = encoding257-258- # Make sure the package exists. This also makes namespace259- # packages work, otherwise get_loader returns None.260- import_module(package_name)261- self._loader = loader = pkgutil.get_loader(package_name)262-263- # Zip loader's archive attribute points at the zip.264- self._archive = getattr(loader, "archive", None)265- self._template_root = None266-267- if hasattr(loader, "get_filename"):268- # A standard directory package, or a zip package.269- self._template_root = os.path.join(270- os.path.dirname(loader.get_filename(package_name)), package_path271- )272- elif hasattr(loader, "_path"):273- # A namespace package, limited support. Find the first274- # contributor with the template directory.275- for root in loader._path:276- root = os.path.join(root, package_path)277-278- if os.path.isdir(root):279- self._template_root = root280- break281-282- if self._template_root is None:283- raise ValueError(284- "The %r package was not installed in a way that"285- " PackageLoader understands." % package_name286- )287-288- def get_source(self, environment, template):289- p = os.path.join(self._template_root, *split_template_path(template))290-291- if self._archive is None:292- # Package is a directory.293- if not os.path.isfile(p):294- raise TemplateNotFound(template)295-296- with open(p, "rb") as f:297- source = f.read()298-299- mtime = os.path.getmtime(p)300-301- def up_to_date():302- return os.path.isfile(p) and os.path.getmtime(p) == mtime303- else:304- # Package is a zip file.305- try:306- source = self._loader.get_data(p)307- except OSError:308- raise TemplateNotFound(template)309-310- # Could use the zip's mtime for all template mtimes, but311- # would need to safely reload the module if it's out of312- # date, so just report it as always current.313- up_to_date = None314-315- return source.decode(self.encoding), p, up_to_date316-317- def list_templates(self):318- results = []319-320- if self._archive is None:321- # Package is a directory.322- offset = len(self._template_root)323-324- for dirpath, _, filenames in os.walk(self._template_root):325- dirpath = dirpath[offset:].lstrip(os.path.sep)326- results.extend(327- os.path.join(dirpath, name).replace(os.path.sep, "/")328- for name in filenames329- )330- else:331- if not hasattr(self._loader, "_files"):332- raise TypeError(333- "This zip import does not have the required"334- " metadata to list templates."335- )336-337- # Package is a zip file.338- prefix = (339- self._template_root[len(self._archive):].lstrip(os.path.sep)340- + os.path.sep341- )342- offset = len(prefix)343-344- for name in self._loader._files.keys():345- # Find names under the templates directory that aren't directories.346- if name.startswith(prefix) and name[-1] != os.path.sep:347- results.append(name[offset:].replace(os.path.sep, "/"))348-349- results.sort()350- return results351-352-353-class DictLoader(BaseLoader):354- """Loads a template from a python dict. It's passed a dict of unicode355- strings bound to template names. This loader is useful for unittesting:356-357- >>> loader = DictLoader({'index.html': 'source here'})358-359- Because auto reloading is rarely useful this is disabled per default.360- """361-362- def __init__(self, mapping):363- self.mapping = mapping364-365- def get_source(self, environment, template):366- if template in self.mapping:367- source = self.mapping[template]368- return source, None, lambda: source == self.mapping.get(template)369- raise TemplateNotFound(template)370-371- def list_templates(self):372- return sorted(self.mapping)373-374-375-class FunctionLoader(BaseLoader):376- """A loader that is passed a function which does the loading. The377- function receives the name of the template and has to return either378- an unicode string with the template source, a tuple in the form ``(source,379- filename, uptodatefunc)`` or `None` if the template does not exist.380-381- >>> def load_template(name):382- ... if name == 'index.html':383- ... return '...'384- ...385- >>> loader = FunctionLoader(load_template)386-387- The `uptodatefunc` is a function that is called if autoreload is enabled388- and has to return `True` if the template is still up to date. For more389- details have a look at :meth:`BaseLoader.get_source` which has the same390- return value.391- """392-393- def __init__(self, load_func):394- self.load_func = load_func395-396- def get_source(self, environment, template):397- rv = self.load_func(template)398- if rv is None:399- raise TemplateNotFound(template)400- elif isinstance(rv, string_types):401- return rv, None, None402- return rv403-404-405-class PrefixLoader(BaseLoader):406- """A loader that is passed a dict of loaders where each loader is bound407- to a prefix. The prefix is delimited from the template by a slash per408- default, which can be changed by setting the `delimiter` argument to409- something else::410-411- loader = PrefixLoader({412- 'app1': PackageLoader('mypackage.app1'),413- 'app2': PackageLoader('mypackage.app2')414- })415-416- By loading ``'app1/index.html'`` the file from the app1 package is loaded,417- by loading ``'app2/index.html'`` the file from the second.418- """419-420- def __init__(self, mapping, delimiter='/'):421- self.mapping = mapping422- self.delimiter = delimiter423-424- def get_loader(self, template):425- try:426- prefix, name = template.split(self.delimiter, 1)427- loader = self.mapping[prefix]428- except (ValueError, KeyError):429- raise TemplateNotFound(template)430- return loader, name431-432- def get_source(self, environment, template):433- loader, name = self.get_loader(template)434- try:435- return loader.get_source(environment, name)436- except TemplateNotFound:437- # re-raise the exception with the correct filename here.438- # (the one that includes the prefix)439- raise TemplateNotFound(template)440-441- @internalcode442- def load(self, environment, name, globals=None):443- loader, local_name = self.get_loader(name)444- try:445- return loader.load(environment, local_name, globals)446- except TemplateNotFound:447- # re-raise the exception with the correct filename here.448- # (the one that includes the prefix)449- raise TemplateNotFound(name)450-451- def list_templates(self):452- result = []453- for prefix, loader in iteritems(self.mapping):454- for template in loader.list_templates():455- result.append(prefix + self.delimiter + template)456- return result457-458-459-class ChoiceLoader(BaseLoader):460- """This loader works like the `PrefixLoader` just that no prefix is461- specified. If a template could not be found by one loader the next one462- is tried.463-464- >>> loader = ChoiceLoader([465- ... FileSystemLoader('/path/to/user/templates'),466- ... FileSystemLoader('/path/to/system/templates')467- ... ])468-469- This is useful if you want to allow users to override builtin templates470- from a different location.471- """472-473- def __init__(self, loaders):474- self.loaders = loaders475-476- def get_source(self, environment, template):477- for loader in self.loaders:478- try:479- return loader.get_source(environment, template)480- except TemplateNotFound:481- pass482- raise TemplateNotFound(template)483-484- @internalcode485- def load(self, environment, name, globals=None):486- for loader in self.loaders:487- try:488- return loader.load(environment, name, globals)489- except TemplateNotFound:490- pass491- raise TemplateNotFound(name)492-493- def list_templates(self):494- found = set()495- for loader in self.loaders:496- found.update(loader.list_templates())497- return sorted(found)498-499-500-class _TemplateModule(ModuleType):501- """Like a normal module but with support for weak references"""502-503-504-class ModuleLoader(BaseLoader):505- """This loader loads templates from precompiled templates.506-507- Example usage:508-509- >>> loader = ChoiceLoader([510- ... ModuleLoader('/path/to/compiled/templates'),511- ... FileSystemLoader('/path/to/templates')512- ... ])513-514- Templates can be precompiled with :meth:`Environment.compile_templates`.515- """516-517- has_source_access = False518-519- def __init__(self, path):520- package_name = '_jinja2_module_templates_%x' % id(self)521-522- # create a fake module that looks for the templates in the523- # path given.524- mod = _TemplateModule(package_name)525-526- if (527- not isinstance(path, abc.Iterable)528- or isinstance(path, string_types)529- ):530- path = [path]531-532- mod.__path__ = [fspath(p) for p in path]533-534- sys.modules[package_name] = weakref.proxy(mod,535- lambda x: sys.modules.pop(package_name, None))536-537- # the only strong reference, the sys.modules entry is weak538- # so that the garbage collector can remove it once the539- # loader that created it goes out of business.540- self.module = mod541- self.package_name = package_name542-543- @staticmethod544- def get_template_key(name):545- return 'tmpl_' + sha1(name.encode('utf-8')).hexdigest()546-547- @staticmethod548- def get_module_filename(name):549- return ModuleLoader.get_template_key(name) + '.py'550-551- @internalcode552- def load(self, environment, name, globals=None):553- key = self.get_template_key(name)554- module = '%s.%s' % (self.package_name, key)555- mod = getattr(self.module, module, None)556- if mod is None:557- try:558- mod = __import__(module, None, None, ['root'])559- except ImportError:560- raise TemplateNotFound(name)561-562- # remove the entry from sys.modules, we only want the attribute563- # on the module object we have stored on the loader.564- sys.modules.pop(module, None)565-566- return environment.template_class.from_module_dict(567- environment, mod.__dict__, globals)deleted:jinja2/meta.py-106 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.meta4- ~~~~~~~~~~~5-6- This module implements various functions that exposes information about7- templates that might be interesting for various kinds of applications.8-9- :copyright: (c) 2017 by the Jinja Team, see AUTHORS for more details.10- :license: BSD, see LICENSE for more details.11-"""12-from jinja2 import nodes13-from jinja2.compiler import CodeGenerator14-from jinja2._compat import string_types, iteritems15-16-17-class TrackingCodeGenerator(CodeGenerator):18- """We abuse the code generator for introspection."""19-20- def __init__(self, environment):21- CodeGenerator.__init__(self, environment, '<introspection>',22- '<introspection>')23- self.undeclared_identifiers = set()24-25- def write(self, x):26- """Don't write."""27-28- def enter_frame(self, frame):29- """Remember all undeclared identifiers."""30- CodeGenerator.enter_frame(self, frame)31- for _, (action, param) in iteritems(frame.symbols.loads):32- if action == 'resolve' and param not in self.environment.globals:33- self.undeclared_identifiers.add(param)34-35-36-def find_undeclared_variables(ast):37- """Returns a set of all variables in the AST that will be looked up from38- the context at runtime. Because at compile time it's not known which39- variables will be used depending on the path the execution takes at40- runtime, all variables are returned.41-42- >>> from jinja2 import Environment, meta43- >>> env = Environment()44- >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')45- >>> meta.find_undeclared_variables(ast) == set(['bar'])46- True47-48- .. admonition:: Implementation49-50- Internally the code generator is used for finding undeclared variables.51- This is good to know because the code generator might raise a52- :exc:`TemplateAssertionError` during compilation and as a matter of53- fact this function can currently raise that exception as well.54- """55- codegen = TrackingCodeGenerator(ast.environment)56- codegen.visit(ast)57- return codegen.undeclared_identifiers58-59-60-def find_referenced_templates(ast):61- """Finds all the referenced templates from the AST. This will return an62- iterator over all the hardcoded template extensions, inclusions and63- imports. If dynamic inheritance or inclusion is used, `None` will be64- yielded.65-66- >>> from jinja2 import Environment, meta67- >>> env = Environment()68- >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')69- >>> list(meta.find_referenced_templates(ast))70- ['layout.html', None]71-72- This function is useful for dependency tracking. For example if you want73- to rebuild parts of the website after a layout template has changed.74- """75- for node in ast.find_all((nodes.Extends, nodes.FromImport, nodes.Import,76- nodes.Include)):77- if not isinstance(node.template, nodes.Const):78- # a tuple with some non consts in there79- if isinstance(node.template, (nodes.Tuple, nodes.List)):80- for template_name in node.template.items:81- # something const, only yield the strings and ignore82- # non-string consts that really just make no sense83- if isinstance(template_name, nodes.Const):84- if isinstance(template_name.value, string_types):85- yield template_name.value86- # something dynamic in there87- else:88- yield None89- # something dynamic we don't know about here90- else:91- yield None92- continue93- # constant is a basestring, direct template name94- if isinstance(node.template.value, string_types):95- yield node.template.value96- # a tuple or list (latter *should* not happen) made of consts,97- # yield the consts that are strings. We could warn here for98- # non string values99- elif isinstance(node, nodes.Include) and \100- isinstance(node.template.value, (tuple, list)):101- for template_name in node.template.value:102- if isinstance(template_name, string_types):103- yield template_name104- # something else we don't care about, we could warn here105- else:106- yield Nonedeleted:jinja2/nativetypes.py-107 removed
1-import types2-from ast import literal_eval3-from itertools import islice, chain4-from jinja2 import nodes5-from jinja2._compat import text_type6-from jinja2.compiler import CodeGenerator, has_safe_repr7-from jinja2.environment import Environment, Template8-9-10-def native_concat(nodes, preserve_quotes=True):11- """Return a native Python type from the list of compiled nodes. If12- the result is a single node, its value is returned. Otherwise, the13- nodes are concatenated as strings. If the result can be parsed with14- :func:`ast.literal_eval`, the parsed value is returned. Otherwise,15- the string is returned.16-17- :param nodes: Iterable of nodes to concatenate.18- :param preserve_quotes: Whether to re-wrap literal strings with19- quotes, to preserve quotes around expressions for later parsing.20- Should be ``False`` in :meth:`NativeEnvironment.render`.21- """22- head = list(islice(nodes, 2))23-24- if not head:25- return None26-27- if len(head) == 1:28- raw = head[0]29- else:30- if isinstance(nodes, types.GeneratorType):31- nodes = chain(head, nodes)32- raw = u''.join([text_type(v) for v in nodes])33-34- try:35- literal = literal_eval(raw)36- except (ValueError, SyntaxError, MemoryError):37- return raw38-39- # If literal_eval returned a string, re-wrap with the original40- # quote character to avoid dropping quotes between expression nodes.41- # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should42- # be ('a', 'b').43- if preserve_quotes and isinstance(literal, str):44- return "{quote}{}{quote}".format(literal, quote=raw[0])45-46- return literal47-48-49-class NativeCodeGenerator(CodeGenerator):50- """A code generator which renders Python types by not adding51- ``to_string()`` around output nodes, and using :func:`native_concat`52- to convert complex strings back to Python types if possible.53- """54-55- @staticmethod56- def _default_finalize(value):57- return value58-59- def _output_const_repr(self, group):60- return repr(native_concat(group))61-62- def _output_child_to_const(self, node, frame, finalize):63- const = node.as_const(frame.eval_ctx)64-65- if not has_safe_repr(const):66- raise nodes.Impossible()67-68- if isinstance(node, nodes.TemplateData):69- return const70-71- return finalize.const(const)72-73- def _output_child_pre(self, node, frame, finalize):74- if finalize.src is not None:75- self.write(finalize.src)76-77- def _output_child_post(self, node, frame, finalize):78- if finalize.src is not None:79- self.write(")")80-81-82-class NativeEnvironment(Environment):83- """An environment that renders templates to native Python types."""84-85- code_generator_class = NativeCodeGenerator86-87-88-class NativeTemplate(Template):89- environment_class = NativeEnvironment90-91- def render(self, *args, **kwargs):92- """Render the template to produce a native Python type. If the93- result is a single node, its value is returned. Otherwise, the94- nodes are concatenated as strings. If the result can be parsed95- with :func:`ast.literal_eval`, the parsed value is returned.96- Otherwise, the string is returned.97- """98- vars = dict(*args, **kwargs)99- try:100- return native_concat(101- self.root_render_func(self.new_context(vars)), preserve_quotes=False102- )103- except Exception:104- return self.environment.handle_exception()105-106-107-NativeEnvironment.template_class = NativeTemplatedeleted:jinja2/nodes.py-1015 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.nodes4- ~~~~~~~~~~~~5-6- This module implements additional nodes derived from the ast base node.7-8- It also provides some node tree helper functions like `in_lineno` and9- `get_nodes` used by the parser and translator in order to normalize10- python and jinja nodes.11-12- :copyright: (c) 2017 by the Jinja Team.13- :license: BSD, see LICENSE for more details.14-"""15-import types16-import operator17-18-from collections import deque19-from jinja2.utils import Markup20-from jinja2._compat import izip, with_metaclass, text_type, PY221-22-23-_binop_to_func = {24- '*': operator.mul,25- '/': operator.truediv,26- '//': operator.floordiv,27- '**': operator.pow,28- '%': operator.mod,29- '+': operator.add,30- '-': operator.sub31-}32-33-_uaop_to_func = {34- 'not': operator.not_,35- '+': operator.pos,36- '-': operator.neg37-}38-39-_cmpop_to_func = {40- 'eq': operator.eq,41- 'ne': operator.ne,42- 'gt': operator.gt,43- 'gteq': operator.ge,44- 'lt': operator.lt,45- 'lteq': operator.le,46- 'in': lambda a, b: a in b,47- 'notin': lambda a, b: a not in b48-}49-50-51-class Impossible(Exception):52- """Raised if the node could not perform a requested action."""53-54-55-class NodeType(type):56- """A metaclass for nodes that handles the field and attribute57- inheritance. fields and attributes from the parent class are58- automatically forwarded to the child."""59-60- def __new__(cls, name, bases, d):61- for attr in 'fields', 'attributes':62- storage = []63- storage.extend(getattr(bases[0], attr, ()))64- storage.extend(d.get(attr, ()))65- assert len(bases) == 1, 'multiple inheritance not allowed'66- assert len(storage) == len(set(storage)), 'layout conflict'67- d[attr] = tuple(storage)68- d.setdefault('abstract', False)69- return type.__new__(cls, name, bases, d)70-71-72-class EvalContext(object):73- """Holds evaluation time information. Custom attributes can be attached74- to it in extensions.75- """76-77- def __init__(self, environment, template_name=None):78- self.environment = environment79- if callable(environment.autoescape):80- self.autoescape = environment.autoescape(template_name)81- else:82- self.autoescape = environment.autoescape83- self.volatile = False84-85- def save(self):86- return self.__dict__.copy()87-88- def revert(self, old):89- self.__dict__.clear()90- self.__dict__.update(old)91-92-93-def get_eval_context(node, ctx):94- if ctx is None:95- if node.environment is None:96- raise RuntimeError('if no eval context is passed, the '97- 'node must have an attached '98- 'environment.')99- return EvalContext(node.environment)100- return ctx101-102-103-class Node(with_metaclass(NodeType, object)):104- """Baseclass for all Jinja nodes. There are a number of nodes available105- of different types. There are four major types:106-107- - :class:`Stmt`: statements108- - :class:`Expr`: expressions109- - :class:`Helper`: helper nodes110- - :class:`Template`: the outermost wrapper node111-112- All nodes have fields and attributes. Fields may be other nodes, lists,113- or arbitrary values. Fields are passed to the constructor as regular114- positional arguments, attributes as keyword arguments. Each node has115- two attributes: `lineno` (the line number of the node) and `environment`.116- The `environment` attribute is set at the end of the parsing process for117- all nodes automatically.118- """119- fields = ()120- attributes = ('lineno', 'environment')121- abstract = True122-123- def __init__(self, *fields, **attributes):124- if self.abstract:125- raise TypeError('abstract nodes are not instantiable')126- if fields:127- if len(fields) != len(self.fields):128- if not self.fields:129- raise TypeError('%r takes 0 arguments' %130- self.__class__.__name__)131- raise TypeError('%r takes 0 or %d argument%s' % (132- self.__class__.__name__,133- len(self.fields),134- len(self.fields) != 1 and 's' or ''135- ))136- for name, arg in izip(self.fields, fields):137- setattr(self, name, arg)138- for attr in self.attributes:139- setattr(self, attr, attributes.pop(attr, None))140- if attributes:141- raise TypeError('unknown attribute %r' %142- next(iter(attributes)))143-144- def iter_fields(self, exclude=None, only=None):145- """This method iterates over all fields that are defined and yields146- ``(key, value)`` tuples. Per default all fields are returned, but147- it's possible to limit that to some fields by providing the `only`148- parameter or to exclude some using the `exclude` parameter. Both149- should be sets or tuples of field names.150- """151- for name in self.fields:152- if (exclude is only is None) or \153- (exclude is not None and name not in exclude) or \154- (only is not None and name in only):155- try:156- yield name, getattr(self, name)157- except AttributeError:158- pass159-160- def iter_child_nodes(self, exclude=None, only=None):161- """Iterates over all direct child nodes of the node. This iterates162- over all fields and yields the values of they are nodes. If the value163- of a field is a list all the nodes in that list are returned.164- """165- for field, item in self.iter_fields(exclude, only):166- if isinstance(item, list):167- for n in item:168- if isinstance(n, Node):169- yield n170- elif isinstance(item, Node):171- yield item172-173- def find(self, node_type):174- """Find the first node of a given type. If no such node exists the175- return value is `None`.176- """177- for result in self.find_all(node_type):178- return result179-180- def find_all(self, node_type):181- """Find all the nodes of a given type. If the type is a tuple,182- the check is performed for any of the tuple items.183- """184- for child in self.iter_child_nodes():185- if isinstance(child, node_type):186- yield child187- for result in child.find_all(node_type):188- yield result189-190- def set_ctx(self, ctx):191- """Reset the context of a node and all child nodes. Per default the192- parser will all generate nodes that have a 'load' context as it's the193- most common one. This method is used in the parser to set assignment194- targets and other nodes to a store context.195- """196- todo = deque([self])197- while todo:198- node = todo.popleft()199- if 'ctx' in node.fields:200- node.ctx = ctx201- todo.extend(node.iter_child_nodes())202- return self203-204- def set_lineno(self, lineno, override=False):205- """Set the line numbers of the node and children."""206- todo = deque([self])207- while todo:208- node = todo.popleft()209- if 'lineno' in node.attributes:210- if node.lineno is None or override:211- node.lineno = lineno212- todo.extend(node.iter_child_nodes())213- return self214-215- def set_environment(self, environment):216- """Set the environment for all nodes."""217- todo = deque([self])218- while todo:219- node = todo.popleft()220- node.environment = environment221- todo.extend(node.iter_child_nodes())222- return self223-224- def __eq__(self, other):225- return type(self) is type(other) and \226- tuple(self.iter_fields()) == tuple(other.iter_fields())227-228- def __ne__(self, other):229- return not self.__eq__(other)230-231- # Restore Python 2 hashing behavior on Python 3232- __hash__ = object.__hash__233-234- def __repr__(self):235- return '%s(%s)' % (236- self.__class__.__name__,237- ', '.join('%s=%r' % (arg, getattr(self, arg, None)) for238- arg in self.fields)239- )240-241- def dump(self):242- def _dump(node):243- if not isinstance(node, Node):244- buf.append(repr(node))245- return246-247- buf.append('nodes.%s(' % node.__class__.__name__)248- if not node.fields:249- buf.append(')')250- return251- for idx, field in enumerate(node.fields):252- if idx:253- buf.append(', ')254- value = getattr(node, field)255- if isinstance(value, list):256- buf.append('[')257- for idx, item in enumerate(value):258- if idx:259- buf.append(', ')260- _dump(item)261- buf.append(']')262- else:263- _dump(value)264- buf.append(')')265- buf = []266- _dump(self)267- return ''.join(buf)268-269-270-271-class Stmt(Node):272- """Base node for all statements."""273- abstract = True274-275-276-class Helper(Node):277- """Nodes that exist in a specific context only."""278- abstract = True279-280-281-class Template(Node):282- """Node that represents a template. This must be the outermost node that283- is passed to the compiler.284- """285- fields = ('body',)286-287-288-class Output(Stmt):289- """A node that holds multiple expressions which are then printed out.290- This is used both for the `print` statement and the regular template data.291- """292- fields = ('nodes',)293-294-295-class Extends(Stmt):296- """Represents an extends statement."""297- fields = ('template',)298-299-300-class For(Stmt):301- """The for loop. `target` is the target for the iteration (usually a302- :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list303- of nodes that are used as loop-body, and `else_` a list of nodes for the304- `else` block. If no else node exists it has to be an empty list.305-306- For filtered nodes an expression can be stored as `test`, otherwise `None`.307- """308- fields = ('target', 'iter', 'body', 'else_', 'test', 'recursive')309-310-311-class If(Stmt):312- """If `test` is true, `body` is rendered, else `else_`."""313- fields = ('test', 'body', 'elif_', 'else_')314-315-316-class Macro(Stmt):317- """A macro definition. `name` is the name of the macro, `args` a list of318- arguments and `defaults` a list of defaults if there are any. `body` is319- a list of nodes for the macro body.320- """321- fields = ('name', 'args', 'defaults', 'body')322-323-324-class CallBlock(Stmt):325- """Like a macro without a name but a call instead. `call` is called with326- the unnamed macro as `caller` argument this node holds.327- """328- fields = ('call', 'args', 'defaults', 'body')329-330-331-class FilterBlock(Stmt):332- """Node for filter sections."""333- fields = ('body', 'filter')334-335-336-class With(Stmt):337- """Specific node for with statements. In older versions of Jinja the338- with statement was implemented on the base of the `Scope` node instead.339-340- .. versionadded:: 2.9.3341- """342- fields = ('targets', 'values', 'body')343-344-345-class Block(Stmt):346- """A node that represents a block."""347- fields = ('name', 'body', 'scoped')348-349-350-class Include(Stmt):351- """A node that represents the include tag."""352- fields = ('template', 'with_context', 'ignore_missing')353-354-355-class Import(Stmt):356- """A node that represents the import tag."""357- fields = ('template', 'target', 'with_context')358-359-360-class FromImport(Stmt):361- """A node that represents the from import tag. It's important to not362- pass unsafe names to the name attribute. The compiler translates the363- attribute lookups directly into getattr calls and does *not* use the364- subscript callback of the interface. As exported variables may not365- start with double underscores (which the parser asserts) this is not a366- problem for regular Jinja code, but if this node is used in an extension367- extra care must be taken.368-369- The list of names may contain tuples if aliases are wanted.370- """371- fields = ('template', 'names', 'with_context')372-373-374-class ExprStmt(Stmt):375- """A statement that evaluates an expression and discards the result."""376- fields = ('node',)377-378-379-class Assign(Stmt):380- """Assigns an expression to a target."""381- fields = ('target', 'node')382-383-384-class AssignBlock(Stmt):385- """Assigns a block to a target."""386- fields = ('target', 'filter', 'body')387-388-389-class Expr(Node):390- """Baseclass for all expressions."""391- abstract = True392-393- def as_const(self, eval_ctx=None):394- """Return the value of the expression as constant or raise395- :exc:`Impossible` if this was not possible.396-397- An :class:`EvalContext` can be provided, if none is given398- a default context is created which requires the nodes to have399- an attached environment.400-401- .. versionchanged:: 2.4402- the `eval_ctx` parameter was added.403- """404- raise Impossible()405-406- def can_assign(self):407- """Check if it's possible to assign something to this node."""408- return False409-410-411-class BinExpr(Expr):412- """Baseclass for all binary expressions."""413- fields = ('left', 'right')414- operator = None415- abstract = True416-417- def as_const(self, eval_ctx=None):418- eval_ctx = get_eval_context(self, eval_ctx)419- # intercepted operators cannot be folded at compile time420- if self.environment.sandboxed and \421- self.operator in self.environment.intercepted_binops:422- raise Impossible()423- f = _binop_to_func[self.operator]424- try:425- return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))426- except Exception:427- raise Impossible()428-429-430-class UnaryExpr(Expr):431- """Baseclass for all unary expressions."""432- fields = ('node',)433- operator = None434- abstract = True435-436- def as_const(self, eval_ctx=None):437- eval_ctx = get_eval_context(self, eval_ctx)438- # intercepted operators cannot be folded at compile time439- if self.environment.sandboxed and \440- self.operator in self.environment.intercepted_unops:441- raise Impossible()442- f = _uaop_to_func[self.operator]443- try:444- return f(self.node.as_const(eval_ctx))445- except Exception:446- raise Impossible()447-448-449-class Name(Expr):450- """Looks up a name or stores a value in a name.451- The `ctx` of the node can be one of the following values:452-453- - `store`: store a value in the name454- - `load`: load that name455- - `param`: like `store` but if the name was defined as function parameter.456- """457- fields = ('name', 'ctx')458-459- def can_assign(self):460- return self.name not in ('true', 'false', 'none',461- 'True', 'False', 'None')462-463-464-class NSRef(Expr):465- """Reference to a namespace value assignment"""466- fields = ('name', 'attr')467-468- def can_assign(self):469- # We don't need any special checks here; NSRef assignments have a470- # runtime check to ensure the target is a namespace object which will471- # have been checked already as it is created using a normal assignment472- # which goes through a `Name` node.473- return True474-475-476-class Literal(Expr):477- """Baseclass for literals."""478- abstract = True479-480-481-class Const(Literal):482- """All constant values. The parser will return this node for simple483- constants such as ``42`` or ``"foo"`` but it can be used to store more484- complex values such as lists too. Only constants with a safe485- representation (objects where ``eval(repr(x)) == x`` is true).486- """487- fields = ('value',)488-489- def as_const(self, eval_ctx=None):490- rv = self.value491- if PY2 and type(rv) is text_type and \492- self.environment.policies['compiler.ascii_str']:493- try:494- rv = rv.encode('ascii')495- except UnicodeError:496- pass497- return rv498-499- @classmethod500- def from_untrusted(cls, value, lineno=None, environment=None):501- """Return a const object if the value is representable as502- constant value in the generated code, otherwise it will raise503- an `Impossible` exception.504- """505- from .compiler import has_safe_repr506- if not has_safe_repr(value):507- raise Impossible()508- return cls(value, lineno=lineno, environment=environment)509-510-511-class TemplateData(Literal):512- """A constant template string."""513- fields = ('data',)514-515- def as_const(self, eval_ctx=None):516- eval_ctx = get_eval_context(self, eval_ctx)517- if eval_ctx.volatile:518- raise Impossible()519- if eval_ctx.autoescape:520- return Markup(self.data)521- return self.data522-523-524-class Tuple(Literal):525- """For loop unpacking and some other things like multiple arguments526- for subscripts. Like for :class:`Name` `ctx` specifies if the tuple527- is used for loading the names or storing.528- """529- fields = ('items', 'ctx')530-531- def as_const(self, eval_ctx=None):532- eval_ctx = get_eval_context(self, eval_ctx)533- return tuple(x.as_const(eval_ctx) for x in self.items)534-535- def can_assign(self):536- for item in self.items:537- if not item.can_assign():538- return False539- return True540-541-542-class List(Literal):543- """Any list literal such as ``[1, 2, 3]``"""544- fields = ('items',)545-546- def as_const(self, eval_ctx=None):547- eval_ctx = get_eval_context(self, eval_ctx)548- return [x.as_const(eval_ctx) for x in self.items]549-550-551-class Dict(Literal):552- """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of553- :class:`Pair` nodes.554- """555- fields = ('items',)556-557- def as_const(self, eval_ctx=None):558- eval_ctx = get_eval_context(self, eval_ctx)559- return dict(x.as_const(eval_ctx) for x in self.items)560-561-562-class Pair(Helper):563- """A key, value pair for dicts."""564- fields = ('key', 'value')565-566- def as_const(self, eval_ctx=None):567- eval_ctx = get_eval_context(self, eval_ctx)568- return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)569-570-571-class Keyword(Helper):572- """A key, value pair for keyword arguments where key is a string."""573- fields = ('key', 'value')574-575- def as_const(self, eval_ctx=None):576- eval_ctx = get_eval_context(self, eval_ctx)577- return self.key, self.value.as_const(eval_ctx)578-579-580-class CondExpr(Expr):581- """A conditional expression (inline if expression). (``{{582- foo if bar else baz }}``)583- """584- fields = ('test', 'expr1', 'expr2')585-586- def as_const(self, eval_ctx=None):587- eval_ctx = get_eval_context(self, eval_ctx)588- if self.test.as_const(eval_ctx):589- return self.expr1.as_const(eval_ctx)590-591- # if we evaluate to an undefined object, we better do that at runtime592- if self.expr2 is None:593- raise Impossible()594-595- return self.expr2.as_const(eval_ctx)596-597-598-def args_as_const(node, eval_ctx):599- args = [x.as_const(eval_ctx) for x in node.args]600- kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)601-602- if node.dyn_args is not None:603- try:604- args.extend(node.dyn_args.as_const(eval_ctx))605- except Exception:606- raise Impossible()607-608- if node.dyn_kwargs is not None:609- try:610- kwargs.update(node.dyn_kwargs.as_const(eval_ctx))611- except Exception:612- raise Impossible()613-614- return args, kwargs615-616-617-class Filter(Expr):618- """This node applies a filter on an expression. `name` is the name of619- the filter, the rest of the fields are the same as for :class:`Call`.620-621- If the `node` of a filter is `None` the contents of the last buffer are622- filtered. Buffers are created by macros and filter blocks.623- """624-625- fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')626-627- def as_const(self, eval_ctx=None):628- eval_ctx = get_eval_context(self, eval_ctx)629-630- if eval_ctx.volatile or self.node is None:631- raise Impossible()632-633- # we have to be careful here because we call filter_ below.634- # if this variable would be called filter, 2to3 would wrap the635- # call in a list because it is assuming we are talking about the636- # builtin filter function here which no longer returns a list in637- # python 3. because of that, do not rename filter_ to filter!638- filter_ = self.environment.filters.get(self.name)639-640- if filter_ is None or getattr(filter_, 'contextfilter', False):641- raise Impossible()642-643- # We cannot constant handle async filters, so we need to make sure644- # to not go down this path.645- if (646- eval_ctx.environment.is_async647- and getattr(filter_, 'asyncfiltervariant', False)648- ):649- raise Impossible()650-651- args, kwargs = args_as_const(self, eval_ctx)652- args.insert(0, self.node.as_const(eval_ctx))653-654- if getattr(filter_, 'evalcontextfilter', False):655- args.insert(0, eval_ctx)656- elif getattr(filter_, 'environmentfilter', False):657- args.insert(0, self.environment)658-659- try:660- return filter_(*args, **kwargs)661- except Exception:662- raise Impossible()663-664-665-class Test(Expr):666- """Applies a test on an expression. `name` is the name of the test, the667- rest of the fields are the same as for :class:`Call`.668- """669-670- fields = ('node', 'name', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')671-672- def as_const(self, eval_ctx=None):673- test = self.environment.tests.get(self.name)674-675- if test is None:676- raise Impossible()677-678- eval_ctx = get_eval_context(self, eval_ctx)679- args, kwargs = args_as_const(self, eval_ctx)680- args.insert(0, self.node.as_const(eval_ctx))681-682- try:683- return test(*args, **kwargs)684- except Exception:685- raise Impossible()686-687-688-class Call(Expr):689- """Calls an expression. `args` is a list of arguments, `kwargs` a list690- of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`691- and `dyn_kwargs` has to be either `None` or a node that is used as692- node for dynamic positional (``*args``) or keyword (``**kwargs``)693- arguments.694- """695- fields = ('node', 'args', 'kwargs', 'dyn_args', 'dyn_kwargs')696-697-698-class Getitem(Expr):699- """Get an attribute or item from an expression and prefer the item."""700- fields = ('node', 'arg', 'ctx')701-702- def as_const(self, eval_ctx=None):703- eval_ctx = get_eval_context(self, eval_ctx)704- if self.ctx != 'load':705- raise Impossible()706- try:707- return self.environment.getitem(self.node.as_const(eval_ctx),708- self.arg.as_const(eval_ctx))709- except Exception:710- raise Impossible()711-712- def can_assign(self):713- return False714-715-716-class Getattr(Expr):717- """Get an attribute or item from an expression that is a ascii-only718- bytestring and prefer the attribute.719- """720- fields = ('node', 'attr', 'ctx')721-722- def as_const(self, eval_ctx=None):723- if self.ctx != 'load':724- raise Impossible()725- try:726- eval_ctx = get_eval_context(self, eval_ctx)727- return self.environment.getattr(self.node.as_const(eval_ctx),728- self.attr)729- except Exception:730- raise Impossible()731-732- def can_assign(self):733- return False734-735-736-class Slice(Expr):737- """Represents a slice object. This must only be used as argument for738- :class:`Subscript`.739- """740- fields = ('start', 'stop', 'step')741-742- def as_const(self, eval_ctx=None):743- eval_ctx = get_eval_context(self, eval_ctx)744- def const(obj):745- if obj is None:746- return None747- return obj.as_const(eval_ctx)748- return slice(const(self.start), const(self.stop), const(self.step))749-750-751-class Concat(Expr):752- """Concatenates the list of expressions provided after converting them to753- unicode.754- """755- fields = ('nodes',)756-757- def as_const(self, eval_ctx=None):758- eval_ctx = get_eval_context(self, eval_ctx)759- return ''.join(text_type(x.as_const(eval_ctx)) for x in self.nodes)760-761-762-class Compare(Expr):763- """Compares an expression with some other expressions. `ops` must be a764- list of :class:`Operand`\\s.765- """766- fields = ('expr', 'ops')767-768- def as_const(self, eval_ctx=None):769- eval_ctx = get_eval_context(self, eval_ctx)770- result = value = self.expr.as_const(eval_ctx)771-772- try:773- for op in self.ops:774- new_value = op.expr.as_const(eval_ctx)775- result = _cmpop_to_func[op.op](value, new_value)776-777- if not result:778- return False779-780- value = new_value781- except Exception:782- raise Impossible()783-784- return result785-786-787-class Operand(Helper):788- """Holds an operator and an expression."""789- fields = ('op', 'expr')790-791-if __debug__:792- Operand.__doc__ += '\nThe following operators are available: ' + \793- ', '.join(sorted('``%s``' % x for x in set(_binop_to_func) |794- set(_uaop_to_func) | set(_cmpop_to_func)))795-796-797-class Mul(BinExpr):798- """Multiplies the left with the right node."""799- operator = '*'800-801-802-class Div(BinExpr):803- """Divides the left by the right node."""804- operator = '/'805-806-807-class FloorDiv(BinExpr):808- """Divides the left by the right node and truncates conver the809- result into an integer by truncating.810- """811- operator = '//'812-813-814-class Add(BinExpr):815- """Add the left to the right node."""816- operator = '+'817-818-819-class Sub(BinExpr):820- """Subtract the right from the left node."""821- operator = '-'822-823-824-class Mod(BinExpr):825- """Left modulo right."""826- operator = '%'827-828-829-class Pow(BinExpr):830- """Left to the power of right."""831- operator = '**'832-833-834-class And(BinExpr):835- """Short circuited AND."""836- operator = 'and'837-838- def as_const(self, eval_ctx=None):839- eval_ctx = get_eval_context(self, eval_ctx)840- return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)841-842-843-class Or(BinExpr):844- """Short circuited OR."""845- operator = 'or'846-847- def as_const(self, eval_ctx=None):848- eval_ctx = get_eval_context(self, eval_ctx)849- return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)850-851-852-class Not(UnaryExpr):853- """Negate the expression."""854- operator = 'not'855-856-857-class Neg(UnaryExpr):858- """Make the expression negative."""859- operator = '-'860-861-862-class Pos(UnaryExpr):863- """Make the expression positive (noop for most expressions)"""864- operator = '+'865-866-867-# Helpers for extensions868-869-870-class EnvironmentAttribute(Expr):871- """Loads an attribute from the environment object. This is useful for872- extensions that want to call a callback stored on the environment.873- """874- fields = ('name',)875-876-877-class ExtensionAttribute(Expr):878- """Returns the attribute of an extension bound to the environment.879- The identifier is the identifier of the :class:`Extension`.880-881- This node is usually constructed by calling the882- :meth:`~jinja2.ext.Extension.attr` method on an extension.883- """884- fields = ('identifier', 'name')885-886-887-class ImportedName(Expr):888- """If created with an import name the import name is returned on node889- access. For example ``ImportedName('cgi.escape')`` returns the `escape`890- function from the cgi module on evaluation. Imports are optimized by the891- compiler so there is no need to assign them to local variables.892- """893- fields = ('importname',)894-895-896-class InternalName(Expr):897- """An internal name in the compiler. You cannot create these nodes898- yourself but the parser provides a899- :meth:`~jinja2.parser.Parser.free_identifier` method that creates900- a new identifier for you. This identifier is not available from the901- template and is not threated specially by the compiler.902- """903- fields = ('name',)904-905- def __init__(self):906- raise TypeError('Can\'t create internal names. Use the '907- '`free_identifier` method on a parser.')908-909-910-class MarkSafe(Expr):911- """Mark the wrapped expression as safe (wrap it as `Markup`)."""912- fields = ('expr',)913-914- def as_const(self, eval_ctx=None):915- eval_ctx = get_eval_context(self, eval_ctx)916- return Markup(self.expr.as_const(eval_ctx))917-918-919-class MarkSafeIfAutoescape(Expr):920- """Mark the wrapped expression as safe (wrap it as `Markup`) but921- only if autoescaping is active.922-923- .. versionadded:: 2.5924- """925- fields = ('expr',)926-927- def as_const(self, eval_ctx=None):928- eval_ctx = get_eval_context(self, eval_ctx)929- if eval_ctx.volatile:930- raise Impossible()931- expr = self.expr.as_const(eval_ctx)932- if eval_ctx.autoescape:933- return Markup(expr)934- return expr935-936-937-class ContextReference(Expr):938- """Returns the current template context. It can be used like a939- :class:`Name` node, with a ``'load'`` ctx and will return the940- current :class:`~jinja2.runtime.Context` object.941-942- Here an example that assigns the current template name to a943- variable named `foo`::944-945- Assign(Name('foo', ctx='store'),946- Getattr(ContextReference(), 'name'))947-948- This is basically equivalent to using the949- :func:`~jinja2.contextfunction` decorator when using the950- high-level API, which causes a reference to the context to be passed951- as the first argument to a function.952- """953-954-955-class DerivedContextReference(Expr):956- """Return the current template context including locals. Behaves957- exactly like :class:`ContextReference`, but includes local958- variables, such as from a ``for`` loop.959-960- .. versionadded:: 2.11961- """962-963-964-class Continue(Stmt):965- """Continue a loop."""966-967-968-class Break(Stmt):969- """Break a loop."""970-971-972-class Scope(Stmt):973- """An artificial scope."""974- fields = ('body',)975-976-977-class OverlayScope(Stmt):978- """An overlay scope for extensions. This is a largely unoptimized scope979- that however can be used to introduce completely arbitrary variables into980- a sub scope from a dictionary or dictionary like object. The `context`981- field has to evaluate to a dictionary object.982-983- Example usage::984-985- OverlayScope(context=self.call_method('get_context'),986- body=[...])987-988- .. versionadded:: 2.10989- """990- fields = ('context', 'body')991-992-993-class EvalContextModifier(Stmt):994- """Modifies the eval context. For each option that should be modified,995- a :class:`Keyword` has to be added to the :attr:`options` list.996-997- Example to change the `autoescape` setting::998-999- EvalContextModifier(options=[Keyword('autoescape', Const(True))])1000- """1001- fields = ('options',)1002-1003-1004-class ScopedEvalContextModifier(EvalContextModifier):1005- """Modifies the eval context and reverts it later. Works exactly like1006- :class:`EvalContextModifier` but will only modify the1007- :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.1008- """1009- fields = ('body',)1010-1011-1012-# make sure nobody creates custom nodes1013-def _failing_new(*args, **kwargs):1014- raise TypeError('can\'t create custom node types')1015-NodeType.__new__ = staticmethod(_failing_new); del _failing_newdeleted:jinja2/optimizer.py-49 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.optimizer4- ~~~~~~~~~~~~~~~~5-6- The jinja optimizer is currently trying to constant fold a few expressions7- and modify the AST in place so that it should be easier to evaluate it.8-9- Because the AST does not contain all the scoping information and the10- compiler has to find that out, we cannot do all the optimizations we11- want. For example loop unrolling doesn't work because unrolled loops would12- have a different scoping.13-14- The solution would be a second syntax tree that has the scoping rules stored.15-16- :copyright: (c) 2017 by the Jinja Team.17- :license: BSD.18-"""19-from jinja2 import nodes20-from jinja2.visitor import NodeTransformer21-22-23-def optimize(node, environment):24- """The context hint can be used to perform an static optimization25- based on the context given."""26- optimizer = Optimizer(environment)27- return optimizer.visit(node)28-29-30-class Optimizer(NodeTransformer):31- def __init__(self, environment):32- self.environment = environment33-34- def generic_visit(self, node, *args, **kwargs):35- node = super(Optimizer, self).generic_visit(node, *args, **kwargs)36-37- # Do constant folding. Some other nodes besides Expr have38- # as_const, but folding them causes errors later on.39- if isinstance(node, nodes.Expr):40- try:41- return nodes.Const.from_untrusted(42- node.as_const(args[0] if args else None),43- lineno=node.lineno,44- environment=self.environment,45- )46- except nodes.Impossible:47- pass48-49- return nodedeleted:jinja2/parser.py-907 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.parser4- ~~~~~~~~~~~~~5-6- Implements the template parser.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-from jinja2 import nodes12-from jinja2.exceptions import TemplateSyntaxError, TemplateAssertionError13-from jinja2.lexer import describe_token, describe_token_expr14-from jinja2._compat import imap15-16-17-_statement_keywords = frozenset(['for', 'if', 'block', 'extends', 'print',18- 'macro', 'include', 'from', 'import',19- 'set', 'with', 'autoescape'])20-_compare_operators = frozenset(['eq', 'ne', 'lt', 'lteq', 'gt', 'gteq'])21-22-_math_nodes = {23- 'add': nodes.Add,24- 'sub': nodes.Sub,25- 'mul': nodes.Mul,26- 'div': nodes.Div,27- 'floordiv': nodes.FloorDiv,28- 'mod': nodes.Mod,29-}30-31-32-class Parser(object):33- """This is the central parsing class Jinja uses. It's passed to34- extensions and can be used to parse expressions or statements.35- """36-37- def __init__(self, environment, source, name=None, filename=None,38- state=None):39- self.environment = environment40- self.stream = environment._tokenize(source, name, filename, state)41- self.name = name42- self.filename = filename43- self.closed = False44- self.extensions = {}45- for extension in environment.iter_extensions():46- for tag in extension.tags:47- self.extensions[tag] = extension.parse48- self._last_identifier = 049- self._tag_stack = []50- self._end_token_stack = []51-52- def fail(self, msg, lineno=None, exc=TemplateSyntaxError):53- """Convenience method that raises `exc` with the message, passed54- line number or last line number as well as the current name and55- filename.56- """57- if lineno is None:58- lineno = self.stream.current.lineno59- raise exc(msg, lineno, self.name, self.filename)60-61- def _fail_ut_eof(self, name, end_token_stack, lineno):62- expected = []63- for exprs in end_token_stack:64- expected.extend(imap(describe_token_expr, exprs))65- if end_token_stack:66- currently_looking = ' or '.join(67- "'%s'" % describe_token_expr(expr)68- for expr in end_token_stack[-1])69- else:70- currently_looking = None71-72- if name is None:73- message = ['Unexpected end of template.']74- else:75- message = ['Encountered unknown tag \'%s\'.' % name]76-77- if currently_looking:78- if name is not None and name in expected:79- message.append('You probably made a nesting mistake. Jinja '80- 'is expecting this tag, but currently looking '81- 'for %s.' % currently_looking)82- else:83- message.append('Jinja was looking for the following tags: '84- '%s.' % currently_looking)85-86- if self._tag_stack:87- message.append('The innermost block that needs to be '88- 'closed is \'%s\'.' % self._tag_stack[-1])89-90- self.fail(' '.join(message), lineno)91-92- def fail_unknown_tag(self, name, lineno=None):93- """Called if the parser encounters an unknown tag. Tries to fail94- with a human readable error message that could help to identify95- the problem.96- """97- return self._fail_ut_eof(name, self._end_token_stack, lineno)98-99- def fail_eof(self, end_tokens=None, lineno=None):100- """Like fail_unknown_tag but for end of template situations."""101- stack = list(self._end_token_stack)102- if end_tokens is not None:103- stack.append(end_tokens)104- return self._fail_ut_eof(None, stack, lineno)105-106- def is_tuple_end(self, extra_end_rules=None):107- """Are we at the end of a tuple?"""108- if self.stream.current.type in ('variable_end', 'block_end', 'rparen'):109- return True110- elif extra_end_rules is not None:111- return self.stream.current.test_any(extra_end_rules)112- return False113-114- def free_identifier(self, lineno=None):115- """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""116- self._last_identifier += 1117- rv = object.__new__(nodes.InternalName)118- nodes.Node.__init__(rv, 'fi%d' % self._last_identifier, lineno=lineno)119- return rv120-121- def parse_statement(self):122- """Parse a single statement."""123- token = self.stream.current124- if token.type != 'name':125- self.fail('tag name expected', token.lineno)126- self._tag_stack.append(token.value)127- pop_tag = True128- try:129- if token.value in _statement_keywords:130- return getattr(self, 'parse_' + self.stream.current.value)()131- if token.value == 'call':132- return self.parse_call_block()133- if token.value == 'filter':134- return self.parse_filter_block()135- ext = self.extensions.get(token.value)136- if ext is not None:137- return ext(self)138-139- # did not work out, remove the token we pushed by accident140- # from the stack so that the unknown tag fail function can141- # produce a proper error message.142- self._tag_stack.pop()143- pop_tag = False144- self.fail_unknown_tag(token.value, token.lineno)145- finally:146- if pop_tag:147- self._tag_stack.pop()148-149- def parse_statements(self, end_tokens, drop_needle=False):150- """Parse multiple statements into a list until one of the end tokens151- is reached. This is used to parse the body of statements as it also152- parses template data if appropriate. The parser checks first if the153- current token is a colon and skips it if there is one. Then it checks154- for the block end and parses until if one of the `end_tokens` is155- reached. Per default the active token in the stream at the end of156- the call is the matched end token. If this is not wanted `drop_needle`157- can be set to `True` and the end token is removed.158- """159- # the first token may be a colon for python compatibility160- self.stream.skip_if('colon')161-162- # in the future it would be possible to add whole code sections163- # by adding some sort of end of statement token and parsing those here.164- self.stream.expect('block_end')165- result = self.subparse(end_tokens)166-167- # we reached the end of the template too early, the subparser168- # does not check for this, so we do that now169- if self.stream.current.type == 'eof':170- self.fail_eof(end_tokens)171-172- if drop_needle:173- next(self.stream)174- return result175-176- def parse_set(self):177- """Parse an assign statement."""178- lineno = next(self.stream).lineno179- target = self.parse_assign_target(with_namespace=True)180- if self.stream.skip_if('assign'):181- expr = self.parse_tuple()182- return nodes.Assign(target, expr, lineno=lineno)183- filter_node = self.parse_filter(None)184- body = self.parse_statements(('name:endset',),185- drop_needle=True)186- return nodes.AssignBlock(target, filter_node, body, lineno=lineno)187-188- def parse_for(self):189- """Parse a for loop."""190- lineno = self.stream.expect('name:for').lineno191- target = self.parse_assign_target(extra_end_rules=('name:in',))192- self.stream.expect('name:in')193- iter = self.parse_tuple(with_condexpr=False,194- extra_end_rules=('name:recursive',))195- test = None196- if self.stream.skip_if('name:if'):197- test = self.parse_expression()198- recursive = self.stream.skip_if('name:recursive')199- body = self.parse_statements(('name:endfor', 'name:else'))200- if next(self.stream).value == 'endfor':201- else_ = []202- else:203- else_ = self.parse_statements(('name:endfor',), drop_needle=True)204- return nodes.For(target, iter, body, else_, test,205- recursive, lineno=lineno)206-207- def parse_if(self):208- """Parse an if construct."""209- node = result = nodes.If(lineno=self.stream.expect('name:if').lineno)210- while 1:211- node.test = self.parse_tuple(with_condexpr=False)212- node.body = self.parse_statements(('name:elif', 'name:else',213- 'name:endif'))214- node.elif_ = []215- node.else_ = []216- token = next(self.stream)217- if token.test('name:elif'):218- node = nodes.If(lineno=self.stream.current.lineno)219- result.elif_.append(node)220- continue221- elif token.test('name:else'):222- result.else_ = self.parse_statements(('name:endif',),223- drop_needle=True)224- break225- return result226-227- def parse_with(self):228- node = nodes.With(lineno=next(self.stream).lineno)229- targets = []230- values = []231- while self.stream.current.type != 'block_end':232- lineno = self.stream.current.lineno233- if targets:234- self.stream.expect('comma')235- target = self.parse_assign_target()236- target.set_ctx('param')237- targets.append(target)238- self.stream.expect('assign')239- values.append(self.parse_expression())240- node.targets = targets241- node.values = values242- node.body = self.parse_statements(('name:endwith',),243- drop_needle=True)244- return node245-246- def parse_autoescape(self):247- node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)248- node.options = [249- nodes.Keyword('autoescape', self.parse_expression())250- ]251- node.body = self.parse_statements(('name:endautoescape',),252- drop_needle=True)253- return nodes.Scope([node])254-255- def parse_block(self):256- node = nodes.Block(lineno=next(self.stream).lineno)257- node.name = self.stream.expect('name').value258- node.scoped = self.stream.skip_if('name:scoped')259-260- # common problem people encounter when switching from django261- # to jinja. we do not support hyphens in block names, so let's262- # raise a nicer error message in that case.263- if self.stream.current.type == 'sub':264- self.fail('Block names in Jinja have to be valid Python '265- 'identifiers and may not contain hyphens, use an '266- 'underscore instead.')267-268- node.body = self.parse_statements(('name:endblock',), drop_needle=True)269- self.stream.skip_if('name:' + node.name)270- return node271-272- def parse_extends(self):273- node = nodes.Extends(lineno=next(self.stream).lineno)274- node.template = self.parse_expression()275- return node276-277- def parse_import_context(self, node, default):278- if self.stream.current.test_any('name:with', 'name:without') and \279- self.stream.look().test('name:context'):280- node.with_context = next(self.stream).value == 'with'281- self.stream.skip()282- else:283- node.with_context = default284- return node285-286- def parse_include(self):287- node = nodes.Include(lineno=next(self.stream).lineno)288- node.template = self.parse_expression()289- if self.stream.current.test('name:ignore') and \290- self.stream.look().test('name:missing'):291- node.ignore_missing = True292- self.stream.skip(2)293- else:294- node.ignore_missing = False295- return self.parse_import_context(node, True)296-297- def parse_import(self):298- node = nodes.Import(lineno=next(self.stream).lineno)299- node.template = self.parse_expression()300- self.stream.expect('name:as')301- node.target = self.parse_assign_target(name_only=True).name302- return self.parse_import_context(node, False)303-304- def parse_from(self):305- node = nodes.FromImport(lineno=next(self.stream).lineno)306- node.template = self.parse_expression()307- self.stream.expect('name:import')308- node.names = []309-310- def parse_context():311- if self.stream.current.value in ('with', 'without') and \312- self.stream.look().test('name:context'):313- node.with_context = next(self.stream).value == 'with'314- self.stream.skip()315- return True316- return False317-318- while 1:319- if node.names:320- self.stream.expect('comma')321- if self.stream.current.type == 'name':322- if parse_context():323- break324- target = self.parse_assign_target(name_only=True)325- if target.name.startswith('_'):326- self.fail('names starting with an underline can not '327- 'be imported', target.lineno,328- exc=TemplateAssertionError)329- if self.stream.skip_if('name:as'):330- alias = self.parse_assign_target(name_only=True)331- node.names.append((target.name, alias.name))332- else:333- node.names.append(target.name)334- if parse_context() or self.stream.current.type != 'comma':335- break336- else:337- self.stream.expect('name')338- if not hasattr(node, 'with_context'):339- node.with_context = False340- return node341-342- def parse_signature(self, node):343- node.args = args = []344- node.defaults = defaults = []345- self.stream.expect('lparen')346- while self.stream.current.type != 'rparen':347- if args:348- self.stream.expect('comma')349- arg = self.parse_assign_target(name_only=True)350- arg.set_ctx('param')351- if self.stream.skip_if('assign'):352- defaults.append(self.parse_expression())353- elif defaults:354- self.fail('non-default argument follows default argument')355- args.append(arg)356- self.stream.expect('rparen')357-358- def parse_call_block(self):359- node = nodes.CallBlock(lineno=next(self.stream).lineno)360- if self.stream.current.type == 'lparen':361- self.parse_signature(node)362- else:363- node.args = []364- node.defaults = []365-366- node.call = self.parse_expression()367- if not isinstance(node.call, nodes.Call):368- self.fail('expected call', node.lineno)369- node.body = self.parse_statements(('name:endcall',), drop_needle=True)370- return node371-372- def parse_filter_block(self):373- node = nodes.FilterBlock(lineno=next(self.stream).lineno)374- node.filter = self.parse_filter(None, start_inline=True)375- node.body = self.parse_statements(('name:endfilter',),376- drop_needle=True)377- return node378-379- def parse_macro(self):380- node = nodes.Macro(lineno=next(self.stream).lineno)381- node.name = self.parse_assign_target(name_only=True).name382- self.parse_signature(node)383- node.body = self.parse_statements(('name:endmacro',),384- drop_needle=True)385- return node386-387- def parse_print(self):388- node = nodes.Output(lineno=next(self.stream).lineno)389- node.nodes = []390- while self.stream.current.type != 'block_end':391- if node.nodes:392- self.stream.expect('comma')393- node.nodes.append(self.parse_expression())394- return node395-396- def parse_assign_target(self, with_tuple=True, name_only=False,397- extra_end_rules=None, with_namespace=False):398- """Parse an assignment target. As Jinja allows assignments to399- tuples, this function can parse all allowed assignment targets. Per400- default assignments to tuples are parsed, that can be disable however401- by setting `with_tuple` to `False`. If only assignments to names are402- wanted `name_only` can be set to `True`. The `extra_end_rules`403- parameter is forwarded to the tuple parsing function. If404- `with_namespace` is enabled, a namespace assignment may be parsed.405- """406- if with_namespace and self.stream.look().type == 'dot':407- token = self.stream.expect('name')408- next(self.stream) # dot409- attr = self.stream.expect('name')410- target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)411- elif name_only:412- token = self.stream.expect('name')413- target = nodes.Name(token.value, 'store', lineno=token.lineno)414- else:415- if with_tuple:416- target = self.parse_tuple(simplified=True,417- extra_end_rules=extra_end_rules)418- else:419- target = self.parse_primary()420- target.set_ctx('store')421- if not target.can_assign():422- self.fail('can\'t assign to %r' % target.__class__.423- __name__.lower(), target.lineno)424- return target425-426- def parse_expression(self, with_condexpr=True):427- """Parse an expression. Per default all expressions are parsed, if428- the optional `with_condexpr` parameter is set to `False` conditional429- expressions are not parsed.430- """431- if with_condexpr:432- return self.parse_condexpr()433- return self.parse_or()434-435- def parse_condexpr(self):436- lineno = self.stream.current.lineno437- expr1 = self.parse_or()438- while self.stream.skip_if('name:if'):439- expr2 = self.parse_or()440- if self.stream.skip_if('name:else'):441- expr3 = self.parse_condexpr()442- else:443- expr3 = None444- expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)445- lineno = self.stream.current.lineno446- return expr1447-448- def parse_or(self):449- lineno = self.stream.current.lineno450- left = self.parse_and()451- while self.stream.skip_if('name:or'):452- right = self.parse_and()453- left = nodes.Or(left, right, lineno=lineno)454- lineno = self.stream.current.lineno455- return left456-457- def parse_and(self):458- lineno = self.stream.current.lineno459- left = self.parse_not()460- while self.stream.skip_if('name:and'):461- right = self.parse_not()462- left = nodes.And(left, right, lineno=lineno)463- lineno = self.stream.current.lineno464- return left465-466- def parse_not(self):467- if self.stream.current.test('name:not'):468- lineno = next(self.stream).lineno469- return nodes.Not(self.parse_not(), lineno=lineno)470- return self.parse_compare()471-472- def parse_compare(self):473- lineno = self.stream.current.lineno474- expr = self.parse_math1()475- ops = []476- while 1:477- token_type = self.stream.current.type478- if token_type in _compare_operators:479- next(self.stream)480- ops.append(nodes.Operand(token_type, self.parse_math1()))481- elif self.stream.skip_if('name:in'):482- ops.append(nodes.Operand('in', self.parse_math1()))483- elif (self.stream.current.test('name:not') and484- self.stream.look().test('name:in')):485- self.stream.skip(2)486- ops.append(nodes.Operand('notin', self.parse_math1()))487- else:488- break489- lineno = self.stream.current.lineno490- if not ops:491- return expr492- return nodes.Compare(expr, ops, lineno=lineno)493-494- def parse_math1(self):495- lineno = self.stream.current.lineno496- left = self.parse_concat()497- while self.stream.current.type in ('add', 'sub'):498- cls = _math_nodes[self.stream.current.type]499- next(self.stream)500- right = self.parse_concat()501- left = cls(left, right, lineno=lineno)502- lineno = self.stream.current.lineno503- return left504-505- def parse_concat(self):506- lineno = self.stream.current.lineno507- args = [self.parse_math2()]508- while self.stream.current.type == 'tilde':509- next(self.stream)510- args.append(self.parse_math2())511- if len(args) == 1:512- return args[0]513- return nodes.Concat(args, lineno=lineno)514-515- def parse_math2(self):516- lineno = self.stream.current.lineno517- left = self.parse_pow()518- while self.stream.current.type in ('mul', 'div', 'floordiv', 'mod'):519- cls = _math_nodes[self.stream.current.type]520- next(self.stream)521- right = self.parse_pow()522- left = cls(left, right, lineno=lineno)523- lineno = self.stream.current.lineno524- return left525-526- def parse_pow(self):527- lineno = self.stream.current.lineno528- left = self.parse_unary()529- while self.stream.current.type == 'pow':530- next(self.stream)531- right = self.parse_unary()532- left = nodes.Pow(left, right, lineno=lineno)533- lineno = self.stream.current.lineno534- return left535-536- def parse_unary(self, with_filter=True):537- token_type = self.stream.current.type538- lineno = self.stream.current.lineno539- if token_type == 'sub':540- next(self.stream)541- node = nodes.Neg(self.parse_unary(False), lineno=lineno)542- elif token_type == 'add':543- next(self.stream)544- node = nodes.Pos(self.parse_unary(False), lineno=lineno)545- else:546- node = self.parse_primary()547- node = self.parse_postfix(node)548- if with_filter:549- node = self.parse_filter_expr(node)550- return node551-552- def parse_primary(self):553- token = self.stream.current554- if token.type == 'name':555- if token.value in ('true', 'false', 'True', 'False'):556- node = nodes.Const(token.value in ('true', 'True'),557- lineno=token.lineno)558- elif token.value in ('none', 'None'):559- node = nodes.Const(None, lineno=token.lineno)560- else:561- node = nodes.Name(token.value, 'load', lineno=token.lineno)562- next(self.stream)563- elif token.type == 'string':564- next(self.stream)565- buf = [token.value]566- lineno = token.lineno567- while self.stream.current.type == 'string':568- buf.append(self.stream.current.value)569- next(self.stream)570- node = nodes.Const(''.join(buf), lineno=lineno)571- elif token.type in ('integer', 'float'):572- next(self.stream)573- node = nodes.Const(token.value, lineno=token.lineno)574- elif token.type == 'lparen':575- next(self.stream)576- node = self.parse_tuple(explicit_parentheses=True)577- self.stream.expect('rparen')578- elif token.type == 'lbracket':579- node = self.parse_list()580- elif token.type == 'lbrace':581- node = self.parse_dict()582- else:583- self.fail("unexpected '%s'" % describe_token(token), token.lineno)584- return node585-586- def parse_tuple(self, simplified=False, with_condexpr=True,587- extra_end_rules=None, explicit_parentheses=False):588- """Works like `parse_expression` but if multiple expressions are589- delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.590- This method could also return a regular expression instead of a tuple591- if no commas where found.592-593- The default parsing mode is a full tuple. If `simplified` is `True`594- only names and literals are parsed. The `no_condexpr` parameter is595- forwarded to :meth:`parse_expression`.596-597- Because tuples do not require delimiters and may end in a bogus comma598- an extra hint is needed that marks the end of a tuple. For example599- for loops support tuples between `for` and `in`. In that case the600- `extra_end_rules` is set to ``['name:in']``.601-602- `explicit_parentheses` is true if the parsing was triggered by an603- expression in parentheses. This is used to figure out if an empty604- tuple is a valid expression or not.605- """606- lineno = self.stream.current.lineno607- if simplified:608- parse = self.parse_primary609- elif with_condexpr:610- parse = self.parse_expression611- else:612- parse = lambda: self.parse_expression(with_condexpr=False)613- args = []614- is_tuple = False615- while 1:616- if args:617- self.stream.expect('comma')618- if self.is_tuple_end(extra_end_rules):619- break620- args.append(parse())621- if self.stream.current.type == 'comma':622- is_tuple = True623- else:624- break625- lineno = self.stream.current.lineno626-627- if not is_tuple:628- if args:629- return args[0]630-631- # if we don't have explicit parentheses, an empty tuple is632- # not a valid expression. This would mean nothing (literally633- # nothing) in the spot of an expression would be an empty634- # tuple.635- if not explicit_parentheses:636- self.fail('Expected an expression, got \'%s\'' %637- describe_token(self.stream.current))638-639- return nodes.Tuple(args, 'load', lineno=lineno)640-641- def parse_list(self):642- token = self.stream.expect('lbracket')643- items = []644- while self.stream.current.type != 'rbracket':645- if items:646- self.stream.expect('comma')647- if self.stream.current.type == 'rbracket':648- break649- items.append(self.parse_expression())650- self.stream.expect('rbracket')651- return nodes.List(items, lineno=token.lineno)652-653- def parse_dict(self):654- token = self.stream.expect('lbrace')655- items = []656- while self.stream.current.type != 'rbrace':657- if items:658- self.stream.expect('comma')659- if self.stream.current.type == 'rbrace':660- break661- key = self.parse_expression()662- self.stream.expect('colon')663- value = self.parse_expression()664- items.append(nodes.Pair(key, value, lineno=key.lineno))665- self.stream.expect('rbrace')666- return nodes.Dict(items, lineno=token.lineno)667-668- def parse_postfix(self, node):669- while 1:670- token_type = self.stream.current.type671- if token_type == 'dot' or token_type == 'lbracket':672- node = self.parse_subscript(node)673- # calls are valid both after postfix expressions (getattr674- # and getitem) as well as filters and tests675- elif token_type == 'lparen':676- node = self.parse_call(node)677- else:678- break679- return node680-681- def parse_filter_expr(self, node):682- while 1:683- token_type = self.stream.current.type684- if token_type == 'pipe':685- node = self.parse_filter(node)686- elif token_type == 'name' and self.stream.current.value == 'is':687- node = self.parse_test(node)688- # calls are valid both after postfix expressions (getattr689- # and getitem) as well as filters and tests690- elif token_type == 'lparen':691- node = self.parse_call(node)692- else:693- break694- return node695-696- def parse_subscript(self, node):697- token = next(self.stream)698- if token.type == 'dot':699- attr_token = self.stream.current700- next(self.stream)701- if attr_token.type == 'name':702- return nodes.Getattr(node, attr_token.value, 'load',703- lineno=token.lineno)704- elif attr_token.type != 'integer':705- self.fail('expected name or number', attr_token.lineno)706- arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)707- return nodes.Getitem(node, arg, 'load', lineno=token.lineno)708- if token.type == 'lbracket':709- args = []710- while self.stream.current.type != 'rbracket':711- if args:712- self.stream.expect('comma')713- args.append(self.parse_subscribed())714- self.stream.expect('rbracket')715- if len(args) == 1:716- arg = args[0]717- else:718- arg = nodes.Tuple(args, 'load', lineno=token.lineno)719- return nodes.Getitem(node, arg, 'load', lineno=token.lineno)720- self.fail('expected subscript expression', token.lineno)721-722- def parse_subscribed(self):723- lineno = self.stream.current.lineno724-725- if self.stream.current.type == 'colon':726- next(self.stream)727- args = [None]728- else:729- node = self.parse_expression()730- if self.stream.current.type != 'colon':731- return node732- next(self.stream)733- args = [node]734-735- if self.stream.current.type == 'colon':736- args.append(None)737- elif self.stream.current.type not in ('rbracket', 'comma'):738- args.append(self.parse_expression())739- else:740- args.append(None)741-742- if self.stream.current.type == 'colon':743- next(self.stream)744- if self.stream.current.type not in ('rbracket', 'comma'):745- args.append(self.parse_expression())746- else:747- args.append(None)748- else:749- args.append(None)750-751- return nodes.Slice(lineno=lineno, *args)752-753- def parse_call(self, node):754- token = self.stream.expect('lparen')755- args = []756- kwargs = []757- dyn_args = dyn_kwargs = None758- require_comma = False759-760- def ensure(expr):761- if not expr:762- self.fail('invalid syntax for function call expression',763- token.lineno)764-765- while self.stream.current.type != 'rparen':766- if require_comma:767- self.stream.expect('comma')768- # support for trailing comma769- if self.stream.current.type == 'rparen':770- break771- if self.stream.current.type == 'mul':772- ensure(dyn_args is None and dyn_kwargs is None)773- next(self.stream)774- dyn_args = self.parse_expression()775- elif self.stream.current.type == 'pow':776- ensure(dyn_kwargs is None)777- next(self.stream)778- dyn_kwargs = self.parse_expression()779- else:780- if self.stream.current.type == 'name' and \781- self.stream.look().type == 'assign':782- # Parsing a kwarg783- ensure(dyn_kwargs is None)784- key = self.stream.current.value785- self.stream.skip(2)786- value = self.parse_expression()787- kwargs.append(nodes.Keyword(key, value,788- lineno=value.lineno))789- else:790- # Parsing an arg791- ensure(dyn_args is None and dyn_kwargs is None and not kwargs)792- args.append(self.parse_expression())793-794- require_comma = True795- self.stream.expect('rparen')796-797- if node is None:798- return args, kwargs, dyn_args, dyn_kwargs799- return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs,800- lineno=token.lineno)801-802- def parse_filter(self, node, start_inline=False):803- while self.stream.current.type == 'pipe' or start_inline:804- if not start_inline:805- next(self.stream)806- token = self.stream.expect('name')807- name = token.value808- while self.stream.current.type == 'dot':809- next(self.stream)810- name += '.' + self.stream.expect('name').value811- if self.stream.current.type == 'lparen':812- args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)813- else:814- args = []815- kwargs = []816- dyn_args = dyn_kwargs = None817- node = nodes.Filter(node, name, args, kwargs, dyn_args,818- dyn_kwargs, lineno=token.lineno)819- start_inline = False820- return node821-822- def parse_test(self, node):823- token = next(self.stream)824- if self.stream.current.test('name:not'):825- next(self.stream)826- negated = True827- else:828- negated = False829- name = self.stream.expect('name').value830- while self.stream.current.type == 'dot':831- next(self.stream)832- name += '.' + self.stream.expect('name').value833- dyn_args = dyn_kwargs = None834- kwargs = []835- if self.stream.current.type == 'lparen':836- args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)837- elif (self.stream.current.type in ('name', 'string', 'integer',838- 'float', 'lparen', 'lbracket',839- 'lbrace') and not840- self.stream.current.test_any('name:else', 'name:or',841- 'name:and')):842- if self.stream.current.test('name:is'):843- self.fail('You cannot chain multiple tests with is')844- arg_node = self.parse_primary()845- arg_node = self.parse_postfix(arg_node)846- args = [arg_node]847- else:848- args = []849- node = nodes.Test(node, name, args, kwargs, dyn_args,850- dyn_kwargs, lineno=token.lineno)851- if negated:852- node = nodes.Not(node, lineno=token.lineno)853- return node854-855- def subparse(self, end_tokens=None):856- body = []857- data_buffer = []858- add_data = data_buffer.append859-860- if end_tokens is not None:861- self._end_token_stack.append(end_tokens)862-863- def flush_data():864- if data_buffer:865- lineno = data_buffer[0].lineno866- body.append(nodes.Output(data_buffer[:], lineno=lineno))867- del data_buffer[:]868-869- try:870- while self.stream:871- token = self.stream.current872- if token.type == 'data':873- if token.value:874- add_data(nodes.TemplateData(token.value,875- lineno=token.lineno))876- next(self.stream)877- elif token.type == 'variable_begin':878- next(self.stream)879- add_data(self.parse_tuple(with_condexpr=True))880- self.stream.expect('variable_end')881- elif token.type == 'block_begin':882- flush_data()883- next(self.stream)884- if end_tokens is not None and \885- self.stream.current.test_any(*end_tokens):886- return body887- rv = self.parse_statement()888- if isinstance(rv, list):889- body.extend(rv)890- else:891- body.append(rv)892- self.stream.expect('block_end')893- else:894- raise AssertionError('internal parsing error')895-896- flush_data()897- finally:898- if end_tokens is not None:899- self._end_token_stack.pop()900-901- return body902-903- def parse(self):904- """Parse the whole template into a `Template` node."""905- result = nodes.Template(self.subparse(), lineno=1)906- result.set_environment(self.environment)907- return resultdeleted:jinja2/runtime.py-906 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.runtime4- ~~~~~~~~~~~~~~5-6- Runtime helpers.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD.10-"""11-import sys12-13-from itertools import chain14-from types import MethodType15-16-from jinja2.nodes import EvalContext17-from jinja2.utils import Markup, soft_unicode, escape, missing, concat, \18- internalcode, object_type_repr, evalcontextfunction, Namespace19-from jinja2.exceptions import UndefinedError, TemplateRuntimeError, \20- TemplateNotFound21-from jinja2._compat import imap, text_type, iteritems, \22- implements_iterator, implements_to_string, string_types, PY2, \23- with_metaclass, abc24-25-26-# these variables are exported to the template runtime27-__all__ = ['LoopContext', 'TemplateReference', 'Macro', 'Markup',28- 'TemplateRuntimeError', 'missing', 'concat', 'escape',29- 'markup_join', 'unicode_join', 'to_string', 'identity',30- 'TemplateNotFound', 'Namespace', 'Undefined']31-32-#: the name of the function that is used to convert something into33-#: a string. We can just use the text type here.34-to_string = text_type35-36-#: the identity function. Useful for certain things in the environment37-identity = lambda x: x38-39-_first_iteration = object()40-_last_iteration = object()41-42-43-def markup_join(seq):44- """Concatenation that escapes if necessary and converts to unicode."""45- buf = []46- iterator = imap(soft_unicode, seq)47- for arg in iterator:48- buf.append(arg)49- if hasattr(arg, '__html__'):50- return Markup(u'').join(chain(buf, iterator))51- return concat(buf)52-53-54-def unicode_join(seq):55- """Simple args to unicode conversion and concatenation."""56- return concat(imap(text_type, seq))57-58-59-def new_context(environment, template_name, blocks, vars=None,60- shared=None, globals=None, locals=None):61- """Internal helper for context creation."""62- if vars is None:63- vars = {}64- if shared:65- parent = vars66- else:67- parent = dict(globals or (), **vars)68- if locals:69- # if the parent is shared a copy should be created because70- # we don't want to modify the dict passed71- if shared:72- parent = dict(parent)73- for key, value in iteritems(locals):74- if value is not missing:75- parent[key] = value76- return environment.context_class(environment, parent, template_name,77- blocks)78-79-80-class TemplateReference(object):81- """The `self` in templates."""82-83- def __init__(self, context):84- self.__context = context85-86- def __getitem__(self, name):87- blocks = self.__context.blocks[name]88- return BlockReference(name, self.__context, blocks, 0)89-90- def __repr__(self):91- return '<%s %r>' % (92- self.__class__.__name__,93- self.__context.name94- )95-96-97-def _get_func(x):98- return getattr(x, '__func__', x)99-100-101-class ContextMeta(type):102-103- def __new__(cls, name, bases, d):104- rv = type.__new__(cls, name, bases, d)105- if bases == ():106- return rv107-108- resolve = _get_func(rv.resolve)109- default_resolve = _get_func(Context.resolve)110- resolve_or_missing = _get_func(rv.resolve_or_missing)111- default_resolve_or_missing = _get_func(Context.resolve_or_missing)112-113- # If we have a changed resolve but no changed default or missing114- # resolve we invert the call logic.115- if resolve is not default_resolve and \116- resolve_or_missing is default_resolve_or_missing:117- rv._legacy_resolve_mode = True118- elif resolve is default_resolve and \119- resolve_or_missing is default_resolve_or_missing:120- rv._fast_resolve_mode = True121-122- return rv123-124-125-def resolve_or_missing(context, key, missing=missing):126- if key in context.vars:127- return context.vars[key]128- if key in context.parent:129- return context.parent[key]130- return missing131-132-133-class Context(with_metaclass(ContextMeta)):134- """The template context holds the variables of a template. It stores the135- values passed to the template and also the names the template exports.136- Creating instances is neither supported nor useful as it's created137- automatically at various stages of the template evaluation and should not138- be created by hand.139-140- The context is immutable. Modifications on :attr:`parent` **must not**141- happen and modifications on :attr:`vars` are allowed from generated142- template code only. Template filters and global functions marked as143- :func:`contextfunction`\\s get the active context passed as first argument144- and are allowed to access the context read-only.145-146- The template context supports read only dict operations (`get`,147- `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,148- `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`149- method that doesn't fail with a `KeyError` but returns an150- :class:`Undefined` object for missing variables.151- """152- # XXX: we want to eventually make this be a deprecation warning and153- # remove it.154- _legacy_resolve_mode = False155- _fast_resolve_mode = False156-157- def __init__(self, environment, parent, name, blocks):158- self.parent = parent159- self.vars = {}160- self.environment = environment161- self.eval_ctx = EvalContext(self.environment, name)162- self.exported_vars = set()163- self.name = name164-165- # create the initial mapping of blocks. Whenever template inheritance166- # takes place the runtime will update this mapping with the new blocks167- # from the template.168- self.blocks = dict((k, [v]) for k, v in iteritems(blocks))169-170- # In case we detect the fast resolve mode we can set up an alias171- # here that bypasses the legacy code logic.172- if self._fast_resolve_mode:173- self.resolve_or_missing = MethodType(resolve_or_missing, self)174-175- def super(self, name, current):176- """Render a parent block."""177- try:178- blocks = self.blocks[name]179- index = blocks.index(current) + 1180- blocks[index]181- except LookupError:182- return self.environment.undefined('there is no parent block '183- 'called %r.' % name,184- name='super')185- return BlockReference(name, self, blocks, index)186-187- def get(self, key, default=None):188- """Returns an item from the template context, if it doesn't exist189- `default` is returned.190- """191- try:192- return self[key]193- except KeyError:194- return default195-196- def resolve(self, key):197- """Looks up a variable like `__getitem__` or `get` but returns an198- :class:`Undefined` object with the name of the name looked up.199- """200- if self._legacy_resolve_mode:201- rv = resolve_or_missing(self, key)202- else:203- rv = self.resolve_or_missing(key)204- if rv is missing:205- return self.environment.undefined(name=key)206- return rv207-208- def resolve_or_missing(self, key):209- """Resolves a variable like :meth:`resolve` but returns the210- special `missing` value if it cannot be found.211- """212- if self._legacy_resolve_mode:213- rv = self.resolve(key)214- if isinstance(rv, Undefined):215- rv = missing216- return rv217- return resolve_or_missing(self, key)218-219- def get_exported(self):220- """Get a new dict with the exported variables."""221- return dict((k, self.vars[k]) for k in self.exported_vars)222-223- def get_all(self):224- """Return the complete context as dict including the exported225- variables. For optimizations reasons this might not return an226- actual copy so be careful with using it.227- """228- if not self.vars:229- return self.parent230- if not self.parent:231- return self.vars232- return dict(self.parent, **self.vars)233-234- @internalcode235- def call(__self, __obj, *args, **kwargs):236- """Call the callable with the arguments and keyword arguments237- provided but inject the active context or environment as first238- argument if the callable is a :func:`contextfunction` or239- :func:`environmentfunction`.240- """241- if __debug__:242- __traceback_hide__ = True # noqa243-244- # Allow callable classes to take a context245- if hasattr(__obj, '__call__'):246- fn = __obj.__call__247- for fn_type in ('contextfunction',248- 'evalcontextfunction',249- 'environmentfunction'):250- if hasattr(fn, fn_type):251- __obj = fn252- break253-254- if callable(__obj):255- if getattr(__obj, 'contextfunction', 0):256- args = (__self,) + args257- elif getattr(__obj, 'evalcontextfunction', 0):258- args = (__self.eval_ctx,) + args259- elif getattr(__obj, 'environmentfunction', 0):260- args = (__self.environment,) + args261- try:262- return __obj(*args, **kwargs)263- except StopIteration:264- return __self.environment.undefined('value was undefined because '265- 'a callable raised a '266- 'StopIteration exception')267-268- def derived(self, locals=None):269- """Internal helper function to create a derived context. This is270- used in situations where the system needs a new context in the same271- template that is independent.272- """273- context = new_context(self.environment, self.name, {},274- self.get_all(), True, None, locals)275- context.eval_ctx = self.eval_ctx276- context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))277- return context278-279- def _all(meth):280- proxy = lambda self: getattr(self.get_all(), meth)()281- proxy.__doc__ = getattr(dict, meth).__doc__282- proxy.__name__ = meth283- return proxy284-285- keys = _all('keys')286- values = _all('values')287- items = _all('items')288-289- # not available on python 3290- if PY2:291- iterkeys = _all('iterkeys')292- itervalues = _all('itervalues')293- iteritems = _all('iteritems')294- del _all295-296- def __contains__(self, name):297- return name in self.vars or name in self.parent298-299- def __getitem__(self, key):300- """Lookup a variable or raise `KeyError` if the variable is301- undefined.302- """303- item = self.resolve_or_missing(key)304- if item is missing:305- raise KeyError(key)306- return item307-308- def __repr__(self):309- return '<%s %s of %r>' % (310- self.__class__.__name__,311- repr(self.get_all()),312- self.name313- )314-315-316-abc.Mapping.register(Context)317-318-319-class BlockReference(object):320- """One block on a template reference."""321-322- def __init__(self, name, context, stack, depth):323- self.name = name324- self._context = context325- self._stack = stack326- self._depth = depth327-328- @property329- def super(self):330- """Super the block."""331- if self._depth + 1 >= len(self._stack):332- return self._context.environment. \333- undefined('there is no parent block called %r.' %334- self.name, name='super')335- return BlockReference(self.name, self._context, self._stack,336- self._depth + 1)337-338- @internalcode339- def __call__(self):340- rv = concat(self._stack[self._depth](self._context))341- if self._context.eval_ctx.autoescape:342- rv = Markup(rv)343- return rv344-345-346-@implements_iterator347-class LoopContext:348- """A wrapper iterable for dynamic ``for`` loops, with information349- about the loop and iteration.350- """351-352- #: Current iteration of the loop, starting at 0.353- index0 = -1354-355- _length = None356- _after = missing357- _current = missing358- _before = missing359- _last_changed_value = missing360-361- def __init__(self, iterable, undefined, recurse=None, depth0=0):362- """363- :param iterable: Iterable to wrap.364- :param undefined: :class:`Undefined` class to use for next and365- previous items.366- :param recurse: The function to render the loop body when the367- loop is marked recursive.368- :param depth0: Incremented when looping recursively.369- """370- self._iterable = iterable371- self._iterator = self._to_iterator(iterable)372- self._undefined = undefined373- self._recurse = recurse374- #: How many levels deep a recursive loop currently is, starting at 0.375- self.depth0 = depth0376-377- @staticmethod378- def _to_iterator(iterable):379- return iter(iterable)380-381- @property382- def length(self):383- """Length of the iterable.384-385- If the iterable is a generator or otherwise does not have a386- size, it is eagerly evaluated to get a size.387- """388- if self._length is not None:389- return self._length390-391- try:392- self._length = len(self._iterable)393- except TypeError:394- iterable = list(self._iterator)395- self._iterator = self._to_iterator(iterable)396- self._length = len(iterable) + self.index + (self._after is not missing)397-398- return self._length399-400- def __len__(self):401- return self.length402-403- @property404- def depth(self):405- """How many levels deep a recursive loop currently is, starting at 1."""406- return self.depth0 + 1407-408- @property409- def index(self):410- """Current iteration of the loop, starting at 1."""411- return self.index0 + 1412-413- @property414- def revindex0(self):415- """Number of iterations from the end of the loop, ending at 0.416-417- Requires calculating :attr:`length`.418- """419- return self.length - self.index420-421- @property422- def revindex(self):423- """Number of iterations from the end of the loop, ending at 1.424-425- Requires calculating :attr:`length`.426- """427- return self.length - self.index0428-429- @property430- def first(self):431- """Whether this is the first iteration of the loop."""432- return self.index0 == 0433-434- def _peek_next(self):435- """Return the next element in the iterable, or :data:`missing`436- if the iterable is exhausted. Only peeks one item ahead, caching437- the result in :attr:`_last` for use in subsequent checks. The438- cache is reset when :meth:`__next__` is called.439- """440- if self._after is not missing:441- return self._after442-443- self._after = next(self._iterator, missing)444- return self._after445-446- @property447- def last(self):448- """Whether this is the last iteration of the loop.449-450- Causes the iterable to advance early. See451- :func:`itertools.groupby` for issues this can cause.452- The :func:`groupby` filter avoids that issue.453- """454- return self._peek_next() is missing455-456- @property457- def previtem(self):458- """The item in the previous iteration. Undefined during the459- first iteration.460- """461- if self.first:462- return self._undefined("there is no previous item")463-464- return self._before465-466- @property467- def nextitem(self):468- """The item in the next iteration. Undefined during the last469- iteration.470-471- Causes the iterable to advance early. See472- :func:`itertools.groupby` for issues this can cause.473- The :func:`groupby` filter avoids that issue.474- """475- rv = self._peek_next()476-477- if rv is missing:478- return self._undefined("there is no next item")479-480- return rv481-482- def cycle(self, *args):483- """Return a value from the given args, cycling through based on484- the current :attr:`index0`.485-486- :param args: One or more values to cycle through.487- """488- if not args:489- raise TypeError("no items for cycling given")490-491- return args[self.index0 % len(args)]492-493- def changed(self, *value):494- """Return ``True`` if previously called with a different value495- (including when called for the first time).496-497- :param value: One or more values to compare to the last call.498- """499- if self._last_changed_value != value:500- self._last_changed_value = value501- return True502-503- return False504-505- def __iter__(self):506- return self507-508- def __next__(self):509- if self._after is not missing:510- rv = self._after511- self._after = missing512- else:513- rv = next(self._iterator)514-515- self.index0 += 1516- self._before = self._current517- self._current = rv518- return rv, self519-520- @internalcode521- def __call__(self, iterable):522- """When iterating over nested data, render the body of the loop523- recursively with the given inner iterable data.524-525- The loop must have the ``recursive`` marker for this to work.526- """527- if self._recurse is None:528- raise TypeError(529- "The loop must have the 'recursive' marker to be"530- " called recursively."531- )532-533- return self._recurse(iterable, self._recurse, depth=self.depth)534-535- def __repr__(self):536- return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)537-538-539-class Macro(object):540- """Wraps a macro function."""541-542- def __init__(self, environment, func, name, arguments,543- catch_kwargs, catch_varargs, caller,544- default_autoescape=None):545- self._environment = environment546- self._func = func547- self._argument_count = len(arguments)548- self.name = name549- self.arguments = arguments550- self.catch_kwargs = catch_kwargs551- self.catch_varargs = catch_varargs552- self.caller = caller553- self.explicit_caller = 'caller' in arguments554- if default_autoescape is None:555- default_autoescape = environment.autoescape556- self._default_autoescape = default_autoescape557-558- @internalcode559- @evalcontextfunction560- def __call__(self, *args, **kwargs):561- # This requires a bit of explanation, In the past we used to562- # decide largely based on compile-time information if a macro is563- # safe or unsafe. While there was a volatile mode it was largely564- # unused for deciding on escaping. This turns out to be565- # problematic for macros because whether a macro is safe depends not566- # on the escape mode when it was defined, but rather when it was used.567- #568- # Because however we export macros from the module system and569- # there are historic callers that do not pass an eval context (and570- # will continue to not pass one), we need to perform an instance571- # check here.572- #573- # This is considered safe because an eval context is not a valid574- # argument to callables otherwise anyway. Worst case here is575- # that if no eval context is passed we fall back to the compile576- # time autoescape flag.577- if args and isinstance(args[0], EvalContext):578- autoescape = args[0].autoescape579- args = args[1:]580- else:581- autoescape = self._default_autoescape582-583- # try to consume the positional arguments584- arguments = list(args[:self._argument_count])585- off = len(arguments)586-587- # For information why this is necessary refer to the handling588- # of caller in the `macro_body` handler in the compiler.589- found_caller = False590-591- # if the number of arguments consumed is not the number of592- # arguments expected we start filling in keyword arguments593- # and defaults.594- if off != self._argument_count:595- for idx, name in enumerate(self.arguments[len(arguments):]):596- try:597- value = kwargs.pop(name)598- except KeyError:599- value = missing600- if name == 'caller':601- found_caller = True602- arguments.append(value)603- else:604- found_caller = self.explicit_caller605-606- # it's important that the order of these arguments does not change607- # if not also changed in the compiler's `function_scoping` method.608- # the order is caller, keyword arguments, positional arguments!609- if self.caller and not found_caller:610- caller = kwargs.pop('caller', None)611- if caller is None:612- caller = self._environment.undefined('No caller defined',613- name='caller')614- arguments.append(caller)615-616- if self.catch_kwargs:617- arguments.append(kwargs)618- elif kwargs:619- if 'caller' in kwargs:620- raise TypeError('macro %r was invoked with two values for '621- 'the special caller argument. This is '622- 'most likely a bug.' % self.name)623- raise TypeError('macro %r takes no keyword argument %r' %624- (self.name, next(iter(kwargs))))625- if self.catch_varargs:626- arguments.append(args[self._argument_count:])627- elif len(args) > self._argument_count:628- raise TypeError('macro %r takes not more than %d argument(s)' %629- (self.name, len(self.arguments)))630-631- return self._invoke(arguments, autoescape)632-633- def _invoke(self, arguments, autoescape):634- """This method is being swapped out by the async implementation."""635- rv = self._func(*arguments)636- if autoescape:637- rv = Markup(rv)638- return rv639-640- def __repr__(self):641- return '<%s %s>' % (642- self.__class__.__name__,643- self.name is None and 'anonymous' or repr(self.name)644- )645-646-647-@implements_to_string648-class Undefined(object):649- """The default undefined type. This undefined type can be printed and650- iterated over, but every other access will raise an :exc:`UndefinedError`:651-652- >>> foo = Undefined(name='foo')653- >>> str(foo)654- ''655- >>> not foo656- True657- >>> foo + 42658- Traceback (most recent call last):659- ...660- jinja2.exceptions.UndefinedError: 'foo' is undefined661- """662- __slots__ = ('_undefined_hint', '_undefined_obj', '_undefined_name',663- '_undefined_exception')664-665- def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):666- self._undefined_hint = hint667- self._undefined_obj = obj668- self._undefined_name = name669- self._undefined_exception = exc670-671- @property672- def _undefined_message(self):673- """Build a message about the undefined value based on how it was674- accessed.675- """676- if self._undefined_hint:677- return self._undefined_hint678-679- if self._undefined_obj is missing:680- return '%r is undefined' % self._undefined_name681-682- if not isinstance(self._undefined_name, string_types):683- return '%s has no element %r' % (684- object_type_repr(self._undefined_obj),685- self._undefined_name686- )687-688- return '%r has no attribute %r' % (689- object_type_repr(self._undefined_obj),690- self._undefined_name691- )692-693- @internalcode694- def _fail_with_undefined_error(self, *args, **kwargs):695- """Raise an :exc:`UndefinedError` when operations are performed696- on the undefined value.697- """698- raise self._undefined_exception(self._undefined_message)699-700- @internalcode701- def __getattr__(self, name):702- if name[:2] == '__':703- raise AttributeError(name)704- return self._fail_with_undefined_error()705-706- __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \707- __truediv__ = __rtruediv__ = __floordiv__ = __rfloordiv__ = \708- __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \709- __getitem__ = __lt__ = __le__ = __gt__ = __ge__ = __int__ = \710- __float__ = __complex__ = __pow__ = __rpow__ = __sub__ = \711- __rsub__ = _fail_with_undefined_error712-713- def __eq__(self, other):714- return type(self) is type(other)715-716- def __ne__(self, other):717- return not self.__eq__(other)718-719- def __hash__(self):720- return id(type(self))721-722- def __str__(self):723- return u''724-725- def __len__(self):726- return 0727-728- def __iter__(self):729- if 0:730- yield None731-732- def __nonzero__(self):733- return False734- __bool__ = __nonzero__735-736- def __repr__(self):737- return 'Undefined'738-739-740-def make_logging_undefined(logger=None, base=None):741- """Given a logger object this returns a new undefined class that will742- log certain failures. It will log iterations and printing. If no743- logger is given a default logger is created.744-745- Example::746-747- logger = logging.getLogger(__name__)748- LoggingUndefined = make_logging_undefined(749- logger=logger,750- base=Undefined751- )752-753- .. versionadded:: 2.8754-755- :param logger: the logger to use. If not provided, a default logger756- is created.757- :param base: the base class to add logging functionality to. This758- defaults to :class:`Undefined`.759- """760- if logger is None:761- import logging762- logger = logging.getLogger(__name__)763- logger.addHandler(logging.StreamHandler(sys.stderr))764- if base is None:765- base = Undefined766-767- def _log_message(undef):768- if undef._undefined_hint is None:769- if undef._undefined_obj is missing:770- hint = '%s is undefined' % undef._undefined_name771- elif not isinstance(undef._undefined_name, string_types):772- hint = '%s has no element %s' % (773- object_type_repr(undef._undefined_obj),774- undef._undefined_name)775- else:776- hint = '%s has no attribute %s' % (777- object_type_repr(undef._undefined_obj),778- undef._undefined_name)779- else:780- hint = undef._undefined_hint781- logger.warning('Template variable warning: %s', hint)782-783- class LoggingUndefined(base):784-785- def _fail_with_undefined_error(self, *args, **kwargs):786- try:787- return base._fail_with_undefined_error(self, *args, **kwargs)788- except self._undefined_exception as e:789- logger.error('Template variable error: %s', str(e))790- raise e791-792- def __str__(self):793- rv = base.__str__(self)794- _log_message(self)795- return rv796-797- def __iter__(self):798- rv = base.__iter__(self)799- _log_message(self)800- return rv801-802- if PY2:803- def __nonzero__(self):804- rv = base.__nonzero__(self)805- _log_message(self)806- return rv807-808- def __unicode__(self):809- rv = base.__unicode__(self)810- _log_message(self)811- return rv812- else:813- def __bool__(self):814- rv = base.__bool__(self)815- _log_message(self)816- return rv817-818- return LoggingUndefined819-820-821-# No @implements_to_string decorator here because __str__822-# is not overwritten from Undefined in this class.823-# This would cause a recursion error in Python 2.824-class ChainableUndefined(Undefined):825- """An undefined that is chainable, where both ``__getattr__`` and826- ``__getitem__`` return itself rather than raising an827- :exc:`UndefinedError`.828-829- >>> foo = ChainableUndefined(name='foo')830- >>> str(foo.bar['baz'])831- ''832- >>> foo.bar['baz'] + 42833- Traceback (most recent call last):834- ...835- jinja2.exceptions.UndefinedError: 'foo' is undefined836-837- .. versionadded:: 2.11.0838- """839- __slots__ = ()840-841- def __html__(self):842- return self.__str__()843-844- def __getattr__(self, _):845- return self846-847- __getitem__ = __getattr__848-849-850-@implements_to_string851-class DebugUndefined(Undefined):852- """An undefined that returns the debug info when printed.853-854- >>> foo = DebugUndefined(name='foo')855- >>> str(foo)856- '{{ foo }}'857- >>> not foo858- True859- >>> foo + 42860- Traceback (most recent call last):861- ...862- jinja2.exceptions.UndefinedError: 'foo' is undefined863- """864- __slots__ = ()865-866- def __str__(self):867- if self._undefined_hint is None:868- if self._undefined_obj is missing:869- return u'{{ %s }}' % self._undefined_name870- return '{{ no such element: %s[%r] }}' % (871- object_type_repr(self._undefined_obj),872- self._undefined_name873- )874- return u'{{ undefined value printed: %s }}' % self._undefined_hint875-876-877-@implements_to_string878-class StrictUndefined(Undefined):879- """An undefined that barks on print and iteration as well as boolean880- tests and all kinds of comparisons. In other words: you can do nothing881- with it except checking if it's defined using the `defined` test.882-883- >>> foo = StrictUndefined(name='foo')884- >>> str(foo)885- Traceback (most recent call last):886- ...887- jinja2.exceptions.UndefinedError: 'foo' is undefined888- >>> not foo889- Traceback (most recent call last):890- ...891- jinja2.exceptions.UndefinedError: 'foo' is undefined892- >>> foo + 42893- Traceback (most recent call last):894- ...895- jinja2.exceptions.UndefinedError: 'foo' is undefined896- """897- __slots__ = ()898- __iter__ = __str__ = __len__ = __nonzero__ = __eq__ = \899- __ne__ = __bool__ = __hash__ = \900- Undefined._fail_with_undefined_error901-902-903-# remove remaining slots attributes, after the metaclass did the magic they904-# are unneeded and irritating as they contain wrong data for the subclasses.905-del Undefined.__slots__, ChainableUndefined.__slots__, \906- DebugUndefined.__slots__, StrictUndefined.__slots__deleted:jinja2/sandbox.py-488 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.sandbox4- ~~~~~~~~~~~~~~5-6- Adds a sandbox layer to Jinja as it was the default behavior in the old7- Jinja 1 releases. This sandbox is slightly different from Jinja 1 as the8- default behavior is easier to use.9-10- The behavior can be changed by subclassing the environment.11-12- :copyright: (c) 2017 by the Jinja Team.13- :license: BSD.14-"""15-import types16-import operator17-from jinja2.environment import Environment18-from jinja2.exceptions import SecurityError19-from jinja2._compat import string_types, PY2, abc, range_type20-from jinja2.utils import Markup21-22-from markupsafe import EscapeFormatter23-from string import Formatter24-25-26-#: maximum number of items a range may produce27-MAX_RANGE = 10000028-29-#: attributes of function objects that are considered unsafe.30-if PY2:31- UNSAFE_FUNCTION_ATTRIBUTES = set(['func_closure', 'func_code', 'func_dict',32- 'func_defaults', 'func_globals'])33-else: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()37-38-39-#: unsafe method attributes. function attributes are unsafe for methods too40-UNSAFE_METHOD_ATTRIBUTES = set(['im_class', 'im_func', 'im_self'])41-42-#: unsafe generator attributes.43-UNSAFE_GENERATOR_ATTRIBUTES = set(['gi_frame', 'gi_code'])44-45-#: unsafe attributes on coroutines46-UNSAFE_COROUTINE_ATTRIBUTES = set(['cr_frame', 'cr_code'])47-48-#: unsafe attributes on async generators49-UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = set(['ag_code', 'ag_frame'])50-51-import warnings52-53-# make sure we don't warn in python 2.6 about stuff we don't care about54-warnings.filterwarnings('ignore', 'the sets module', DeprecationWarning,55- module='jinja2.sandbox')56-57-from collections import deque58-59-_mutable_set_types = (set,)60-_mutable_mapping_types = (dict,)61-_mutable_sequence_types = (list,)62-63-64-# on python 2.x we can register the user collection types65-try:66- from UserDict import UserDict, DictMixin67- from UserList import UserList68- _mutable_mapping_types += (UserDict, DictMixin)69- _mutable_set_types += (UserList,)70-except ImportError:71- pass72-73-# if sets is still available, register the mutable set from there as well74-try:75- from sets import Set76- _mutable_set_types += (Set,)77-except ImportError:78- pass79-80-#: register Python 2.6 abstract base classes81-_mutable_set_types += (abc.MutableSet,)82-_mutable_mapping_types += (abc.MutableMapping,)83-_mutable_sequence_types += (abc.MutableSequence,)84-85-86-_mutable_spec = (87- (_mutable_set_types, frozenset([88- 'add', 'clear', 'difference_update', 'discard', 'pop', 'remove',89- 'symmetric_difference_update', 'update'90- ])),91- (_mutable_mapping_types, frozenset([92- 'clear', 'pop', 'popitem', 'setdefault', 'update'93- ])),94- (_mutable_sequence_types, frozenset([95- 'append', 'reverse', 'insert', 'sort', 'extend', 'remove'96- ])),97- (deque, frozenset([98- 'append', 'appendleft', 'clear', 'extend', 'extendleft', 'pop',99- 'popleft', 'remove', 'rotate'100- ]))101-)102-103-104-class _MagicFormatMapping(abc.Mapping):105- """This class implements a dummy wrapper to fix a bug in the Python106- standard library for string formatting.107-108- See https://bugs.python.org/issue13598 for information about why109- this is necessary.110- """111-112- def __init__(self, args, kwargs):113- self._args = args114- self._kwargs = kwargs115- self._last_index = 0116-117- def __getitem__(self, key):118- if key == '':119- idx = self._last_index120- self._last_index += 1121- try:122- return self._args[idx]123- except LookupError:124- pass125- key = str(idx)126- return self._kwargs[key]127-128- def __iter__(self):129- return iter(self._kwargs)130-131- def __len__(self):132- return len(self._kwargs)133-134-135-def inspect_format_method(callable):136- if not isinstance(callable, (types.MethodType,137- types.BuiltinMethodType)) or \138- callable.__name__ not in ('format', 'format_map'):139- return None140- obj = callable.__self__141- if isinstance(obj, string_types):142- return obj143-144-145-def safe_range(*args):146- """A range that can't generate ranges with a length of more than147- MAX_RANGE items.148- """149- rng = range_type(*args)150-151- if len(rng) > MAX_RANGE:152- raise OverflowError(153- "Range too big. The sandbox blocks ranges larger than"154- " MAX_RANGE (%d)." % MAX_RANGE155- )156-157- return rng158-159-160-def unsafe(f):161- """Marks a function or method as unsafe.162-163- ::164-165- @unsafe166- def delete(self):167- pass168- """169- f.unsafe_callable = True170- return f171-172-173-def is_internal_attribute(obj, attr):174- """Test if the attribute given is an internal python attribute. For175- example this function returns `True` for the `func_code` attribute of176- python objects. This is useful if the environment method177- :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.178-179- >>> from jinja2.sandbox import is_internal_attribute180- >>> is_internal_attribute(str, "mro")181- True182- >>> is_internal_attribute(str, "upper")183- False184- """185- if isinstance(obj, types.FunctionType):186- if attr in UNSAFE_FUNCTION_ATTRIBUTES:187- return True188- elif isinstance(obj, types.MethodType):189- if attr in UNSAFE_FUNCTION_ATTRIBUTES or \190- attr in UNSAFE_METHOD_ATTRIBUTES:191- return True192- elif isinstance(obj, type):193- if attr == 'mro':194- return True195- elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):196- return True197- elif isinstance(obj, types.GeneratorType):198- if attr in UNSAFE_GENERATOR_ATTRIBUTES:199- return True200- elif hasattr(types, 'CoroutineType') and isinstance(obj, types.CoroutineType):201- if attr in UNSAFE_COROUTINE_ATTRIBUTES:202- return True203- elif hasattr(types, 'AsyncGeneratorType') and isinstance(obj, types.AsyncGeneratorType):204- if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:205- return True206- return attr.startswith('__')207-208-209-def modifies_known_mutable(obj, attr):210- """This function checks if an attribute on a builtin mutable object211- (list, dict, set or deque) would modify it if called. It also supports212- the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and213- with Python 2.6 onwards the abstract base classes `MutableSet`,214- `MutableMapping`, and `MutableSequence`.215-216- >>> modifies_known_mutable({}, "clear")217- True218- >>> modifies_known_mutable({}, "keys")219- False220- >>> modifies_known_mutable([], "append")221- True222- >>> modifies_known_mutable([], "index")223- False224-225- If called with an unsupported object (such as unicode) `False` is226- returned.227-228- >>> modifies_known_mutable("foo", "upper")229- False230- """231- for typespec, unsafe in _mutable_spec:232- if isinstance(obj, typespec):233- return attr in unsafe234- return False235-236-237-class SandboxedEnvironment(Environment):238- """The sandboxed environment. It works like the regular environment but239- tells the compiler to generate sandboxed code. Additionally subclasses of240- this environment may override the methods that tell the runtime what241- attributes or functions are safe to access.242-243- If the template tries to access insecure code a :exc:`SecurityError` is244- raised. However also other exceptions may occur during the rendering so245- the caller has to ensure that all exceptions are caught.246- """247- sandboxed = True248-249- #: default callback table for the binary operators. A copy of this is250- #: available on each instance of a sandboxed environment as251- #: :attr:`binop_table`252- default_binop_table = {253- '+': operator.add,254- '-': operator.sub,255- '*': operator.mul,256- '/': operator.truediv,257- '//': operator.floordiv,258- '**': operator.pow,259- '%': operator.mod260- }261-262- #: default callback table for the unary operators. A copy of this is263- #: available on each instance of a sandboxed environment as264- #: :attr:`unop_table`265- default_unop_table = {266- '+': operator.pos,267- '-': operator.neg268- }269-270- #: a set of binary operators that should be intercepted. Each operator271- #: that is added to this set (empty by default) is delegated to the272- #: :meth:`call_binop` method that will perform the operator. The default273- #: operator callback is specified by :attr:`binop_table`.274- #:275- #: The following binary operators are interceptable:276- #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``277- #:278- #: The default operation form the operator table corresponds to the279- #: builtin function. Intercepted calls are always slower than the native280- #: operator call, so make sure only to intercept the ones you are281- #: interested in.282- #:283- #: .. versionadded:: 2.6284- intercepted_binops = frozenset()285-286- #: a set of unary operators that should be intercepted. Each operator287- #: that is added to this set (empty by default) is delegated to the288- #: :meth:`call_unop` method that will perform the operator. The default289- #: operator callback is specified by :attr:`unop_table`.290- #:291- #: The following unary operators are interceptable: ``+``, ``-``292- #:293- #: The default operation form the operator table corresponds to the294- #: builtin function. Intercepted calls are always slower than the native295- #: operator call, so make sure only to intercept the ones you are296- #: interested in.297- #:298- #: .. versionadded:: 2.6299- intercepted_unops = frozenset()300-301- def intercept_unop(self, operator):302- """Called during template compilation with the name of a unary303- operator to check if it should be intercepted at runtime. If this304- method returns `True`, :meth:`call_unop` is executed for this unary305- operator. The default implementation of :meth:`call_unop` will use306- the :attr:`unop_table` dictionary to perform the operator with the307- same logic as the builtin one.308-309- The following unary operators are interceptable: ``+`` and ``-``310-311- Intercepted calls are always slower than the native operator call,312- so make sure only to intercept the ones you are interested in.313-314- .. versionadded:: 2.6315- """316- return False317-318-319- def __init__(self, *args, **kwargs):320- Environment.__init__(self, *args, **kwargs)321- self.globals['range'] = safe_range322- self.binop_table = self.default_binop_table.copy()323- self.unop_table = self.default_unop_table.copy()324-325- def is_safe_attribute(self, obj, attr, value):326- """The sandboxed environment will call this method to check if the327- attribute of an object is safe to access. Per default all attributes328- starting with an underscore are considered private as well as the329- special attributes of internal python objects as returned by the330- :func:`is_internal_attribute` function.331- """332- return not (attr.startswith('_') or is_internal_attribute(obj, attr))333-334- def is_safe_callable(self, obj):335- """Check if an object is safely callable. Per default a function is336- considered safe unless the `unsafe_callable` attribute exists and is337- True. Override this method to alter the behavior, but this won't338- affect the `unsafe` decorator from this module.339- """340- return not (getattr(obj, 'unsafe_callable', False) or341- getattr(obj, 'alters_data', False))342-343- def call_binop(self, context, operator, left, right):344- """For intercepted binary operator calls (:meth:`intercepted_binops`)345- this function is executed instead of the builtin operator. This can346- be used to fine tune the behavior of certain operators.347-348- .. versionadded:: 2.6349- """350- return self.binop_table[operator](left, right)351-352- def call_unop(self, context, operator, arg):353- """For intercepted unary operator calls (:meth:`intercepted_unops`)354- this function is executed instead of the builtin operator. This can355- be used to fine tune the behavior of certain operators.356-357- .. versionadded:: 2.6358- """359- return self.unop_table[operator](arg)360-361- def getitem(self, obj, argument):362- """Subscribe an object from sandboxed code."""363- try:364- return obj[argument]365- except (TypeError, LookupError):366- if isinstance(argument, string_types):367- try:368- attr = str(argument)369- except Exception:370- pass371- else:372- try:373- value = getattr(obj, attr)374- except AttributeError:375- pass376- else:377- if self.is_safe_attribute(obj, argument, value):378- return value379- return self.unsafe_undefined(obj, argument)380- return self.undefined(obj=obj, name=argument)381-382- def getattr(self, obj, attribute):383- """Subscribe an object from sandboxed code and prefer the384- attribute. The attribute passed *must* be a bytestring.385- """386- try:387- value = getattr(obj, attribute)388- except AttributeError:389- try:390- return obj[attribute]391- except (TypeError, LookupError):392- pass393- else:394- if self.is_safe_attribute(obj, attribute, value):395- return value396- return self.unsafe_undefined(obj, attribute)397- return self.undefined(obj=obj, name=attribute)398-399- def unsafe_undefined(self, obj, attribute):400- """Return an undefined object for unsafe attributes."""401- return self.undefined('access to attribute %r of %r '402- 'object is unsafe.' % (403- attribute,404- obj.__class__.__name__405- ), name=attribute, obj=obj, exc=SecurityError)406-407- def format_string(self, s, args, kwargs, format_func=None):408- """If a format call is detected, then this is routed through this409- method so that our safety sandbox can be used for it.410- """411- if isinstance(s, Markup):412- formatter = SandboxedEscapeFormatter(self, s.escape)413- else:414- formatter = SandboxedFormatter(self)415-416- if format_func is not None and format_func.__name__ == 'format_map':417- if len(args) != 1 or kwargs:418- raise TypeError(419- 'format_map() takes exactly one argument %d given'420- % (len(args) + (kwargs is not None))421- )422-423- kwargs = args[0]424- args = None425-426- kwargs = _MagicFormatMapping(args, kwargs)427- rv = formatter.vformat(s, args, kwargs)428- return type(s)(rv)429-430- def call(__self, __context, __obj, *args, **kwargs):431- """Call an object from sandboxed code."""432- fmt = inspect_format_method(__obj)433- if fmt is not None:434- return __self.format_string(fmt, args, kwargs, __obj)435-436- # the double prefixes are to avoid double keyword argument437- # errors when proxying the call.438- if not __self.is_safe_callable(__obj):439- raise SecurityError('%r is not safely callable' % (__obj,))440- return __context.call(__obj, *args, **kwargs)441-442-443-class ImmutableSandboxedEnvironment(SandboxedEnvironment):444- """Works exactly like the regular `SandboxedEnvironment` but does not445- permit modifications on the builtin mutable objects `list`, `set`, and446- `dict` by using the :func:`modifies_known_mutable` function.447- """448-449- def is_safe_attribute(self, obj, attr, value):450- if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):451- return False452- return not modifies_known_mutable(obj, attr)453-454-455-# This really is not a public API apparently.456-try:457- from _string import formatter_field_name_split458-except ImportError:459- def formatter_field_name_split(field_name):460- return field_name._formatter_field_name_split()461-462-463-class SandboxedFormatterMixin(object):464-465- def __init__(self, env):466- self._env = env467-468- def get_field(self, field_name, args, kwargs):469- first, rest = formatter_field_name_split(field_name)470- obj = self.get_value(first, args, kwargs)471- for is_attr, i in rest:472- if is_attr:473- obj = self._env.getattr(obj, i)474- else:475- obj = self._env.getitem(obj, i)476- return obj, first477-478-class SandboxedFormatter(SandboxedFormatterMixin, Formatter):479-480- def __init__(self, env):481- SandboxedFormatterMixin.__init__(self, env)482- Formatter.__init__(self)483-484-class SandboxedEscapeFormatter(SandboxedFormatterMixin, EscapeFormatter):485-486- def __init__(self, env, escape):487- SandboxedFormatterMixin.__init__(self, env)488- EscapeFormatter.__init__(self, escape)deleted:jinja2/tests.py-221 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.tests4- ~~~~~~~~~~~~5-6- Jinja test functions. Used with the "is" operator.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-import operator12-import re13-from jinja2.runtime import Undefined14-from jinja2._compat import text_type, string_types, integer_types, abc15-import decimal16-17-number_re = re.compile(r'^-?\d+(\.\d+)?$')18-regex_type = type(number_re)19-20-21-test_callable = callable22-23-24-def test_odd(value):25- """Return true if the variable is odd."""26- return value % 2 == 127-28-29-def test_even(value):30- """Return true if the variable is even."""31- return value % 2 == 032-33-34-def test_divisibleby(value, num):35- """Check if a variable is divisible by a number."""36- return value % num == 037-38-39-def test_defined(value):40- """Return true if the variable is defined:41-42- .. sourcecode:: jinja43-44- {% if variable is defined %}45- value of variable: {{ variable }}46- {% else %}47- variable is not defined48- {% endif %}49-50- See the :func:`default` filter for a simple way to set undefined51- variables.52- """53- return not isinstance(value, Undefined)54-55-56-def test_undefined(value):57- """Like :func:`defined` but the other way round."""58- return isinstance(value, Undefined)59-60-61-def test_none(value):62- """Return true if the variable is none."""63- return value is None64-65-66-def test_boolean(value):67- """Return true if the object is a boolean value.68-69- .. versionadded:: 2.1170- """71- return value is True or value is False72-73-74-def test_false(value):75- """Return true if the object is False.76-77- .. versionadded:: 2.1178- """79- return value is False80-81-82-def test_true(value):83- """Return true if the object is True.84-85- .. versionadded:: 2.1186- """87- return value is True88-89-90-# NOTE: The existing 'number' test matches booleans and floats91-def test_integer(value):92- """Return true if the object is an integer.93-94- .. versionadded:: 2.1195- """96- return isinstance(value, integer_types) and value is not True and value is not False97-98-99-# NOTE: The existing 'number' test matches booleans and integers100-def test_float(value):101- """Return true if the object is a float.102-103- .. versionadded:: 2.11104- """105- return isinstance(value, float)106-107-108-def test_lower(value):109- """Return true if the variable is lowercased."""110- return text_type(value).islower()111-112-113-def test_upper(value):114- """Return true if the variable is uppercased."""115- return text_type(value).isupper()116-117-118-def test_string(value):119- """Return true if the object is a string."""120- return isinstance(value, string_types)121-122-123-def test_mapping(value):124- """Return true if the object is a mapping (dict etc.).125-126- .. versionadded:: 2.6127- """128- return isinstance(value, abc.Mapping)129-130-131-def test_number(value):132- """Return true if the variable is a number."""133- return isinstance(value, integer_types + (float, complex, decimal.Decimal))134-135-136-def test_sequence(value):137- """Return true if the variable is a sequence. Sequences are variables138- that are iterable.139- """140- try:141- len(value)142- value.__getitem__143- except:144- return False145- return True146-147-148-def test_sameas(value, other):149- """Check if an object points to the same memory address than another150- object:151-152- .. sourcecode:: jinja153-154- {% if foo.attribute is sameas false %}155- the foo attribute really is the `False` singleton156- {% endif %}157- """158- return value is other159-160-161-def test_iterable(value):162- """Check if it's possible to iterate over an object."""163- try:164- iter(value)165- except TypeError:166- return False167- return True168-169-170-def test_escaped(value):171- """Check if the value is escaped."""172- return hasattr(value, '__html__')173-174-175-def test_in(value, seq):176- """Check if value is in seq.177-178- .. versionadded:: 2.10179- """180- return value in seq181-182-183-TESTS = {184- 'odd': test_odd,185- 'even': test_even,186- 'divisibleby': test_divisibleby,187- 'defined': test_defined,188- 'undefined': test_undefined,189- 'none': test_none,190- 'boolean': test_boolean,191- 'false': test_false,192- 'true': test_true,193- 'integer': test_integer,194- 'float': test_float,195- 'lower': test_lower,196- 'upper': test_upper,197- 'string': test_string,198- 'mapping': test_mapping,199- 'number': test_number,200- 'sequence': test_sequence,201- 'iterable': test_iterable,202- 'callable': test_callable,203- 'sameas': test_sameas,204- 'escaped': test_escaped,205- 'in': test_in,206- '==': operator.eq,207- 'eq': operator.eq,208- 'equalto': operator.eq,209- '!=': operator.ne,210- 'ne': operator.ne,211- '>': operator.gt,212- 'gt': operator.gt,213- 'greaterthan': operator.gt,214- 'ge': operator.ge,215- '>=': operator.ge,216- '<': operator.lt,217- 'lt': operator.lt,218- 'lessthan': operator.lt,219- '<=': operator.le,220- 'le': operator.le,221-}deleted:jinja2/utils.py-678 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.utils4- ~~~~~~~~~~~~5-6- Utility functions.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-import os12-import re13-import json14-import warnings15-from collections import deque16-from threading import Lock17-from jinja2._compat import text_type, string_types, url_quote, abc18-19-20-_word_split_re = re.compile(r'(\s+)')21-_punctuation_re = re.compile(22- '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (23- '|'.join(map(re.escape, ('(', '<', '<'))),24- '|'.join(map(re.escape, ('.', ',', ')', '>', '\n', '>')))25- )26-)27-_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')28-_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')29-_entity_re = re.compile(r'&([^;]+);')30-_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'31-_digits = '0123456789'32-33-# special singleton representing missing values for the runtime34-missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()35-36-# internal code37-internal_code = set()38-39-concat = u''.join40-41-_slash_escape = '\\/' not in json.dumps('/')42-43-44-def contextfunction(f):45- """This decorator can be used to mark a function or method context callable.46- A context callable is passed the active :class:`Context` as first argument when47- called from the template. This is useful if a function wants to get access48- to the context or functions provided on the context object. For example49- a function that returns a sorted list of template variables the current50- template exports could look like this::51-52- @contextfunction53- def get_exported_names(context):54- return sorted(context.exported_vars)55- """56- f.contextfunction = True57- return f58-59-60-def evalcontextfunction(f):61- """This decorator can be used to mark a function or method as an eval62- context callable. This is similar to the :func:`contextfunction`63- but instead of passing the context, an evaluation context object is64- passed. For more information about the eval context, see65- :ref:`eval-context`.66-67- .. versionadded:: 2.468- """69- f.evalcontextfunction = True70- return f71-72-73-def environmentfunction(f):74- """This decorator can be used to mark a function or method as environment75- callable. This decorator works exactly like the :func:`contextfunction`76- decorator just that the first argument is the active :class:`Environment`77- and not context.78- """79- f.environmentfunction = True80- return f81-82-83-def internalcode(f):84- """Marks the function as internally used"""85- internal_code.add(f.__code__)86- return f87-88-89-def is_undefined(obj):90- """Check if the object passed is undefined. This does nothing more than91- performing an instance check against :class:`Undefined` but looks nicer.92- This can be used for custom filters or tests that want to react to93- undefined variables. For example a custom default filter can look like94- this::95-96- def default(var, default=''):97- if is_undefined(var):98- return default99- return var100- """101- from jinja2.runtime import Undefined102- return isinstance(obj, Undefined)103-104-105-def consume(iterable):106- """Consumes an iterable without doing anything with it."""107- for event in iterable:108- pass109-110-111-def clear_caches():112- """Jinja keeps internal caches for environments and lexers. These are113- used so that Jinja doesn't have to recreate environments and lexers all114- the time. Normally you don't have to care about that but if you are115- measuring memory consumption you may want to clean the caches.116- """117- from jinja2.environment import _spontaneous_environments118- from jinja2.lexer import _lexer_cache119- _spontaneous_environments.clear()120- _lexer_cache.clear()121-122-123-def import_string(import_name, silent=False):124- """Imports an object based on a string. This is useful if you want to125- use import paths as endpoints or something similar. An import path can126- be specified either in dotted notation (``xml.sax.saxutils.escape``)127- or with a colon as object delimiter (``xml.sax.saxutils:escape``).128-129- If the `silent` is True the return value will be `None` if the import130- fails.131-132- :return: imported object133- """134- try:135- if ':' in import_name:136- module, obj = import_name.split(':', 1)137- elif '.' in import_name:138- module, _, obj = import_name.rpartition('.')139- else:140- return __import__(import_name)141- return getattr(__import__(module, None, None, [obj]), obj)142- except (ImportError, AttributeError):143- if not silent:144- raise145-146-147-def open_if_exists(filename, mode='rb'):148- """Returns a file descriptor for the filename if that file exists,149- otherwise ``None``.150- """151- if not os.path.isfile(filename):152- return None153-154- return open(filename, mode)155-156-157-def object_type_repr(obj):158- """Returns the name of the object's type. For some recognized159- singletons the name of the object is returned instead. (For160- example for `None` and `Ellipsis`).161- """162- if obj is None:163- return 'None'164- elif obj is Ellipsis:165- return 'Ellipsis'166- # __builtin__ in 2.x, builtins in 3.x167- if obj.__class__.__module__ in ('__builtin__', 'builtins'):168- name = obj.__class__.__name__169- else:170- name = obj.__class__.__module__ + '.' + obj.__class__.__name__171- return '%s object' % name172-173-174-def pformat(obj, verbose=False):175- """Prettyprint an object. Either use the `pretty` library or the176- builtin `pprint`.177- """178- try:179- from pretty import pretty180- return pretty(obj, verbose=verbose)181- except ImportError:182- from pprint import pformat183- return pformat(obj)184-185-186-def urlize(text, trim_url_limit=None, rel=None, target=None):187- """Converts any URLs in text into clickable links. Works on http://,188- https:// and www. links. Links can have trailing punctuation (periods,189- commas, close-parens) and leading punctuation (opening parens) and190- it'll still do the right thing.191-192- If trim_url_limit is not None, the URLs in link text will be limited193- to trim_url_limit characters.194-195- If nofollow is True, the URLs in link text will get a rel="nofollow"196- attribute.197-198- If target is not None, a target attribute will be added to the link.199- """200- trim_url = lambda x, limit=trim_url_limit: limit is not None \201- and (x[:limit] + (len(x) >=limit and '...'202- or '')) or x203- words = _word_split_re.split(text_type(escape(text)))204- rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ''205- target_attr = target and ' target="%s"' % escape(target) or ''206-207- for i, word in enumerate(words):208- match = _punctuation_re.match(word)209- if match:210- lead, middle, trail = match.groups()211- if middle.startswith('www.') or (212- '@' not in middle and213- not middle.startswith('http://') and214- not middle.startswith('https://') and215- len(middle) > 0 and216- middle[0] in _letters + _digits and (217- middle.endswith('.org') or218- middle.endswith('.net') or219- middle.endswith('.com')220- )):221- middle = '<a href="http://%s"%s%s>%s</a>' % (middle,222- rel_attr, target_attr, trim_url(middle))223- if middle.startswith('http://') or \224- middle.startswith('https://'):225- middle = '<a href="%s"%s%s>%s</a>' % (middle,226- rel_attr, target_attr, trim_url(middle))227- if '@' in middle and not middle.startswith('www.') and \228- not ':' in middle and _simple_email_re.match(middle):229- middle = '<a href="mailto:%s">%s</a>' % (middle, middle)230- if lead + middle + trail != word:231- words[i] = lead + middle + trail232- return u''.join(words)233-234-235-def generate_lorem_ipsum(n=5, html=True, min=20, max=100):236- """Generate some lorem ipsum for the template."""237- from jinja2.constants import LOREM_IPSUM_WORDS238- from random import choice, randrange239- words = LOREM_IPSUM_WORDS.split()240- result = []241-242- for _ in range(n):243- next_capitalized = True244- last_comma = last_fullstop = 0245- word = None246- last = None247- p = []248-249- # each paragraph contains out of 20 to 100 words.250- for idx, _ in enumerate(range(randrange(min, max))):251- while True:252- word = choice(words)253- if word != last:254- last = word255- break256- if next_capitalized:257- word = word.capitalize()258- next_capitalized = False259- # add commas260- if idx - randrange(3, 8) > last_comma:261- last_comma = idx262- last_fullstop += 2263- word += ','264- # add end of sentences265- if idx - randrange(10, 20) > last_fullstop:266- last_comma = last_fullstop = idx267- word += '.'268- next_capitalized = True269- p.append(word)270-271- # ensure that the paragraph ends with a dot.272- p = u' '.join(p)273- if p.endswith(','):274- p = p[:-1] + '.'275- elif not p.endswith('.'):276- p += '.'277- result.append(p)278-279- if not html:280- return u'\n\n'.join(result)281- return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))282-283-284-def unicode_urlencode(obj, charset="utf-8", for_qs=False):285- """Quote a string for use in a URL using the given charset.286-287- This function is misnamed, it is a wrapper around288- :func:`urllib.parse.quote`.289-290- :param obj: String or bytes to quote. Other types are converted to291- string then encoded to bytes using the given charset.292- :param charset: Encode text to bytes using this charset.293- :param for_qs: Quote "/" and use "+" for spaces.294- """295- if not isinstance(obj, string_types):296- obj = text_type(obj)297-298- if isinstance(obj, text_type):299- obj = obj.encode(charset)300-301- safe = b"" if for_qs else b"/"302- rv = url_quote(obj, safe)303-304- if not isinstance(rv, text_type):305- rv = rv.decode("utf-8")306-307- if for_qs:308- rv = rv.replace("%20", "+")309-310- return rv311-312-313-class LRUCache(object):314- """A simple LRU Cache implementation."""315-316- # this is fast for small capacities (something below 1000) but doesn't317- # scale. But as long as it's only used as storage for templates this318- # won't do any harm.319-320- def __init__(self, capacity):321- self.capacity = capacity322- self._mapping = {}323- self._queue = deque()324- self._postinit()325-326- def _postinit(self):327- # alias all queue methods for faster lookup328- self._popleft = self._queue.popleft329- self._pop = self._queue.pop330- self._remove = self._queue.remove331- self._wlock = Lock()332- self._append = self._queue.append333-334- def __getstate__(self):335- return {336- 'capacity': self.capacity,337- '_mapping': self._mapping,338- '_queue': self._queue339- }340-341- def __setstate__(self, d):342- self.__dict__.update(d)343- self._postinit()344-345- def __getnewargs__(self):346- return (self.capacity,)347-348- def copy(self):349- """Return a shallow copy of the instance."""350- rv = self.__class__(self.capacity)351- rv._mapping.update(self._mapping)352- rv._queue.extend(self._queue)353- return rv354-355- def get(self, key, default=None):356- """Return an item from the cache dict or `default`"""357- try:358- return self[key]359- except KeyError:360- return default361-362- def setdefault(self, key, default=None):363- """Set `default` if the key is not in the cache otherwise364- leave unchanged. Return the value of this key.365- """366- try:367- return self[key]368- except KeyError:369- self[key] = default370- return default371-372- def clear(self):373- """Clear the cache."""374- self._wlock.acquire()375- try:376- self._mapping.clear()377- self._queue.clear()378- finally:379- self._wlock.release()380-381- def __contains__(self, key):382- """Check if a key exists in this cache."""383- return key in self._mapping384-385- def __len__(self):386- """Return the current size of the cache."""387- return len(self._mapping)388-389- def __repr__(self):390- return '<%s %r>' % (391- self.__class__.__name__,392- self._mapping393- )394-395- def __getitem__(self, key):396- """Get an item from the cache. Moves the item up so that it has the397- highest priority then.398-399- Raise a `KeyError` if it does not exist.400- """401- self._wlock.acquire()402- try:403- rv = self._mapping[key]404- if self._queue[-1] != key:405- try:406- self._remove(key)407- except ValueError:408- # if something removed the key from the container409- # when we read, ignore the ValueError that we would410- # get otherwise.411- pass412- self._append(key)413- return rv414- finally:415- self._wlock.release()416-417- def __setitem__(self, key, value):418- """Sets the value for an item. Moves the item up so that it419- has the highest priority then.420- """421- self._wlock.acquire()422- try:423- if key in self._mapping:424- self._remove(key)425- elif len(self._mapping) == self.capacity:426- del self._mapping[self._popleft()]427- self._append(key)428- self._mapping[key] = value429- finally:430- self._wlock.release()431-432- def __delitem__(self, key):433- """Remove an item from the cache dict.434- Raise a `KeyError` if it does not exist.435- """436- self._wlock.acquire()437- try:438- del self._mapping[key]439- try:440- self._remove(key)441- except ValueError:442- pass443- finally:444- self._wlock.release()445-446- def items(self):447- """Return a list of items."""448- result = [(key, self._mapping[key]) for key in list(self._queue)]449- result.reverse()450- return result451-452- def iteritems(self):453- """Iterate over all items."""454- return iter(self.items())455-456- def values(self):457- """Return a list of all values."""458- return [x[1] for x in self.items()]459-460- def itervalue(self):461- """Iterate over all values."""462- warnings.warn(DeprecationWarning(463- '"itervalue()" is deprecated and will be removed in version 2.12.'464- + ' Use "itervalues()" instead.'465- ), stacklevel=2)466- return self.itervalues()467-468- def itervalues(self):469- """Iterate over all values."""470- return iter(self.values())471-472- def keys(self):473- """Return a list of all keys ordered by most recent usage."""474- return list(self)475-476- def iterkeys(self):477- """Iterate over all keys in the cache dict, ordered by478- the most recent usage.479- """480- return reversed(tuple(self._queue))481-482- __iter__ = iterkeys483-484- def __reversed__(self):485- """Iterate over the keys in the cache dict, oldest items486- coming first.487- """488- return iter(tuple(self._queue))489-490- __copy__ = copy491-492-493-abc.MutableMapping.register(LRUCache)494-495-496-def select_autoescape(enabled_extensions=('html', 'htm', 'xml'),497- disabled_extensions=(),498- default_for_string=True,499- default=False):500- """Intelligently sets the initial value of autoescaping based on the501- filename of the template. This is the recommended way to configure502- autoescaping if you do not want to write a custom function yourself.503-504- If you want to enable it for all templates created from strings or505- for all templates with `.html` and `.xml` extensions::506-507- from jinja2 import Environment, select_autoescape508- env = Environment(autoescape=select_autoescape(509- enabled_extensions=('html', 'xml'),510- default_for_string=True,511- ))512-513- Example configuration to turn it on at all times except if the template514- ends with `.txt`::515-516- from jinja2 import Environment, select_autoescape517- env = Environment(autoescape=select_autoescape(518- disabled_extensions=('txt',),519- default_for_string=True,520- default=True,521- ))522-523- The `enabled_extensions` is an iterable of all the extensions that524- autoescaping should be enabled for. Likewise `disabled_extensions` is525- a list of all templates it should be disabled for. If a template is526- loaded from a string then the default from `default_for_string` is used.527- If nothing matches then the initial value of autoescaping is set to the528- value of `default`.529-530- For security reasons this function operates case insensitive.531-532- .. versionadded:: 2.9533- """534- enabled_patterns = tuple('.' + x.lstrip('.').lower()535- for x in enabled_extensions)536- disabled_patterns = tuple('.' + x.lstrip('.').lower()537- for x in disabled_extensions)538- def autoescape(template_name):539- if template_name is None:540- return default_for_string541- template_name = template_name.lower()542- if template_name.endswith(enabled_patterns):543- return True544- if template_name.endswith(disabled_patterns):545- return False546- return default547- return autoescape548-549-550-def htmlsafe_json_dumps(obj, dumper=None, **kwargs):551- """Works exactly like :func:`dumps` but is safe for use in ``<script>``552- tags. It accepts the same arguments and returns a JSON string. Note that553- this is available in templates through the ``|tojson`` filter which will554- also mark the result as safe. Due to how this function escapes certain555- characters this is safe even if used outside of ``<script>`` tags.556-557- The following characters are escaped in strings:558-559- - ``<``560- - ``>``561- - ``&``562- - ``'``563-564- This makes it safe to embed such strings in any place in HTML with the565- notable exception of double quoted attributes. In that case single566- quote your attributes or HTML escape it in addition.567- """568- if dumper is None:569- dumper = json.dumps570- rv = dumper(obj, **kwargs) \571- .replace(u'<', u'\\u003c') \572- .replace(u'>', u'\\u003e') \573- .replace(u'&', u'\\u0026') \574- .replace(u"'", u'\\u0027')575- return Markup(rv)576-577-578-class Cycler(object):579- """Cycle through values by yield them one at a time, then restarting580- once the end is reached. Available as ``cycler`` in templates.581-582- Similar to ``loop.cycle``, but can be used outside loops or across583- multiple loops. For example, render a list of folders and files in a584- list, alternating giving them "odd" and "even" classes.585-586- .. code-block:: html+jinja587-588- {% set row_class = cycler("odd", "even") %}589- <ul class="browser">590- {% for folder in folders %}591- <li class="folder {{ row_class.next() }}">{{ folder }}592- {% endfor %}593- {% for file in files %}594- <li class="file {{ row_class.next() }}">{{ file }}595- {% endfor %}596- </ul>597-598- :param items: Each positional argument will be yielded in the order599- given for each cycle.600-601- .. versionadded:: 2.1602- """603-604- def __init__(self, *items):605- if not items:606- raise RuntimeError('at least one item has to be provided')607- self.items = items608- self.pos = 0609-610- def reset(self):611- """Resets the current item to the first item."""612- self.pos = 0613-614- @property615- def current(self):616- """Return the current item. Equivalent to the item that will be617- returned next time :meth:`next` is called.618- """619- return self.items[self.pos]620-621- def next(self):622- """Return the current item, then advance :attr:`current` to the623- next item.624- """625- rv = self.current626- self.pos = (self.pos + 1) % len(self.items)627- return rv628-629- __next__ = next630-631-632-class Joiner(object):633- """A joining helper for templates."""634-635- def __init__(self, sep=u', '):636- self.sep = sep637- self.used = False638-639- def __call__(self):640- if not self.used:641- self.used = True642- return u''643- return self.sep644-645-646-class Namespace(object):647- """A namespace object that can hold arbitrary attributes. It may be648- initialized from a dictionary or with keyword arguments."""649-650- def __init__(*args, **kwargs):651- self, args = args[0], args[1:]652- self.__attrs = dict(*args, **kwargs)653-654- def __getattribute__(self, name):655- if name == '_Namespace__attrs':656- return object.__getattribute__(self, name)657- try:658- return self.__attrs[name]659- except KeyError:660- raise AttributeError(name)661-662- def __setitem__(self, name, value):663- self.__attrs[name] = value664-665- def __repr__(self):666- return '<Namespace %r>' % self.__attrs667-668-669-# does this python version support async for in and async generators?670-try:671- exec('async def _():\n async for _ in ():\n yield _')672- have_async_gen = True673-except SyntaxError:674- have_async_gen = False675-676-677-# Imported here because that's where it was in the past678-from markupsafe import Markup, escape, soft_unicodedeleted:jinja2/visitor.py-87 removed
1-# -*- coding: utf-8 -*-2-"""3- jinja2.visitor4- ~~~~~~~~~~~~~~5-6- This module implements a visitor for the nodes.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD.10-"""11-from jinja2.nodes import Node12-13-14-class NodeVisitor(object):15- """Walks the abstract syntax tree and call visitor functions for every16- node found. The visitor functions may return values which will be17- forwarded by the `visit` method.18-19- Per default the visitor functions for the nodes are ``'visit_'`` +20- class name of the node. So a `TryFinally` node visit function would21- be `visit_TryFinally`. This behavior can be changed by overriding22- the `get_visitor` function. If no visitor function exists for a node23- (return value `None`) the `generic_visit` visitor is used instead.24- """25-26- def get_visitor(self, node):27- """Return the visitor function for this node or `None` if no visitor28- exists for this node. In that case the generic visit function is29- used instead.30- """31- method = 'visit_' + node.__class__.__name__32- return getattr(self, method, None)33-34- def visit(self, node, *args, **kwargs):35- """Visit a node."""36- f = self.get_visitor(node)37- if f is not None:38- return f(node, *args, **kwargs)39- return self.generic_visit(node, *args, **kwargs)40-41- def generic_visit(self, node, *args, **kwargs):42- """Called if no explicit visitor function exists for a node."""43- for node in node.iter_child_nodes():44- self.visit(node, *args, **kwargs)45-46-47-class NodeTransformer(NodeVisitor):48- """Walks the abstract syntax tree and allows modifications of nodes.49-50- The `NodeTransformer` will walk the AST and use the return value of the51- visitor functions to replace or remove the old node. If the return52- value of the visitor function is `None` the node will be removed53- from the previous location otherwise it's replaced with the return54- value. The return value may be the original node in which case no55- replacement takes place.56- """57-58- def generic_visit(self, node, *args, **kwargs):59- for field, old_value in node.iter_fields():60- if isinstance(old_value, list):61- new_values = []62- for value in old_value:63- if isinstance(value, Node):64- value = self.visit(value, *args, **kwargs)65- if value is None:66- continue67- elif not isinstance(value, Node):68- new_values.extend(value)69- continue70- new_values.append(value)71- old_value[:] = new_values72- elif isinstance(old_value, Node):73- new_node = self.visit(old_value, *args, **kwargs)74- if new_node is None:75- delattr(node, field)76- else:77- setattr(node, field, new_node)78- return node79-80- def visit_list(self, node, *args, **kwargs):81- """As transformers may return lists in some places this method82- can be used to enforce a list as return value.83- """84- rv = self.visit(node, *args, **kwargs)85- if not isinstance(rv, list):86- rv = [rv]87- return rvmodified:scripts/generate_identifier_pattern.py+20 added-19 removed
3 unmodified lines4 import re5 import sys6 7 if sys.version_info[0] < 3:8- raise RuntimeError('This needs to run on Python 3.')8+ raise RuntimeError("This needs to run on Python 3.")9 10 11 def get_characters():12 """Find every Unicode character that is valid in a Python `identifier`_ but13- is not matched by the regex ``\w`` group.13+ is not matched by the regex ``\\w`` group.14 15- ``\w`` matches some characters that aren't valid in identifiers, but15+ ``\\w`` matches some characters that aren't valid in identifiers, but16 :meth:`str.isidentifier` will catch that later in lexing.17 18 All start characters are valid continue characters, so we only test for19 continue characters.2 unmodified lines22 """23 for cp in range(sys.maxunicode + 1):24 s = chr(cp)25 26- if ('a' + s).isidentifier() and not re.match(r'\w', s):26+ if ("a" + s).isidentifier() and not re.match(r"\w", s):27 yield s28 29 30 def collapse_ranges(data):1 unmodified line32 sequential code points.33 34 Source: https://stackoverflow.com/a/4629241/40061735 """36- for a, b in itertools.groupby(37- enumerate(data),38- lambda x: ord(x[1]) - x[0]39- ):36+ for _, b in itertools.groupby(enumerate(data), lambda x: ord(x[1]) - x[0]):37 b = list(b)38 yield b[0][1], b[-1][1]39 40 10 unmodified lines51 elif ord(b) - ord(a) == 1: # two chars, range is redundant52 out.append(a)53 out.append(b)54 else:58- out.append(f'{a}-{b}')55+ out.append("{}-{}".format(a, b))56 60- return ''.join(out)57+ return "".join(out)58 59 60 def main():64- """Build the regex pattern and write it to the file65- :file:`jinja2/_identifier.py`."""61+ """Build the regex pattern and write it to62+ ``jinja2/_identifier.py``.63+ """64 pattern = build_pattern(collapse_ranges(get_characters()))67- filename = os.path.abspath(os.path.join(68- os.path.dirname(__file__), '..', 'jinja2', '_identifier.py'69- ))65+ filename = os.path.abspath(66+ os.path.join(os.path.dirname(__file__), "..", "src", "jinja2", "_identifier.py")67+ )68 71- with open(filename, 'w', encoding='utf8') as f:72- f.write('# generated by scripts/generate_identifier_pattern.py\n')73- f.write(f'pattern = \'{pattern}\'\n')69+ with open(filename, "w", encoding="utf8") as f:70+ f.write("import re\n\n")71+ f.write("# generated by scripts/generate_identifier_pattern.py\n")72+ f.write("pattern = re.compile(\n")73+ f.write(' r"[\\w{}]+" # noqa: B950\n'.format(pattern))74+ f.write(")\n")75 76 76-if __name__ == '__main__':77+if __name__ == "__main__":78 main()deleted:scripts/jinja2-debug.py-44 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-"""4- Jinja Debug Interface5- ~~~~~~~~~~~~~~~~~~~~~6-7- Helper script for internal Jinja debugging. Requires Werkzeug.8-9- :copyright: Copyright 2010 by Armin Ronacher.10- :license: BSD.11-"""12-from __future__ import print_function13-import sys14-import jinja215-from werkzeug import script16-17-env = jinja2.Environment(extensions=['jinja2.ext.i18n', 'jinja2.ext.do',18- 'jinja2.ext.loopcontrols',19- 'jinja2.ext.with_',20- 'jinja2.ext.autoescape'],21- autoescape=True)22-23-def shell_init_func():24- def _compile(x):25- print(env.compile(x, raw=True))26- result = {27- 'e': env,28- 'c': _compile,29- 't': env.from_string,30- 'p': env.parse31- }32- for key in jinja2.__all__:33- result[key] = getattr(jinja2, key)34- return result35-36-37-def action_compile():38- print(env.compile(sys.stdin.read(), raw=True))39-40-action_shell = script.make_shell(shell_init_func)41-42-43-if __name__ == '__main__':44- script.run()deleted:scripts/make-release.py-180 removed
1-#!/usr/bin/env python2-# -*- coding: utf-8 -*-3-"""4- make-release5- ~~~~~~~~~~~~6-7- Helper script that performs a release. Does pretty much everything8- automatically for us.9-10- :copyright: (c) 2011 by Armin Ronacher.11- :license: BSD, see LICENSE for more details.12-"""13-from __future__ import print_function14-15-import os16-import re17-import sys18-from datetime import date, datetime19-from subprocess import PIPE, Popen20-21-_date_strip_re = re.compile(r'(?<=\d)(st|nd|rd|th)')22-23-24-def parse_changelog():25- with open('CHANGES.rst') as f:26- lineiter = iter(f)27- for line in lineiter:28- match = re.search('^Version\s+(.*)', line.strip())29-30- if match is None:31- continue32-33- version = match.group(1).strip()34-35- if next(lineiter).count('-') != len(match.group(0)):36- continue37-38- while 1:39- change_info = next(lineiter).strip()40-41- if change_info:42- break43-44- match = re.search(45- r'(?:codename (.*),\s*)?released on (\w+\s+\d+\w+\s+\d+)(?i)',46- change_info47- )48-49- if match is None:50- continue51-52- codename, datestr = match.groups()53- return version, parse_date(datestr), codename54-55-56-def bump_version(version):57- try:58- parts = [int(i) for i in version.split('.')]59- except ValueError:60- fail('Current version is not numeric')61-62- parts[-1] += 163- return '.'.join(map(str, parts))64-65-66-def parse_date(string):67- string = _date_strip_re.sub('', string)68- return datetime.strptime(string, '%B %d %Y')69-70-71-def set_filename_version(filename, version_number, pattern):72- changed = []73-74- def inject_version(match):75- before, old, after = match.groups()76- changed.append(True)77- return before + version_number + after78-79- with open(filename) as f:80- contents = re.sub(81- r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern,82- inject_version, f.read()83- )84-85- if not changed:86- fail('Could not find %s in %s', pattern, filename)87-88- with open(filename, 'w') as f:89- f.write(contents)90-91-92-def set_init_version(version):93- info('Setting __init__.py version to %s', version)94- set_filename_version('jinja2/__init__.py', version, '__version__')95-96-97-def set_setup_version(version):98- info('Setting setup.py version to %s', version)99- set_filename_version('setup.py', version, 'version')100-101-102-def build_and_upload():103- cmd = [sys.executable, 'setup.py', 'sdist', 'bdist_wheel']104- Popen(cmd).wait()105-106-107-def fail(message, *args):108- print('Error:', message % args, file=sys.stderr)109- sys.exit(1)110-111-112-def info(message, *args):113- print(message % args, file=sys.stderr)114-115-116-def get_git_tags():117- return set(118- Popen(['git', 'tag'], stdout=PIPE).communicate()[0].splitlines()119- )120-121-122-def git_is_clean():123- return Popen(['git', 'diff', '--quiet']).wait() == 0124-125-126-def make_git_commit(message, *args):127- message = message % args128- Popen(['git', 'commit', '-am', message]).wait()129-130-131-def make_git_tag(tag):132- info('Tagging "%s"', tag)133- Popen(['git', 'tag', tag]).wait()134-135-136-def main():137- os.chdir(os.path.join(os.path.dirname(__file__), '..'))138-139- rv = parse_changelog()140-141- if rv is None:142- fail('Could not parse changelog')143-144- version, release_date, codename = rv145- dev_version = bump_version(version) + '.dev'146-147- info(148- 'Releasing %s (codename %s, release date %s)',149- version, codename, release_date.strftime('%d/%m/%Y')150- )151- tags = get_git_tags()152-153- if version in tags:154- fail('Version "%s" is already tagged', version)155-156- if release_date.date() != date.today():157- fail(158- 'Release date is not today (%s != %s)',159- release_date.date(), date.today()160- )161-162- if not git_is_clean():163- fail('You have uncommitted changes in git')164-165- try:166- import wheel167- except ImportError:168- fail('You need to install the wheel package.')169-170- set_init_version(version)171- set_setup_version(version)172- make_git_commit('Bump version number to %s', version)173- make_git_tag(version)174- build_and_upload()175- set_init_version(dev_version)176- set_setup_version(dev_version)177-178-179-if __name__ == '__main__':180- main()deleted:scripts/pylintrc-301 removed
1-# lint Python modules using external checkers.2-#3-# This is the main checker controlling the other ones and the reports4-# generation. It is itself both a raw checker and an astng checker in order5-# to:6-# * handle message activation / deactivation at the module level7-# * handle some basic but necessary stats'data (number of classes, methods...)8-#9-[MASTER]10-11-# Specify a configuration file.12-#rcfile=13-14-# Profiled execution.15-profile=no16-17-# Add <file or directory> to the black list. It should be a base name, not a18-# path. You may set this option multiple times.19-ignore=.svn20-21-# Pickle collected data for later comparisons.22-persistent=yes23-24-# Set the cache size for astng objects.25-cache-size=50026-27-# List of plugins (as comma separated values of python modules names) to load,28-# usually to register additional checkers.29-load-plugins=30-31-32-[MESSAGES CONTROL]33-34-# Enable only checker(s) with the given id(s). This option conflict with the35-# disable-checker option36-#enable-checker=37-38-# Enable all checker(s) except those with the given id(s). This option conflict39-# with the disable-checker option40-#disable-checker=41-42-# Enable all messages in the listed categories.43-#enable-msg-cat=44-45-# Disable all messages in the listed categories.46-#disable-msg-cat=47-48-# Enable the message(s) with the given id(s).49-#enable-msg=50-51-# Disable the message(s) with the given id(s).52-disable-msg=C0323,W0142,C0301,C0103,C0111,E0213,C0302,C0203,W0703,R020153-54-55-[REPORTS]56-57-# set the output format. Available formats are text, parseable, colorized and58-# html59-output-format=colorized60-61-# Include message's id in output62-include-ids=yes63-64-# Put messages in a separate file for each module / package specified on the65-# command line instead of printing them on stdout. Reports (if any) will be66-# written in a file name "pylint_global.[txt|html]".67-files-output=no68-69-# Tells whether to display a full report or only the messages70-reports=yes71-72-# Python expression which should return a note less than 10 (10 is the highest73-# note).You have access to the variables errors warning, statement which74-# respectively contain the number of errors / warnings messages and the total75-# number of statements analyzed. This is used by the global evaluation report76-# (R0004).77-evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)78-79-# Add a comment according to your evaluation note. This is used by the global80-# evaluation report (R0004).81-comment=no82-83-# Enable the report(s) with the given id(s).84-#enable-report=85-86-# Disable the report(s) with the given id(s).87-#disable-report=88-89-90-# checks for91-# * unused variables / imports92-# * undefined variables93-# * redefinition of variable from builtins or from an outer scope94-# * use of variable before assignment95-#96-[VARIABLES]97-98-# Tells whether we should check for unused import in __init__ files.99-init-import=no100-101-# A regular expression matching names used for dummy variables (i.e. not used).102-dummy-variables-rgx=_|dummy103-104-# List of additional names supposed to be defined in builtins. Remember that105-# you should avoid to define new builtins when possible.106-additional-builtins=107-108-109-# try to find bugs in the code using type inference110-#111-[TYPECHECK]112-113-# Tells whether missing members accessed in mixin class should be ignored. A114-# mixin class is detected if its name ends with "mixin" (case insensitive).115-ignore-mixin-members=yes116-117-# When zope mode is activated, consider the acquired-members option to ignore118-# access to some undefined attributes.119-zope=no120-121-# List of members which are usually gotten through zope's acquisition mechanism122-# and so shouldn't trigger E0201 when accessed (need zope=yes to be considered)123-acquired-members=REQUEST,acl_users,aq_parent124-125-126-# checks for :127-# * doc strings128-# * modules / classes / functions / methods / arguments / variables name129-# * number of arguments, local variables, branchs, returns and statements in130-# functions, methods131-# * required module attributes132-# * dangerous default values as arguments133-# * redefinition of function / method / class134-# * uses of the global statement135-#136-[BASIC]137-138-# Required attributes for module, separated by a comma139-required-attributes=140-141-# Regular expression which should only match functions or classes name which do142-# not require a docstring143-no-docstring-rgx=__.*__144-145-# Regular expression which should only match correct module names146-module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$147-148-# Regular expression which should only match correct module level names149-const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__))$150-151-# Regular expression which should only match correct class names152-class-rgx=[A-Z_][a-zA-Z0-9]+$153-154-# Regular expression which should only match correct function names155-function-rgx=[a-z_][a-z0-9_]*$156-157-# Regular expression which should only match correct method names158-method-rgx=[a-z_][a-z0-9_]*$159-160-# Regular expression which should only match correct instance attribute names161-attr-rgx=[a-z_][a-z0-9_]*$162-163-# Regular expression which should only match correct argument names164-argument-rgx=[a-z_][a-z0-9_]*$165-166-# Regular expression which should only match correct variable names167-variable-rgx=[a-z_][a-z0-9_]*$168-169-# Regular expression which should only match correct list comprehension /170-# generator expression variable names171-inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$172-173-# Good variable names which should always be accepted, separated by a comma174-good-names=i,j,k,ex,Run,_175-176-# Bad variable names which should always be refused, separated by a comma177-bad-names=foo,bar,baz,toto,tutu,tata178-179-# List of builtins function names that should not be used, separated by a comma180-bad-functions=apply,input181-182-183-# checks for sign of poor/misdesign:184-# * number of methods, attributes, local variables...185-# * size, complexity of functions, methods186-#187-[DESIGN]188-189-# Maximum number of arguments for function / method190-max-args=12191-192-# Maximum number of locals for function / method body193-max-locals=30194-195-# Maximum number of return / yield for function / method body196-max-returns=12197-198-# Maximum number of branch for function / method body199-max-branchs=30200-201-# Maximum number of statements in function / method body202-max-statements=60203-204-# Maximum number of parents for a class (see R0901).205-max-parents=7206-207-# Maximum number of attributes for a class (see R0902).208-max-attributes=20209-210-# Minimum number of public methods for a class (see R0903).211-min-public-methods=0212-213-# Maximum number of public methods for a class (see R0904).214-max-public-methods=20215-216-217-# checks for218-# * external modules dependencies219-# * relative / wildcard imports220-# * cyclic imports221-# * uses of deprecated modules222-#223-[IMPORTS]224-225-# Deprecated modules which should not be used, separated by a comma226-deprecated-modules=regsub,string,TERMIOS,Bastion,rexec227-228-# Create a graph of every (i.e. internal and external) dependencies in the229-# given file (report R0402 must not be disabled)230-import-graph=231-232-# Create a graph of external dependencies in the given file (report R0402 must233-# not be disabled)234-ext-import-graph=235-236-# Create a graph of internal dependencies in the given file (report R0402 must237-# not be disabled)238-int-import-graph=239-240-241-# checks for :242-# * methods without self as first argument243-# * overridden methods signature244-# * access only to existent members via self245-# * attributes not defined in the __init__ method246-# * supported interfaces implementation247-# * unreachable code248-#249-[CLASSES]250-251-# List of interface methods to ignore, separated by a comma. This is used for252-# instance to not check methods defines in Zope's Interface base class.253-ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by254-255-# List of method names used to declare (i.e. assign) instance attributes.256-defining-attr-methods=__init__,__new__,setUp257-258-259-# checks for similarities and duplicated code. This computation may be260-# memory / CPU intensive, so you should disable it if you experiments some261-# problems.262-#263-[SIMILARITIES]264-265-# Minimum lines number of a similarity.266-min-similarity-lines=10267-268-# Ignore comments when computing similarities.269-ignore-comments=yes270-271-# Ignore docstrings when computing similarities.272-ignore-docstrings=yes273-274-275-# checks for:276-# * warning notes in the code like FIXME, XXX277-# * PEP 263: source code with non ascii character but no encoding declaration278-#279-[MISCELLANEOUS]280-281-# List of note tags to take in consideration, separated by a comma.282-notes=FIXME,XXX,TODO283-284-285-# checks for :286-# * unauthorized constructions287-# * strict indentation288-# * line length289-# * use of <> instead of !=290-#291-[FORMAT]292-293-# Maximum number of characters on a single line.294-max-line-length=90295-296-# Maximum number of lines in a module297-max-module-lines=1000298-299-# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1300-# tab).301-indent-string=' 'added:src/jinja2/__init__.py+43 added
1+# -*- coding: utf-8 -*-2+"""Jinja is a template engine written in pure Python. It provides a3+non-XML syntax that supports inline expressions and an optional4+sandboxed environment.5+"""6+from .bccache import BytecodeCache7+from .bccache import FileSystemBytecodeCache8+from .bccache import MemcachedBytecodeCache9+from .environment import Environment10+from .environment import Template11+from .exceptions import TemplateAssertionError12+from .exceptions import TemplateError13+from .exceptions import TemplateNotFound14+from .exceptions import TemplateRuntimeError15+from .exceptions import TemplatesNotFound16+from .exceptions import TemplateSyntaxError17+from .exceptions import UndefinedError18+from .filters import contextfilter19+from .filters import environmentfilter20+from .filters import evalcontextfilter21+from .loaders import BaseLoader22+from .loaders import ChoiceLoader23+from .loaders import DictLoader24+from .loaders import FileSystemLoader25+from .loaders import FunctionLoader26+from .loaders import ModuleLoader27+from .loaders import PackageLoader28+from .loaders import PrefixLoader29+from .runtime import ChainableUndefined30+from .runtime import DebugUndefined31+from .runtime import make_logging_undefined32+from .runtime import StrictUndefined33+from .runtime import Undefined34+from .utils import clear_caches35+from .utils import contextfunction36+from .utils import environmentfunction37+from .utils import escape38+from .utils import evalcontextfunction39+from .utils import is_undefined40+from .utils import Markup41+from .utils import select_autoescape42+43+__version__ = "2.11.0.dev0"added:src/jinja2/_compat.py+132 added
1+# -*- coding: utf-8 -*-2+# flake8: noqa3+import marshal4+import sys5+6+PY2 = sys.version_info[0] == 27+PYPY = hasattr(sys, "pypy_translation_info")8+_identity = lambda x: x9+10+if not PY2:11+ unichr = chr12+ range_type = range13+ text_type = str14+ string_types = (str,)15+ integer_types = (int,)16+17+ iterkeys = lambda d: iter(d.keys())18+ itervalues = lambda d: iter(d.values())19+ iteritems = lambda d: iter(d.items())20+21+ import pickle22+ from io import BytesIO, StringIO23+24+ NativeStringIO = StringIO25+26+ def reraise(tp, value, tb=None):27+ if value.__traceback__ is not tb:28+ raise value.with_traceback(tb)29+ raise value30+31+ ifilter = filter32+ imap = map33+ izip = zip34+ intern = sys.intern35+36+ implements_iterator = _identity37+ implements_to_string = _identity38+ encode_filename = _identity39+40+ marshal_dump = marshal.dump41+ marshal_load = marshal.load42+43+else:44+ unichr = unichr45+ text_type = unicode46+ range_type = xrange47+ string_types = (str, unicode)48+ integer_types = (int, long)49+50+ iterkeys = lambda d: d.iterkeys()51+ itervalues = lambda d: d.itervalues()52+ iteritems = lambda d: d.iteritems()53+54+ import cPickle as pickle55+ from cStringIO import StringIO as BytesIO, StringIO56+57+ NativeStringIO = BytesIO58+59+ exec("def reraise(tp, value, tb=None):\n raise tp, value, tb")60+61+ from itertools import imap, izip, ifilter62+63+ intern = intern64+65+ def implements_iterator(cls):66+ cls.next = cls.__next__67+ del cls.__next__68+ return cls69+70+ def implements_to_string(cls):71+ cls.__unicode__ = cls.__str__72+ cls.__str__ = lambda x: x.__unicode__().encode("utf-8")73+ return cls74+75+ def encode_filename(filename):76+ if isinstance(filename, unicode):77+ return filename.encode("utf-8")78+ return filename79+80+ def marshal_dump(code, f):81+ if isinstance(f, file):82+ marshal.dump(code, f)83+ else:84+ f.write(marshal.dumps(code))85+86+ def marshal_load(f):87+ if isinstance(f, file):88+ return marshal.load(f)89+ return marshal.loads(f.read())90+91+92+def 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)100+101+ return type.__new__(metaclass, "temporary_class", (), {})102+103+104+try:105+ from urllib.parse import quote_from_bytes as url_quote106+except ImportError:107+ from urllib import quote as url_quote108+109+110+try:111+ from collections import abc112+except ImportError:113+ import collections as abc114+115+116+try:117+ from os import fspath118+except ImportError:119+ try:120+ from pathlib import PurePath121+ except ImportError:122+ PurePath = None123+124+ def fspath(path):125+ if hasattr(path, "__fspath__"):126+ return path.__fspath__()127+128+ # Python 3.5 doesn't have __fspath__ yet, use str.129+ if PurePath is not None and isinstance(path, PurePath):130+ return str(path)131+132+ return pathadded:src/jinja2/_identifier.py+6 added
1+import re2+3+# generated by scripts/generate_identifier_pattern.py4+pattern = re.compile(5+ r"[\w·̀-ͯ·҃-֑҇-ׇֽֿׁׂׅׄؐ-ًؚ-ٰٟۖ-ۜ۟-۪ۤۧۨ-ܑۭܰ-݊ަ-ް߫-߳ࠖ-࠙ࠛ-ࠣࠥ-ࠧࠩ-࡙࠭-࡛ࣔ-ࣣ࣡-ःऺ-़ा-ॏ॑-ॗॢॣঁ-ঃ়া-ৄেৈো-্ৗৢৣਁ-ਃ਼ਾ-ੂੇੈੋ-੍ੑੰੱੵઁ-ઃ઼ા-ૅે-ૉો-્ૢૣଁ-ଃ଼ା-ୄେୈୋ-୍ୖୗୢୣஂா-ூெ-ைொ-்ௗఀ-ఃా-ౄె-ైొ-్ౕౖౢౣಁ-ಃ಼ಾ-ೄೆ-ೈೊ-್ೕೖೢೣഁ-ഃാ-ൄെ-ൈൊ-്ൗൢൣංඃ්ා-ුූෘ-ෟෲෳัิ-ฺ็-๎ັິ-ູົຼ່-ໍ༹༘༙༵༷༾༿ཱ-྄྆྇ྍ-ྗྙ-ྼ࿆ါ-ှၖ-ၙၞ-ၠၢ-ၤၧ-ၭၱ-ၴႂ-ႍႏႚ-ႝ፝-፟ᜒ-᜔ᜲ-᜴ᝒᝓᝲᝳ឴-៓៝᠋-᠍ᢅᢆᢩᤠ-ᤫᤰ-᤻ᨗ-ᨛᩕ-ᩞ᩠-᩿᩼᪰-᪽ᬀ-ᬄ᬴-᭄᭫-᭳ᮀ-ᮂᮡ-ᮭ᯦-᯳ᰤ-᰷᳐-᳔᳒-᳨᳭ᳲ-᳴᳸᳹᷀-᷵᷻-᷿‿⁀⁔⃐-⃥⃜⃡-⃰℘℮⳯-⵿⳱ⷠ-〪ⷿ-゙゚〯꙯ꙴ-꙽ꚞꚟ꛰꛱ꠂ꠆ꠋꠣ-ꠧꢀꢁꢴ-ꣅ꣠-꣱ꤦ-꤭ꥇ-꥓ꦀ-ꦃ꦳-꧀ꧥꨩ-ꨶꩃꩌꩍꩻ-ꩽꪰꪲ-ꪴꪷꪸꪾ꪿꫁ꫫ-ꫯꫵ꫶ꯣ-ꯪ꯬꯭ﬞ︀-️︠-︯︳︴﹍-﹏_𐇽𐋠𐍶-𐍺𐨁-𐨃𐨅𐨆𐨌-𐨏𐨸-𐨿𐨺𐫦𐫥𑀀-𑀂𑀸-𑁆𑁿-𑂂𑂰-𑂺𑄀-𑄂𑄧-𑅳𑄴𑆀-𑆂𑆳-𑇊𑇀-𑇌𑈬-𑈷𑈾𑋟-𑋪𑌀-𑌃𑌼𑌾-𑍄𑍇𑍈𑍋-𑍍𑍗𑍢𑍣𑍦-𑍬𑍰-𑍴𑐵-𑑆𑒰-𑓃𑖯-𑖵𑖸-𑗀𑗜𑗝𑘰-𑙀𑚫-𑚷𑜝-𑜫𑰯-𑰶𑰸-𑰿𑲒-𑲧𑲩-𑲶𖫰-𖫴𖬰-𖬶𖽑-𖽾𖾏-𖾒𛲝𛲞𝅥-𝅩𝅭-𝅲𝅻-𝆂𝆅-𝆋𝆪-𝆭𝉂-𝉄𝨀-𝨶𝨻-𝩬𝩵𝪄𝪛-𝪟𝪡-𝪯𞀀-𞀆𞀈-𞀘𞀛-𞀡𞀣𞀤𞀦-𞣐𞀪-𞣖𞥄-𞥊󠄀-󠇯]+" # noqa: B9506+)added:src/jinja2/asyncfilters.py+159 added
1+from functools import wraps2+3+from . import filters4+from .asyncsupport import auto_aiter5+from .asyncsupport import auto_await6+7+8+async def auto_to_seq(value):9+ seq = []10+ if hasattr(value, "__aiter__"):11+ async for item in value:12+ seq.append(item)13+ else:14+ for item in value:15+ seq.append(item)16+ return seq17+18+19+async def async_select_or_reject(args, kwargs, modfunc, lookup_attr):20+ seq, func = filters.prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)21+ if seq:22+ async for item in auto_aiter(seq):23+ if func(item):24+ yield item25+26+27+def dualfilter(normal_filter, async_filter):28+ wrap_evalctx = False29+ if getattr(normal_filter, "environmentfilter", False):30+31+ def is_async(args):32+ return args[0].is_async33+34+ wrap_evalctx = False35+ else:36+ if not getattr(normal_filter, "evalcontextfilter", False) and not getattr(37+ normal_filter, "contextfilter", False38+ ):39+ wrap_evalctx = True40+41+ def is_async(args):42+ return args[0].environment.is_async43+44+ @wraps(normal_filter)45+ def wrapper(*args, **kwargs):46+ b = is_async(args)47+ if wrap_evalctx:48+ args = args[1:]49+ if b:50+ return async_filter(*args, **kwargs)51+ return normal_filter(*args, **kwargs)52+53+ if wrap_evalctx:54+ wrapper.evalcontextfilter = True55+56+ wrapper.asyncfiltervariant = True57+58+ return wrapper59+60+61+def asyncfiltervariant(original):62+ def decorator(f):63+ return dualfilter(original, f)64+65+ return decorator66+67+68+@asyncfiltervariant(filters.do_first)69+async def do_first(environment, seq):70+ try:71+ return await auto_aiter(seq).__anext__()72+ except StopAsyncIteration:73+ return environment.undefined("No first item, sequence was empty.")74+75+76+@asyncfiltervariant(filters.do_groupby)77+async def do_groupby(environment, value, attribute):78+ expr = filters.make_attrgetter(environment, attribute)79+ return [80+ filters._GroupTuple(key, await auto_to_seq(values))81+ for key, values in filters.groupby(82+ sorted(await auto_to_seq(value), key=expr), expr83+ )84+ ]85+86+87+@asyncfiltervariant(filters.do_join)88+async def do_join(eval_ctx, value, d=u"", attribute=None):89+ return filters.do_join(eval_ctx, await auto_to_seq(value), d, attribute)90+91+92+@asyncfiltervariant(filters.do_list)93+async def do_list(value):94+ return await auto_to_seq(value)95+96+97+@asyncfiltervariant(filters.do_reject)98+async def do_reject(*args, **kwargs):99+ return async_select_or_reject(args, kwargs, lambda x: not x, False)100+101+102+@asyncfiltervariant(filters.do_rejectattr)103+async def do_rejectattr(*args, **kwargs):104+ return async_select_or_reject(args, kwargs, lambda x: not x, True)105+106+107+@asyncfiltervariant(filters.do_select)108+async def do_select(*args, **kwargs):109+ return async_select_or_reject(args, kwargs, lambda x: x, False)110+111+112+@asyncfiltervariant(filters.do_selectattr)113+async def do_selectattr(*args, **kwargs):114+ return async_select_or_reject(args, kwargs, lambda x: x, True)115+116+117+@asyncfiltervariant(filters.do_map)118+async def do_map(*args, **kwargs):119+ seq, func = filters.prepare_map(args, kwargs)120+ if seq:121+ async for item in auto_aiter(seq):122+ yield await auto_await(func(item))123+124+125+@asyncfiltervariant(filters.do_sum)126+async def do_sum(environment, iterable, attribute=None, start=0):127+ rv = start128+ if attribute is not None:129+ func = filters.make_attrgetter(environment, attribute)130+ else:131+132+ def func(x):133+ return x134+135+ async for item in auto_aiter(iterable):136+ rv += func(item)137+ return rv138+139+140+@asyncfiltervariant(filters.do_slice)141+async def do_slice(value, slices, fill_with=None):142+ return filters.do_slice(await auto_to_seq(value), slices, fill_with)143+144+145+ASYNC_FILTERS = {146+ "first": do_first,147+ "groupby": do_groupby,148+ "join": do_join,149+ "list": do_list,150+ # we intentionally do not support do_last because that would be151+ # ridiculous152+ "reject": do_reject,153+ "rejectattr": do_rejectattr,154+ "map": do_map,155+ "select": do_select,156+ "selectattr": do_selectattr,157+ "sum": do_sum,158+ "slice": do_slice,159+}added:src/jinja2/asyncsupport.py+263 added
1+# -*- coding: utf-8 -*-2+"""The code for async support. Importing this patches Jinja on supported3+Python versions.4+"""5+import asyncio6+import inspect7+from functools import update_wrapper8+9+from .environment import TemplateModule10+from .runtime import LoopContext11+from .utils import concat12+from .utils import internalcode13+from .utils import Markup14+from .utils import missing15+16+17+async def concat_async(async_gen):18+ rv = []19+20+ async def collect():21+ async for event in async_gen:22+ rv.append(event)23+24+ await collect()25+ return concat(rv)26+27+28+async def generate_async(self, *args, **kwargs):29+ vars = dict(*args, **kwargs)30+ try:31+ async for event in self.root_render_func(self.new_context(vars)):32+ yield event33+ except Exception:34+ yield self.environment.handle_exception()35+36+37+def wrap_generate_func(original_generate):38+ def _convert_generator(self, loop, args, kwargs):39+ async_gen = self.generate_async(*args, **kwargs)40+ try:41+ while 1:42+ yield loop.run_until_complete(async_gen.__anext__())43+ except StopAsyncIteration:44+ pass45+46+ def generate(self, *args, **kwargs):47+ if not self.environment.is_async:48+ return original_generate(self, *args, **kwargs)49+ return _convert_generator(self, asyncio.get_event_loop(), args, kwargs)50+51+ return update_wrapper(generate, original_generate)52+53+54+async def render_async(self, *args, **kwargs):55+ if not self.environment.is_async:56+ raise RuntimeError("The environment was not created with async mode enabled.")57+58+ vars = dict(*args, **kwargs)59+ ctx = self.new_context(vars)60+61+ try:62+ return await concat_async(self.root_render_func(ctx))63+ except Exception:64+ return self.environment.handle_exception()65+66+67+def wrap_render_func(original_render):68+ def render(self, *args, **kwargs):69+ if not self.environment.is_async:70+ return original_render(self, *args, **kwargs)71+ loop = asyncio.get_event_loop()72+ return loop.run_until_complete(self.render_async(*args, **kwargs))73+74+ return update_wrapper(render, original_render)75+76+77+def wrap_block_reference_call(original_call):78+ @internalcode79+ async def async_call(self):80+ rv = await concat_async(self._stack[self._depth](self._context))81+ if self._context.eval_ctx.autoescape:82+ rv = Markup(rv)83+ return rv84+85+ @internalcode86+ def __call__(self):87+ if not self._context.environment.is_async:88+ return original_call(self)89+ return async_call(self)90+91+ return update_wrapper(__call__, original_call)92+93+94+def wrap_macro_invoke(original_invoke):95+ @internalcode96+ async def async_invoke(self, arguments, autoescape):97+ rv = await self._func(*arguments)98+ if autoescape:99+ rv = Markup(rv)100+ return rv101+102+ @internalcode103+ def _invoke(self, arguments, autoescape):104+ if not self._environment.is_async:105+ return original_invoke(self, arguments, autoescape)106+ return async_invoke(self, arguments, autoescape)107+108+ return update_wrapper(_invoke, original_invoke)109+110+111+@internalcode112+async def get_default_module_async(self):113+ if self._module is not None:114+ return self._module115+ self._module = rv = await self.make_module_async()116+ return rv117+118+119+def wrap_default_module(original_default_module):120+ @internalcode121+ def _get_default_module(self):122+ if self.environment.is_async:123+ raise RuntimeError("Template module attribute is unavailable in async mode")124+ return original_default_module(self)125+126+ return _get_default_module127+128+129+async def make_module_async(self, vars=None, shared=False, locals=None):130+ context = self.new_context(vars, shared, locals)131+ body_stream = []132+ async for item in self.root_render_func(context):133+ body_stream.append(item)134+ return TemplateModule(self, context, body_stream)135+136+137+def patch_template():138+ from . import Template139+140+ Template.generate = wrap_generate_func(Template.generate)141+ Template.generate_async = update_wrapper(generate_async, Template.generate_async)142+ Template.render_async = update_wrapper(render_async, Template.render_async)143+ Template.render = wrap_render_func(Template.render)144+ Template._get_default_module = wrap_default_module(Template._get_default_module)145+ Template._get_default_module_async = get_default_module_async146+ Template.make_module_async = update_wrapper(147+ make_module_async, Template.make_module_async148+ )149+150+151+def patch_runtime():152+ from .runtime import BlockReference, Macro153+154+ BlockReference.__call__ = wrap_block_reference_call(BlockReference.__call__)155+ Macro._invoke = wrap_macro_invoke(Macro._invoke)156+157+158+def patch_filters():159+ from .filters import FILTERS160+ from .asyncfilters import ASYNC_FILTERS161+162+ FILTERS.update(ASYNC_FILTERS)163+164+165+def patch_all():166+ patch_template()167+ patch_runtime()168+ patch_filters()169+170+171+async def auto_await(value):172+ if inspect.isawaitable(value):173+ return await value174+ return value175+176+177+async def auto_aiter(iterable):178+ if hasattr(iterable, "__aiter__"):179+ async for item in iterable:180+ yield item181+ return182+ for item in iterable:183+ yield item184+185+186+class AsyncLoopContext(LoopContext):187+ _to_iterator = staticmethod(auto_aiter)188+189+ @property190+ async def length(self):191+ if self._length is not None:192+ return self._length193+194+ try:195+ self._length = len(self._iterable)196+ except TypeError:197+ iterable = [x async for x in self._iterator]198+ self._iterator = self._to_iterator(iterable)199+ self._length = len(iterable) + self.index + (self._after is not missing)200+201+ return self._length202+203+ @property204+ async def revindex0(self):205+ return await self.length - self.index206+207+ @property208+ async def revindex(self):209+ return await self.length - self.index0210+211+ async def _peek_next(self):212+ if self._after is not missing:213+ return self._after214+215+ try:216+ self._after = await self._iterator.__anext__()217+ except StopAsyncIteration:218+ self._after = missing219+220+ return self._after221+222+ @property223+ async def last(self):224+ return await self._peek_next() is missing225+226+ @property227+ async def nextitem(self):228+ rv = await self._peek_next()229+230+ if rv is missing:231+ return self._undefined("there is no next item")232+233+ return rv234+235+ def __aiter__(self):236+ return self237+238+ async def __anext__(self):239+ if self._after is not missing:240+ rv = self._after241+ self._after = missing242+ else:243+ rv = await self._iterator.__anext__()244+245+ self.index0 += 1246+ self._before = self._current247+ self._current = rv248+ return rv, self249+250+251+async def make_async_loop_context(iterable, undefined, recurse=None, depth0=0):252+ import warnings253+254+ warnings.warn(255+ "This template must be recompiled with at least Jinja 2.11, or"256+ " it will fail in 3.0.",257+ DeprecationWarning,258+ stacklevel=2,259+ )260+ return AsyncLoopContext(iterable, undefined, recurse, depth0)261+262+263+patch_all()added:src/jinja2/bccache.py+353 added
1+# -*- coding: utf-8 -*-2+"""The optional bytecode cache system. This is useful if you have very3+complex template situations and the compilation of all those templates4+slows down your application too much.5+6+Situations where this is useful are often forking web applications that7+are initialized on the first request.8+"""9+import errno10+import fnmatch11+import os12+import stat13+import sys14+import tempfile15+from hashlib import sha116+from os import listdir17+from os import path18+19+from ._compat import BytesIO20+from ._compat import marshal_dump21+from ._compat import marshal_load22+from ._compat import pickle23+from ._compat import text_type24+from .utils import open_if_exists25+26+bc_version = 327+28+# magic version used to only change with new jinja versions. With 2.629+# we change this to also take Python version changes into account. The30+# reason for this is that Python tends to segfault if fed earlier bytecode31+# versions because someone thought it would be a good idea to reuse opcodes32+# or make Python incompatible with earlier versions.33+bc_magic = (34+ "j2".encode("ascii")35+ + pickle.dumps(bc_version, 2)36+ + pickle.dumps((sys.version_info[0] << 24) | sys.version_info[1])37+)38+39+40+class Bucket(object):41+ """Buckets are used to store the bytecode for one template. It's created42+ and initialized by the bytecode cache and passed to the loading functions.43+44+ The buckets get an internal checksum from the cache assigned and use this45+ to automatically reject outdated cache material. Individual bytecode46+ cache subclasses don't have to care about cache invalidation.47+ """48+49+ def __init__(self, environment, key, checksum):50+ self.environment = environment51+ self.key = key52+ self.checksum = checksum53+ self.reset()54+55+ def reset(self):56+ """Resets the bucket (unloads the bytecode)."""57+ self.code = None58+59+ def load_bytecode(self, f):60+ """Loads bytecode from a file or file like object."""61+ # make sure the magic header is correct62+ magic = f.read(len(bc_magic))63+ if magic != bc_magic:64+ self.reset()65+ return66+ # the source code of the file changed, we need to reload67+ checksum = pickle.load(f)68+ if self.checksum != checksum:69+ self.reset()70+ return71+ # if marshal_load fails then we need to reload72+ try:73+ self.code = marshal_load(f)74+ except (EOFError, ValueError, TypeError):75+ self.reset()76+ return77+78+ def write_bytecode(self, f):79+ """Dump the bytecode into the file or file like object passed."""80+ if self.code is None:81+ raise TypeError("can't write empty bucket")82+ f.write(bc_magic)83+ pickle.dump(self.checksum, f, 2)84+ marshal_dump(self.code, f)85+86+ def bytecode_from_string(self, string):87+ """Load bytecode from a string."""88+ self.load_bytecode(BytesIO(string))89+90+ def bytecode_to_string(self):91+ """Return the bytecode as string."""92+ out = BytesIO()93+ self.write_bytecode(out)94+ return out.getvalue()95+96+97+class BytecodeCache(object):98+ """To implement your own bytecode cache you have to subclass this class99+ and override :meth:`load_bytecode` and :meth:`dump_bytecode`. Both of100+ these methods are passed a :class:`~jinja2.bccache.Bucket`.101+102+ A very basic bytecode cache that saves the bytecode on the file system::103+104+ from os import path105+106+ class MyCache(BytecodeCache):107+108+ def __init__(self, directory):109+ self.directory = directory110+111+ def load_bytecode(self, bucket):112+ filename = path.join(self.directory, bucket.key)113+ if path.exists(filename):114+ with open(filename, 'rb') as f:115+ bucket.load_bytecode(f)116+117+ def dump_bytecode(self, bucket):118+ filename = path.join(self.directory, bucket.key)119+ with open(filename, 'wb') as f:120+ bucket.write_bytecode(f)121+122+ A more advanced version of a filesystem based bytecode cache is part of123+ Jinja.124+ """125+126+ def load_bytecode(self, bucket):127+ """Subclasses have to override this method to load bytecode into a128+ bucket. If they are not able to find code in the cache for the129+ bucket, it must not do anything.130+ """131+ raise NotImplementedError()132+133+ def dump_bytecode(self, bucket):134+ """Subclasses have to override this method to write the bytecode135+ from a bucket back to the cache. If it unable to do so it must not136+ fail silently but raise an exception.137+ """138+ raise NotImplementedError()139+140+ def clear(self):141+ """Clears the cache. This method is not used by Jinja but should be142+ implemented to allow applications to clear the bytecode cache used143+ by a particular environment.144+ """145+146+ def get_cache_key(self, name, filename=None):147+ """Returns the unique hash key for this template name."""148+ hash = sha1(name.encode("utf-8"))149+ if filename is not None:150+ filename = "|" + filename151+ if isinstance(filename, text_type):152+ filename = filename.encode("utf-8")153+ hash.update(filename)154+ return hash.hexdigest()155+156+ def get_source_checksum(self, source):157+ """Returns a checksum for the source."""158+ return sha1(source.encode("utf-8")).hexdigest()159+160+ def get_bucket(self, environment, name, filename, source):161+ """Return a cache bucket for the given template. All arguments are162+ mandatory but filename may be `None`.163+ """164+ key = self.get_cache_key(name, filename)165+ checksum = self.get_source_checksum(source)166+ bucket = Bucket(environment, key, checksum)167+ self.load_bytecode(bucket)168+ return bucket169+170+ def set_bucket(self, bucket):171+ """Put the bucket into the cache."""172+ self.dump_bytecode(bucket)173+174+175+class FileSystemBytecodeCache(BytecodeCache):176+ """A bytecode cache that stores bytecode on the filesystem. It accepts177+ two arguments: The directory where the cache items are stored and a178+ pattern string that is used to build the filename.179+180+ If no directory is specified a default cache directory is selected. On181+ Windows the user's temp directory is used, on UNIX systems a directory182+ is created for the user in the system temp directory.183+184+ The pattern can be used to have multiple separate caches operate on the185+ same directory. The default pattern is ``'__jinja2_%s.cache'``. ``%s``186+ is replaced with the cache key.187+188+ >>> bcc = FileSystemBytecodeCache('/tmp/jinja_cache', '%s.cache')189+190+ This bytecode cache supports clearing of the cache using the clear method.191+ """192+193+ def __init__(self, directory=None, pattern="__jinja2_%s.cache"):194+ if directory is None:195+ directory = self._get_default_cache_dir()196+ self.directory = directory197+ self.pattern = pattern198+199+ def _get_default_cache_dir(self):200+ def _unsafe_dir():201+ raise RuntimeError(202+ "Cannot determine safe temp directory. You "203+ "need to explicitly provide one."204+ )205+206+ tmpdir = tempfile.gettempdir()207+208+ # On windows the temporary directory is used specific unless209+ # explicitly forced otherwise. We can just use that.210+ if os.name == "nt":211+ return tmpdir212+ if not hasattr(os, "getuid"):213+ _unsafe_dir()214+215+ dirname = "_jinja2-cache-%d" % os.getuid()216+ actual_dir = os.path.join(tmpdir, dirname)217+218+ try:219+ os.mkdir(actual_dir, stat.S_IRWXU)220+ except OSError as e:221+ if e.errno != errno.EEXIST:222+ raise223+ try:224+ os.chmod(actual_dir, stat.S_IRWXU)225+ actual_dir_stat = os.lstat(actual_dir)226+ if (227+ actual_dir_stat.st_uid != os.getuid()228+ or not stat.S_ISDIR(actual_dir_stat.st_mode)229+ or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU230+ ):231+ _unsafe_dir()232+ except OSError as e:233+ if e.errno != errno.EEXIST:234+ raise235+236+ actual_dir_stat = os.lstat(actual_dir)237+ if (238+ actual_dir_stat.st_uid != os.getuid()239+ or not stat.S_ISDIR(actual_dir_stat.st_mode)240+ or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU241+ ):242+ _unsafe_dir()243+244+ return actual_dir245+246+ def _get_cache_filename(self, bucket):247+ return path.join(self.directory, self.pattern % bucket.key)248+249+ def load_bytecode(self, bucket):250+ f = open_if_exists(self._get_cache_filename(bucket), "rb")251+ if f is not None:252+ try:253+ bucket.load_bytecode(f)254+ finally:255+ f.close()256+257+ def dump_bytecode(self, bucket):258+ f = open(self._get_cache_filename(bucket), "wb")259+ try:260+ bucket.write_bytecode(f)261+ finally:262+ f.close()263+264+ def clear(self):265+ # imported lazily here because google app-engine doesn't support266+ # write access on the file system and the function does not exist267+ # normally.268+ from os import remove269+270+ files = fnmatch.filter(listdir(self.directory), self.pattern % "*")271+ for filename in files:272+ try:273+ remove(path.join(self.directory, filename))274+ except OSError:275+ pass276+277+278+class MemcachedBytecodeCache(BytecodeCache):279+ """This class implements a bytecode cache that uses a memcache cache for280+ storing the information. It does not enforce a specific memcache library281+ (tummy's memcache or cmemcache) but will accept any class that provides282+ the minimal interface required.283+284+ Libraries compatible with this class:285+286+ - `cachelib <https://github.com/pallets/cachelib>`_287+ - `python-memcached <https://pypi.org/project/python-memcached/>`_288+289+ (Unfortunately the django cache interface is not compatible because it290+ does not support storing binary data, only unicode. You can however pass291+ the underlying cache client to the bytecode cache which is available292+ as `django.core.cache.cache._client`.)293+294+ The minimal interface for the client passed to the constructor is this:295+296+ .. class:: MinimalClientInterface297+298+ .. method:: set(key, value[, timeout])299+300+ Stores the bytecode in the cache. `value` is a string and301+ `timeout` the timeout of the key. If timeout is not provided302+ a default timeout or no timeout should be assumed, if it's303+ provided it's an integer with the number of seconds the cache304+ item should exist.305+306+ .. method:: get(key)307+308+ Returns the value for the cache key. If the item does not309+ exist in the cache the return value must be `None`.310+311+ The other arguments to the constructor are the prefix for all keys that312+ is added before the actual cache key and the timeout for the bytecode in313+ the cache system. We recommend a high (or no) timeout.314+315+ This bytecode cache does not support clearing of used items in the cache.316+ The clear method is a no-operation function.317+318+ .. versionadded:: 2.7319+ Added support for ignoring memcache errors through the320+ `ignore_memcache_errors` parameter.321+ """322+323+ def __init__(324+ self,325+ client,326+ prefix="jinja2/bytecode/",327+ timeout=None,328+ ignore_memcache_errors=True,329+ ):330+ self.client = client331+ self.prefix = prefix332+ self.timeout = timeout333+ self.ignore_memcache_errors = ignore_memcache_errors334+335+ def load_bytecode(self, bucket):336+ try:337+ code = self.client.get(self.prefix + bucket.key)338+ except Exception:339+ if not self.ignore_memcache_errors:340+ raise341+ code = None342+ if code is not None:343+ bucket.bytecode_from_string(code)344+345+ def dump_bytecode(self, bucket):346+ args = (self.prefix + bucket.key, bucket.bytecode_to_string())347+ if self.timeout is not None:348+ args += (self.timeout,)349+ try:350+ self.client.set(*args)351+ except Exception:352+ if not self.ignore_memcache_errors:353+ raiseadded:src/jinja2/compiler.py+1842 added
1+# -*- coding: utf-8 -*-2+"""Compiles nodes from the parser into Python code."""3+from collections import namedtuple4+from functools import update_wrapper5+from itertools import chain6+from keyword import iskeyword as is_python_keyword7+8+from . import nodes9+from ._compat import imap10+from ._compat import iteritems11+from ._compat import izip12+from ._compat import NativeStringIO13+from ._compat import range_type14+from ._compat import string_types15+from ._compat import text_type16+from .exceptions import TemplateAssertionError17+from .idtracking import Symbols18+from .idtracking import VAR_LOAD_ALIAS19+from .idtracking import VAR_LOAD_PARAMETER20+from .idtracking import VAR_LOAD_RESOLVE21+from .idtracking import VAR_LOAD_UNDEFINED22+from .nodes import EvalContext23+from .optimizer import Optimizer24+from .utils import concat25+from .utils import escape26+from .utils import Markup27+from .visitor import NodeVisitor28+29+operators = {30+ "eq": "==",31+ "ne": "!=",32+ "gt": ">",33+ "gteq": ">=",34+ "lt": "<",35+ "lteq": "<=",36+ "in": "in",37+ "notin": "not in",38+}39+40+# what method to iterate over items do we want to use for dict iteration41+# in generated code? on 2.x let's go with iteritems, on 3.x with items42+if hasattr(dict, "iteritems"):43+ dict_item_iter = "iteritems"44+else:45+ dict_item_iter = "items"46+47+code_features = ["division"]48+49+# does this python version support generator stops? (PEP 0479)50+try:51+ exec("from __future__ import generator_stop")52+ code_features.append("generator_stop")53+except SyntaxError:54+ pass55+56+# does this python version support yield from?57+try:58+ exec("def f(): yield from x()")59+except SyntaxError:60+ supports_yield_from = False61+else:62+ supports_yield_from = True63+64+65+def optimizeconst(f):66+ def new_func(self, node, frame, **kwargs):67+ # Only optimize if the frame is not volatile68+ if self.optimized and not frame.eval_ctx.volatile:69+ new_node = self.optimizer.visit(node, frame.eval_ctx)70+ if new_node != node:71+ return self.visit(new_node, frame)72+ return f(self, node, frame, **kwargs)73+74+ return update_wrapper(new_func, f)75+76+77+def generate(78+ node, environment, name, filename, stream=None, defer_init=False, optimized=True79+):80+ """Generate the python source for a node tree."""81+ if not isinstance(node, nodes.Template):82+ raise TypeError("Can't compile non template nodes")83+ generator = environment.code_generator_class(84+ environment, name, filename, stream, defer_init, optimized85+ )86+ generator.visit(node)87+ if stream is None:88+ return generator.stream.getvalue()89+90+91+def has_safe_repr(value):92+ """Does the node have a safe representation?"""93+ if value is None or value is NotImplemented or value is Ellipsis:94+ return True95+ if type(value) in (bool, int, float, complex, range_type, Markup) + string_types:96+ return True97+ if type(value) in (tuple, list, set, frozenset):98+ for item in value:99+ if not has_safe_repr(item):100+ return False101+ return True102+ elif type(value) is dict:103+ for key, value in iteritems(value):104+ if not has_safe_repr(key):105+ return False106+ if not has_safe_repr(value):107+ return False108+ return True109+ return False110+111+112+def find_undeclared(nodes, names):113+ """Check if the names passed are accessed undeclared. The return value114+ is a set of all the undeclared names from the sequence of names found.115+ """116+ visitor = UndeclaredNameVisitor(names)117+ try:118+ for node in nodes:119+ visitor.visit(node)120+ except VisitorExit:121+ pass122+ return visitor.undeclared123+124+125+class MacroRef(object):126+ def __init__(self, node):127+ self.node = node128+ self.accesses_caller = False129+ self.accesses_kwargs = False130+ self.accesses_varargs = False131+132+133+class Frame(object):134+ """Holds compile time information for us."""135+136+ def __init__(self, eval_ctx, parent=None, level=None):137+ self.eval_ctx = eval_ctx138+ self.symbols = Symbols(parent and parent.symbols or None, level=level)139+140+ # a toplevel frame is the root + soft frames such as if conditions.141+ self.toplevel = False142+143+ # the root frame is basically just the outermost frame, so no if144+ # conditions. This information is used to optimize inheritance145+ # situations.146+ self.rootlevel = False147+148+ # in some dynamic inheritance situations the compiler needs to add149+ # write tests around output statements.150+ self.require_output_check = parent and parent.require_output_check151+152+ # inside some tags we are using a buffer rather than yield statements.153+ # this for example affects {% filter %} or {% macro %}. If a frame154+ # is buffered this variable points to the name of the list used as155+ # buffer.156+ self.buffer = None157+158+ # the name of the block we're in, otherwise None.159+ self.block = parent and parent.block or None160+161+ # the parent of this frame162+ self.parent = parent163+164+ if parent is not None:165+ self.buffer = parent.buffer166+167+ def copy(self):168+ """Create a copy of the current one."""169+ rv = object.__new__(self.__class__)170+ rv.__dict__.update(self.__dict__)171+ rv.symbols = self.symbols.copy()172+ return rv173+174+ def inner(self, isolated=False):175+ """Return an inner frame."""176+ if isolated:177+ return Frame(self.eval_ctx, level=self.symbols.level + 1)178+ return Frame(self.eval_ctx, self)179+180+ def soft(self):181+ """Return a soft frame. A soft frame may not be modified as182+ standalone thing as it shares the resources with the frame it183+ was created of, but it's not a rootlevel frame any longer.184+185+ This is only used to implement if-statements.186+ """187+ rv = self.copy()188+ rv.rootlevel = False189+ return rv190+191+ __copy__ = copy192+193+194+class VisitorExit(RuntimeError):195+ """Exception used by the `UndeclaredNameVisitor` to signal a stop."""196+197+198+class DependencyFinderVisitor(NodeVisitor):199+ """A visitor that collects filter and test calls."""200+201+ def __init__(self):202+ self.filters = set()203+ self.tests = set()204+205+ def visit_Filter(self, node):206+ self.generic_visit(node)207+ self.filters.add(node.name)208+209+ def visit_Test(self, node):210+ self.generic_visit(node)211+ self.tests.add(node.name)212+213+ def visit_Block(self, node):214+ """Stop visiting at blocks."""215+216+217+class UndeclaredNameVisitor(NodeVisitor):218+ """A visitor that checks if a name is accessed without being219+ declared. This is different from the frame visitor as it will220+ not stop at closure frames.221+ """222+223+ def __init__(self, names):224+ self.names = set(names)225+ self.undeclared = set()226+227+ def visit_Name(self, node):228+ if node.ctx == "load" and node.name in self.names:229+ self.undeclared.add(node.name)230+ if self.undeclared == self.names:231+ raise VisitorExit()232+ else:233+ self.names.discard(node.name)234+235+ def visit_Block(self, node):236+ """Stop visiting a blocks."""237+238+239+class CompilerExit(Exception):240+ """Raised if the compiler encountered a situation where it just241+ doesn't make sense to further process the code. Any block that242+ raises such an exception is not further processed.243+ """244+245+246+class CodeGenerator(NodeVisitor):247+ def __init__(248+ self, environment, name, filename, stream=None, defer_init=False, optimized=True249+ ):250+ if stream is None:251+ stream = NativeStringIO()252+ self.environment = environment253+ self.name = name254+ self.filename = filename255+ self.stream = stream256+ self.created_block_context = False257+ self.defer_init = defer_init258+ self.optimized = optimized259+ if optimized:260+ self.optimizer = Optimizer(environment)261+262+ # aliases for imports263+ self.import_aliases = {}264+265+ # a registry for all blocks. Because blocks are moved out266+ # into the global python scope they are registered here267+ self.blocks = {}268+269+ # the number of extends statements so far270+ self.extends_so_far = 0271+272+ # some templates have a rootlevel extends. In this case we273+ # can safely assume that we're a child template and do some274+ # more optimizations.275+ self.has_known_extends = False276+277+ # the current line number278+ self.code_lineno = 1279+280+ # registry of all filters and tests (global, not block local)281+ self.tests = {}282+ self.filters = {}283+284+ # the debug information285+ self.debug_info = []286+ self._write_debug_info = None287+288+ # the number of new lines before the next write()289+ self._new_lines = 0290+291+ # the line number of the last written statement292+ self._last_line = 0293+294+ # true if nothing was written so far.295+ self._first_write = True296+297+ # used by the `temporary_identifier` method to get new298+ # unique, temporary identifier299+ self._last_identifier = 0300+301+ # the current indentation302+ self._indentation = 0303+304+ # Tracks toplevel assignments305+ self._assign_stack = []306+307+ # Tracks parameter definition blocks308+ self._param_def_block = []309+310+ # Tracks the current context.311+ self._context_reference_stack = ["context"]312+313+ # -- Various compilation helpers314+315+ def fail(self, msg, lineno):316+ """Fail with a :exc:`TemplateAssertionError`."""317+ raise TemplateAssertionError(msg, lineno, self.name, self.filename)318+319+ def temporary_identifier(self):320+ """Get a new unique identifier."""321+ self._last_identifier += 1322+ return "t_%d" % self._last_identifier323+324+ def buffer(self, frame):325+ """Enable buffering for the frame from that point onwards."""326+ frame.buffer = self.temporary_identifier()327+ self.writeline("%s = []" % frame.buffer)328+329+ def return_buffer_contents(self, frame, force_unescaped=False):330+ """Return the buffer contents of the frame."""331+ if not force_unescaped:332+ if frame.eval_ctx.volatile:333+ self.writeline("if context.eval_ctx.autoescape:")334+ self.indent()335+ self.writeline("return Markup(concat(%s))" % frame.buffer)336+ self.outdent()337+ self.writeline("else:")338+ self.indent()339+ self.writeline("return concat(%s)" % frame.buffer)340+ self.outdent()341+ return342+ elif frame.eval_ctx.autoescape:343+ self.writeline("return Markup(concat(%s))" % frame.buffer)344+ return345+ self.writeline("return concat(%s)" % frame.buffer)346+347+ def indent(self):348+ """Indent by one."""349+ self._indentation += 1350+351+ def outdent(self, step=1):352+ """Outdent by step."""353+ self._indentation -= step354+355+ def start_write(self, frame, node=None):356+ """Yield or write into the frame buffer."""357+ if frame.buffer is None:358+ self.writeline("yield ", node)359+ else:360+ self.writeline("%s.append(" % frame.buffer, node)361+362+ def end_write(self, frame):363+ """End the writing process started by `start_write`."""364+ if frame.buffer is not None:365+ self.write(")")366+367+ def simple_write(self, s, frame, node=None):368+ """Simple shortcut for start_write + write + end_write."""369+ self.start_write(frame, node)370+ self.write(s)371+ self.end_write(frame)372+373+ def blockvisit(self, nodes, frame):374+ """Visit a list of nodes as block in a frame. If the current frame375+ is no buffer a dummy ``if 0: yield None`` is written automatically.376+ """377+ try:378+ self.writeline("pass")379+ for node in nodes:380+ self.visit(node, frame)381+ except CompilerExit:382+ pass383+384+ def write(self, x):385+ """Write a string into the output stream."""386+ if self._new_lines:387+ if not self._first_write:388+ self.stream.write("\n" * self._new_lines)389+ self.code_lineno += self._new_lines390+ if self._write_debug_info is not None:391+ self.debug_info.append((self._write_debug_info, self.code_lineno))392+ self._write_debug_info = None393+ self._first_write = False394+ self.stream.write(" " * self._indentation)395+ self._new_lines = 0396+ self.stream.write(x)397+398+ def writeline(self, x, node=None, extra=0):399+ """Combination of newline and write."""400+ self.newline(node, extra)401+ self.write(x)402+403+ def newline(self, node=None, extra=0):404+ """Add one or more newlines before the next write."""405+ self._new_lines = max(self._new_lines, 1 + extra)406+ if node is not None and node.lineno != self._last_line:407+ self._write_debug_info = node.lineno408+ self._last_line = node.lineno409+410+ def signature(self, node, frame, extra_kwargs=None):411+ """Writes a function call to the stream for the current node.412+ A leading comma is added automatically. The extra keyword413+ arguments may not include python keywords otherwise a syntax414+ error could occur. The extra keyword arguments should be given415+ as python dict.416+ """417+ # if any of the given keyword arguments is a python keyword418+ # we have to make sure that no invalid call is created.419+ kwarg_workaround = False420+ for kwarg in chain((x.key for x in node.kwargs), extra_kwargs or ()):421+ if is_python_keyword(kwarg):422+ kwarg_workaround = True423+ break424+425+ for arg in node.args:426+ self.write(", ")427+ self.visit(arg, frame)428+429+ if not kwarg_workaround:430+ for kwarg in node.kwargs:431+ self.write(", ")432+ self.visit(kwarg, frame)433+ if extra_kwargs is not None:434+ for key, value in iteritems(extra_kwargs):435+ self.write(", %s=%s" % (key, value))436+ if node.dyn_args:437+ self.write(", *")438+ self.visit(node.dyn_args, frame)439+440+ if kwarg_workaround:441+ if node.dyn_kwargs is not None:442+ self.write(", **dict({")443+ else:444+ self.write(", **{")445+ for kwarg in node.kwargs:446+ self.write("%r: " % kwarg.key)447+ self.visit(kwarg.value, frame)448+ self.write(", ")449+ if extra_kwargs is not None:450+ for key, value in iteritems(extra_kwargs):451+ self.write("%r: %s, " % (key, value))452+ if node.dyn_kwargs is not None:453+ self.write("}, **")454+ self.visit(node.dyn_kwargs, frame)455+ self.write(")")456+ else:457+ self.write("}")458+459+ elif node.dyn_kwargs is not None:460+ self.write(", **")461+ self.visit(node.dyn_kwargs, frame)462+463+ def pull_dependencies(self, nodes):464+ """Pull all the dependencies."""465+ visitor = DependencyFinderVisitor()466+ for node in nodes:467+ visitor.visit(node)468+ for dependency in "filters", "tests":469+ mapping = getattr(self, dependency)470+ for name in getattr(visitor, dependency):471+ if name not in mapping:472+ mapping[name] = self.temporary_identifier()473+ self.writeline(474+ "%s = environment.%s[%r]" % (mapping[name], dependency, name)475+ )476+477+ def enter_frame(self, frame):478+ undefs = []479+ for target, (action, param) in iteritems(frame.symbols.loads):480+ if action == VAR_LOAD_PARAMETER:481+ pass482+ elif action == VAR_LOAD_RESOLVE:483+ self.writeline("%s = %s(%r)" % (target, self.get_resolve_func(), param))484+ elif action == VAR_LOAD_ALIAS:485+ self.writeline("%s = %s" % (target, param))486+ elif action == VAR_LOAD_UNDEFINED:487+ undefs.append(target)488+ else:489+ raise NotImplementedError("unknown load instruction")490+ if undefs:491+ self.writeline("%s = missing" % " = ".join(undefs))492+493+ def leave_frame(self, frame, with_python_scope=False):494+ if not with_python_scope:495+ undefs = []496+ for target, _ in iteritems(frame.symbols.loads):497+ undefs.append(target)498+ if undefs:499+ self.writeline("%s = missing" % " = ".join(undefs))500+501+ def func(self, name):502+ if self.environment.is_async:503+ return "async def %s" % name504+ return "def %s" % name505+506+ def macro_body(self, node, frame):507+ """Dump the function def of a macro or call block."""508+ frame = frame.inner()509+ frame.symbols.analyze_node(node)510+ macro_ref = MacroRef(node)511+512+ explicit_caller = None513+ skip_special_params = set()514+ args = []515+ for idx, arg in enumerate(node.args):516+ if arg.name == "caller":517+ explicit_caller = idx518+ if arg.name in ("kwargs", "varargs"):519+ skip_special_params.add(arg.name)520+ args.append(frame.symbols.ref(arg.name))521+522+ undeclared = find_undeclared(node.body, ("caller", "kwargs", "varargs"))523+524+ if "caller" in undeclared:525+ # In older Jinja versions there was a bug that allowed caller526+ # to retain the special behavior even if it was mentioned in527+ # the argument list. However thankfully this was only really528+ # working if it was the last argument. So we are explicitly529+ # checking this now and error out if it is anywhere else in530+ # the argument list.531+ if explicit_caller is not None:532+ try:533+ node.defaults[explicit_caller - len(node.args)]534+ except IndexError:535+ self.fail(536+ "When defining macros or call blocks the "537+ 'special "caller" argument must be omitted '538+ "or be given a default.",539+ node.lineno,540+ )541+ else:542+ args.append(frame.symbols.declare_parameter("caller"))543+ macro_ref.accesses_caller = True544+ if "kwargs" in undeclared and "kwargs" not in skip_special_params:545+ args.append(frame.symbols.declare_parameter("kwargs"))546+ macro_ref.accesses_kwargs = True547+ if "varargs" in undeclared and "varargs" not in skip_special_params:548+ args.append(frame.symbols.declare_parameter("varargs"))549+ macro_ref.accesses_varargs = True550+551+ # macros are delayed, they never require output checks552+ frame.require_output_check = False553+ frame.symbols.analyze_node(node)554+ self.writeline("%s(%s):" % (self.func("macro"), ", ".join(args)), node)555+ self.indent()556+557+ self.buffer(frame)558+ self.enter_frame(frame)559+560+ self.push_parameter_definitions(frame)561+ for idx, arg in enumerate(node.args):562+ ref = frame.symbols.ref(arg.name)563+ self.writeline("if %s is missing:" % ref)564+ self.indent()565+ try:566+ default = node.defaults[idx - len(node.args)]567+ except IndexError:568+ self.writeline(569+ "%s = undefined(%r, name=%r)"570+ % (ref, "parameter %r was not provided" % arg.name, arg.name)571+ )572+ else:573+ self.writeline("%s = " % ref)574+ self.visit(default, frame)575+ self.mark_parameter_stored(ref)576+ self.outdent()577+ self.pop_parameter_definitions()578+579+ self.blockvisit(node.body, frame)580+ self.return_buffer_contents(frame, force_unescaped=True)581+ self.leave_frame(frame, with_python_scope=True)582+ self.outdent()583+584+ return frame, macro_ref585+586+ def macro_def(self, macro_ref, frame):587+ """Dump the macro definition for the def created by macro_body."""588+ arg_tuple = ", ".join(repr(x.name) for x in macro_ref.node.args)589+ name = getattr(macro_ref.node, "name", None)590+ if len(macro_ref.node.args) == 1:591+ arg_tuple += ","592+ self.write(593+ "Macro(environment, macro, %r, (%s), %r, %r, %r, "594+ "context.eval_ctx.autoescape)"595+ % (596+ name,597+ arg_tuple,598+ macro_ref.accesses_kwargs,599+ macro_ref.accesses_varargs,600+ macro_ref.accesses_caller,601+ )602+ )603+604+ def position(self, node):605+ """Return a human readable position for the node."""606+ rv = "line %d" % node.lineno607+ if self.name is not None:608+ rv += " in " + repr(self.name)609+ return rv610+611+ def dump_local_context(self, frame):612+ return "{%s}" % ", ".join(613+ "%r: %s" % (name, target)614+ for name, target in iteritems(frame.symbols.dump_stores())615+ )616+617+ def write_commons(self):618+ """Writes a common preamble that is used by root and block functions.619+ Primarily this sets up common local helpers and enforces a generator620+ through a dead branch.621+ """622+ self.writeline("resolve = context.resolve_or_missing")623+ self.writeline("undefined = environment.undefined")624+ # always use the standard Undefined class for the implicit else of625+ # conditional expressions626+ self.writeline("cond_expr_undefined = Undefined")627+ self.writeline("if 0: yield None")628+629+ def push_parameter_definitions(self, frame):630+ """Pushes all parameter targets from the given frame into a local631+ stack that permits tracking of yet to be assigned parameters. In632+ particular this enables the optimization from `visit_Name` to skip633+ undefined expressions for parameters in macros as macros can reference634+ otherwise unbound parameters.635+ """636+ self._param_def_block.append(frame.symbols.dump_param_targets())637+638+ def pop_parameter_definitions(self):639+ """Pops the current parameter definitions set."""640+ self._param_def_block.pop()641+642+ def mark_parameter_stored(self, target):643+ """Marks a parameter in the current parameter definitions as stored.644+ This will skip the enforced undefined checks.645+ """646+ if self._param_def_block:647+ self._param_def_block[-1].discard(target)648+649+ def push_context_reference(self, target):650+ self._context_reference_stack.append(target)651+652+ def pop_context_reference(self):653+ self._context_reference_stack.pop()654+655+ def get_context_ref(self):656+ return self._context_reference_stack[-1]657+658+ def get_resolve_func(self):659+ target = self._context_reference_stack[-1]660+ if target == "context":661+ return "resolve"662+ return "%s.resolve" % target663+664+ def derive_context(self, frame):665+ return "%s.derived(%s)" % (666+ self.get_context_ref(),667+ self.dump_local_context(frame),668+ )669+670+ def parameter_is_undeclared(self, target):671+ """Checks if a given target is an undeclared parameter."""672+ if not self._param_def_block:673+ return False674+ return target in self._param_def_block[-1]675+676+ def push_assign_tracking(self):677+ """Pushes a new layer for assignment tracking."""678+ self._assign_stack.append(set())679+680+ def pop_assign_tracking(self, frame):681+ """Pops the topmost level for assignment tracking and updates the682+ context variables if necessary.683+ """684+ vars = self._assign_stack.pop()685+ if not frame.toplevel or not vars:686+ return687+ public_names = [x for x in vars if x[:1] != "_"]688+ if len(vars) == 1:689+ name = next(iter(vars))690+ ref = frame.symbols.ref(name)691+ self.writeline("context.vars[%r] = %s" % (name, ref))692+ else:693+ self.writeline("context.vars.update({")694+ for idx, name in enumerate(vars):695+ if idx:696+ self.write(", ")697+ ref = frame.symbols.ref(name)698+ self.write("%r: %s" % (name, ref))699+ self.write("})")700+ if public_names:701+ if len(public_names) == 1:702+ self.writeline("context.exported_vars.add(%r)" % public_names[0])703+ else:704+ self.writeline(705+ "context.exported_vars.update((%s))"706+ % ", ".join(imap(repr, public_names))707+ )708+709+ # -- Statement Visitors710+711+ def visit_Template(self, node, frame=None):712+ assert frame is None, "no root frame allowed"713+ eval_ctx = EvalContext(self.environment, self.name)714+715+ from .runtime import __all__ as exported716+717+ self.writeline("from __future__ import %s" % ", ".join(code_features))718+ self.writeline("from jinja2.runtime import " + ", ".join(exported))719+720+ if self.environment.is_async:721+ self.writeline(722+ "from jinja2.asyncsupport import auto_await, "723+ "auto_aiter, AsyncLoopContext"724+ )725+726+ # if we want a deferred initialization we cannot move the727+ # environment into a local name728+ envenv = not self.defer_init and ", environment=environment" or ""729+730+ # do we have an extends tag at all? If not, we can save some731+ # overhead by just not processing any inheritance code.732+ have_extends = node.find(nodes.Extends) is not None733+734+ # find all blocks735+ for block in node.find_all(nodes.Block):736+ if block.name in self.blocks:737+ self.fail("block %r defined twice" % block.name, block.lineno)738+ self.blocks[block.name] = block739+740+ # find all imports and import them741+ for import_ in node.find_all(nodes.ImportedName):742+ if import_.importname not in self.import_aliases:743+ imp = import_.importname744+ self.import_aliases[imp] = alias = self.temporary_identifier()745+ if "." in imp:746+ module, obj = imp.rsplit(".", 1)747+ self.writeline("from %s import %s as %s" % (module, obj, alias))748+ else:749+ self.writeline("import %s as %s" % (imp, alias))750+751+ # add the load name752+ self.writeline("name = %r" % self.name)753+754+ # generate the root render function.755+ self.writeline(756+ "%s(context, missing=missing%s):" % (self.func("root"), envenv), extra=1757+ )758+ self.indent()759+ self.write_commons()760+761+ # process the root762+ frame = Frame(eval_ctx)763+ if "self" in find_undeclared(node.body, ("self",)):764+ ref = frame.symbols.declare_parameter("self")765+ self.writeline("%s = TemplateReference(context)" % ref)766+ frame.symbols.analyze_node(node)767+ frame.toplevel = frame.rootlevel = True768+ frame.require_output_check = have_extends and not self.has_known_extends769+ if have_extends:770+ self.writeline("parent_template = None")771+ self.enter_frame(frame)772+ self.pull_dependencies(node.body)773+ self.blockvisit(node.body, frame)774+ self.leave_frame(frame, with_python_scope=True)775+ self.outdent()776+777+ # make sure that the parent root is called.778+ if have_extends:779+ if not self.has_known_extends:780+ self.indent()781+ self.writeline("if parent_template is not None:")782+ self.indent()783+ if supports_yield_from and not self.environment.is_async:784+ self.writeline("yield from parent_template.root_render_func(context)")785+ else:786+ self.writeline(787+ "%sfor event in parent_template."788+ "root_render_func(context):"789+ % (self.environment.is_async and "async " or "")790+ )791+ self.indent()792+ self.writeline("yield event")793+ self.outdent()794+ self.outdent(1 + (not self.has_known_extends))795+796+ # at this point we now have the blocks collected and can visit them too.797+ for name, block in iteritems(self.blocks):798+ self.writeline(799+ "%s(context, missing=missing%s):"800+ % (self.func("block_" + name), envenv),801+ block,802+ 1,803+ )804+ self.indent()805+ self.write_commons()806+ # It's important that we do not make this frame a child of the807+ # toplevel template. This would cause a variety of808+ # interesting issues with identifier tracking.809+ block_frame = Frame(eval_ctx)810+ undeclared = find_undeclared(block.body, ("self", "super"))811+ if "self" in undeclared:812+ ref = block_frame.symbols.declare_parameter("self")813+ self.writeline("%s = TemplateReference(context)" % ref)814+ if "super" in undeclared:815+ ref = block_frame.symbols.declare_parameter("super")816+ self.writeline("%s = context.super(%r, block_%s)" % (ref, name, name))817+ block_frame.symbols.analyze_node(block)818+ block_frame.block = name819+ self.enter_frame(block_frame)820+ self.pull_dependencies(block.body)821+ self.blockvisit(block.body, block_frame)822+ self.leave_frame(block_frame, with_python_scope=True)823+ self.outdent()824+825+ self.writeline(826+ "blocks = {%s}" % ", ".join("%r: block_%s" % (x, x) for x in self.blocks),827+ extra=1,828+ )829+830+ # add a function that returns the debug info831+ self.writeline(832+ "debug_info = %r" % "&".join("%s=%s" % x for x in self.debug_info)833+ )834+835+ def visit_Block(self, node, frame):836+ """Call a block and register it for the template."""837+ level = 0838+ if frame.toplevel:839+ # if we know that we are a child template, there is no need to840+ # check if we are one841+ if self.has_known_extends:842+ return843+ if self.extends_so_far > 0:844+ self.writeline("if parent_template is None:")845+ self.indent()846+ level += 1847+848+ if node.scoped:849+ context = self.derive_context(frame)850+ else:851+ context = self.get_context_ref()852+853+ if (854+ supports_yield_from855+ and not self.environment.is_async856+ and frame.buffer is None857+ ):858+ self.writeline(859+ "yield from context.blocks[%r][0](%s)" % (node.name, context), node860+ )861+ else:862+ loop = self.environment.is_async and "async for" or "for"863+ self.writeline(864+ "%s event in context.blocks[%r][0](%s):" % (loop, node.name, context),865+ node,866+ )867+ self.indent()868+ self.simple_write("event", frame)869+ self.outdent()870+871+ self.outdent(level)872+873+ def visit_Extends(self, node, frame):874+ """Calls the extender."""875+ if not frame.toplevel:876+ self.fail("cannot use extend from a non top-level scope", node.lineno)877+878+ # if the number of extends statements in general is zero so879+ # far, we don't have to add a check if something extended880+ # the template before this one.881+ if self.extends_so_far > 0:882+883+ # if we have a known extends we just add a template runtime884+ # error into the generated code. We could catch that at compile885+ # time too, but i welcome it not to confuse users by throwing the886+ # same error at different times just "because we can".887+ if not self.has_known_extends:888+ self.writeline("if parent_template is not None:")889+ self.indent()890+ self.writeline("raise TemplateRuntimeError(%r)" % "extended multiple times")891+892+ # if we have a known extends already we don't need that code here893+ # as we know that the template execution will end here.894+ if self.has_known_extends:895+ raise CompilerExit()896+ else:897+ self.outdent()898+899+ self.writeline("parent_template = environment.get_template(", node)900+ self.visit(node.template, frame)901+ self.write(", %r)" % self.name)902+ self.writeline(903+ "for name, parent_block in parent_template.blocks.%s():" % dict_item_iter904+ )905+ self.indent()906+ self.writeline("context.blocks.setdefault(name, []).append(parent_block)")907+ self.outdent()908+909+ # if this extends statement was in the root level we can take910+ # advantage of that information and simplify the generated code911+ # in the top level from this point onwards912+ if frame.rootlevel:913+ self.has_known_extends = True914+915+ # and now we have one more916+ self.extends_so_far += 1917+918+ def visit_Include(self, node, frame):919+ """Handles includes."""920+ if node.ignore_missing:921+ self.writeline("try:")922+ self.indent()923+924+ func_name = "get_or_select_template"925+ if isinstance(node.template, nodes.Const):926+ if isinstance(node.template.value, string_types):927+ func_name = "get_template"928+ elif isinstance(node.template.value, (tuple, list)):929+ func_name = "select_template"930+ elif isinstance(node.template, (nodes.Tuple, nodes.List)):931+ func_name = "select_template"932+933+ self.writeline("template = environment.%s(" % func_name, node)934+ self.visit(node.template, frame)935+ self.write(", %r)" % self.name)936+ if node.ignore_missing:937+ self.outdent()938+ self.writeline("except TemplateNotFound:")939+ self.indent()940+ self.writeline("pass")941+ self.outdent()942+ self.writeline("else:")943+ self.indent()944+945+ skip_event_yield = False946+ if node.with_context:947+ loop = self.environment.is_async and "async for" or "for"948+ self.writeline(949+ "%s event in template.root_render_func("950+ "template.new_context(context.get_all(), True, "951+ "%s)):" % (loop, self.dump_local_context(frame))952+ )953+ elif self.environment.is_async:954+ self.writeline(955+ "for event in (await "956+ "template._get_default_module_async())"957+ "._body_stream:"958+ )959+ else:960+ if supports_yield_from:961+ self.writeline("yield from template._get_default_module()._body_stream")962+ skip_event_yield = True963+ else:964+ self.writeline(965+ "for event in template._get_default_module()._body_stream:"966+ )967+968+ if not skip_event_yield:969+ self.indent()970+ self.simple_write("event", frame)971+ self.outdent()972+973+ if node.ignore_missing:974+ self.outdent()975+976+ def visit_Import(self, node, frame):977+ """Visit regular imports."""978+ self.writeline("%s = " % frame.symbols.ref(node.target), node)979+ if frame.toplevel:980+ self.write("context.vars[%r] = " % node.target)981+ if self.environment.is_async:982+ self.write("await ")983+ self.write("environment.get_template(")984+ self.visit(node.template, frame)985+ self.write(", %r)." % self.name)986+ if node.with_context:987+ self.write(988+ "make_module%s(context.get_all(), True, %s)"989+ % (990+ self.environment.is_async and "_async" or "",991+ self.dump_local_context(frame),992+ )993+ )994+ elif self.environment.is_async:995+ self.write("_get_default_module_async()")996+ else:997+ self.write("_get_default_module()")998+ if frame.toplevel and not node.target.startswith("_"):999+ self.writeline("context.exported_vars.discard(%r)" % node.target)1000+1001+ def visit_FromImport(self, node, frame):1002+ """Visit named imports."""1003+ self.newline(node)1004+ self.write(1005+ "included_template = %senvironment.get_template("1006+ % (self.environment.is_async and "await " or "")1007+ )1008+ self.visit(node.template, frame)1009+ self.write(", %r)." % self.name)1010+ if node.with_context:1011+ self.write(1012+ "make_module%s(context.get_all(), True, %s)"1013+ % (1014+ self.environment.is_async and "_async" or "",1015+ self.dump_local_context(frame),1016+ )1017+ )1018+ elif self.environment.is_async:1019+ self.write("_get_default_module_async()")1020+ else:1021+ self.write("_get_default_module()")1022+1023+ var_names = []1024+ discarded_names = []1025+ for name in node.names:1026+ if isinstance(name, tuple):1027+ name, alias = name1028+ else:1029+ alias = name1030+ self.writeline(1031+ "%s = getattr(included_template, "1032+ "%r, missing)" % (frame.symbols.ref(alias), name)1033+ )1034+ self.writeline("if %s is missing:" % frame.symbols.ref(alias))1035+ self.indent()1036+ self.writeline(1037+ "%s = undefined(%r %% "1038+ "included_template.__name__, "1039+ "name=%r)"1040+ % (1041+ frame.symbols.ref(alias),1042+ "the template %%r (imported on %s) does "1043+ "not export the requested name %s"1044+ % (self.position(node), repr(name)),1045+ name,1046+ )1047+ )1048+ self.outdent()1049+ if frame.toplevel:1050+ var_names.append(alias)1051+ if not alias.startswith("_"):1052+ discarded_names.append(alias)1053+1054+ if var_names:1055+ if len(var_names) == 1:1056+ name = var_names[0]1057+ self.writeline(1058+ "context.vars[%r] = %s" % (name, frame.symbols.ref(name))1059+ )1060+ else:1061+ self.writeline(1062+ "context.vars.update({%s})"1063+ % ", ".join(1064+ "%r: %s" % (name, frame.symbols.ref(name)) for name in var_names1065+ )1066+ )1067+ if discarded_names:1068+ if len(discarded_names) == 1:1069+ self.writeline("context.exported_vars.discard(%r)" % discarded_names[0])1070+ else:1071+ self.writeline(1072+ "context.exported_vars.difference_"1073+ "update((%s))" % ", ".join(imap(repr, discarded_names))1074+ )1075+1076+ def visit_For(self, node, frame):1077+ loop_frame = frame.inner()1078+ test_frame = frame.inner()1079+ else_frame = frame.inner()1080+1081+ # try to figure out if we have an extended loop. An extended loop1082+ # is necessary if the loop is in recursive mode if the special loop1083+ # variable is accessed in the body.1084+ extended_loop = node.recursive or "loop" in find_undeclared(1085+ node.iter_child_nodes(only=("body",)), ("loop",)1086+ )1087+1088+ loop_ref = None1089+ if extended_loop:1090+ loop_ref = loop_frame.symbols.declare_parameter("loop")1091+1092+ loop_frame.symbols.analyze_node(node, for_branch="body")1093+ if node.else_:1094+ else_frame.symbols.analyze_node(node, for_branch="else")1095+1096+ if node.test:1097+ loop_filter_func = self.temporary_identifier()1098+ test_frame.symbols.analyze_node(node, for_branch="test")1099+ self.writeline("%s(fiter):" % self.func(loop_filter_func), node.test)1100+ self.indent()1101+ self.enter_frame(test_frame)1102+ self.writeline(self.environment.is_async and "async for " or "for ")1103+ self.visit(node.target, loop_frame)1104+ self.write(" in ")1105+ self.write(self.environment.is_async and "auto_aiter(fiter)" or "fiter")1106+ self.write(":")1107+ self.indent()1108+ self.writeline("if ", node.test)1109+ self.visit(node.test, test_frame)1110+ self.write(":")1111+ self.indent()1112+ self.writeline("yield ")1113+ self.visit(node.target, loop_frame)1114+ self.outdent(3)1115+ self.leave_frame(test_frame, with_python_scope=True)1116+1117+ # if we don't have an recursive loop we have to find the shadowed1118+ # variables at that point. Because loops can be nested but the loop1119+ # variable is a special one we have to enforce aliasing for it.1120+ if node.recursive:1121+ self.writeline(1122+ "%s(reciter, loop_render_func, depth=0):" % self.func("loop"), node1123+ )1124+ self.indent()1125+ self.buffer(loop_frame)1126+1127+ # Use the same buffer for the else frame1128+ else_frame.buffer = loop_frame.buffer1129+1130+ # make sure the loop variable is a special one and raise a template1131+ # assertion error if a loop tries to write to loop1132+ if extended_loop:1133+ self.writeline("%s = missing" % loop_ref)1134+1135+ for name in node.find_all(nodes.Name):1136+ if name.ctx == "store" and name.name == "loop":1137+ self.fail(1138+ "Can't assign to special loop variable in for-loop target",1139+ name.lineno,1140+ )1141+1142+ if node.else_:1143+ iteration_indicator = self.temporary_identifier()1144+ self.writeline("%s = 1" % iteration_indicator)1145+1146+ self.writeline(self.environment.is_async and "async for " or "for ", node)1147+ self.visit(node.target, loop_frame)1148+ if extended_loop:1149+ if self.environment.is_async:1150+ self.write(", %s in AsyncLoopContext(" % loop_ref)1151+ else:1152+ self.write(", %s in LoopContext(" % loop_ref)1153+ else:1154+ self.write(" in ")1155+1156+ if node.test:1157+ self.write("%s(" % loop_filter_func)1158+ if node.recursive:1159+ self.write("reciter")1160+ else:1161+ if self.environment.is_async and not extended_loop:1162+ self.write("auto_aiter(")1163+ self.visit(node.iter, frame)1164+ if self.environment.is_async and not extended_loop:1165+ self.write(")")1166+ if node.test:1167+ self.write(")")1168+1169+ if node.recursive:1170+ self.write(", undefined, loop_render_func, depth):")1171+ else:1172+ self.write(extended_loop and ", undefined):" or ":")1173+1174+ self.indent()1175+ self.enter_frame(loop_frame)1176+1177+ self.blockvisit(node.body, loop_frame)1178+ if node.else_:1179+ self.writeline("%s = 0" % iteration_indicator)1180+ self.outdent()1181+ self.leave_frame(1182+ loop_frame, with_python_scope=node.recursive and not node.else_1183+ )1184+1185+ if node.else_:1186+ self.writeline("if %s:" % iteration_indicator)1187+ self.indent()1188+ self.enter_frame(else_frame)1189+ self.blockvisit(node.else_, else_frame)1190+ self.leave_frame(else_frame)1191+ self.outdent()1192+1193+ # if the node was recursive we have to return the buffer contents1194+ # and start the iteration code1195+ if node.recursive:1196+ self.return_buffer_contents(loop_frame)1197+ self.outdent()1198+ self.start_write(frame, node)1199+ if self.environment.is_async:1200+ self.write("await ")1201+ self.write("loop(")1202+ if self.environment.is_async:1203+ self.write("auto_aiter(")1204+ self.visit(node.iter, frame)1205+ if self.environment.is_async:1206+ self.write(")")1207+ self.write(", loop)")1208+ self.end_write(frame)1209+1210+ def visit_If(self, node, frame):1211+ if_frame = frame.soft()1212+ self.writeline("if ", node)1213+ self.visit(node.test, if_frame)1214+ self.write(":")1215+ self.indent()1216+ self.blockvisit(node.body, if_frame)1217+ self.outdent()1218+ for elif_ in node.elif_:1219+ self.writeline("elif ", elif_)1220+ self.visit(elif_.test, if_frame)1221+ self.write(":")1222+ self.indent()1223+ self.blockvisit(elif_.body, if_frame)1224+ self.outdent()1225+ if node.else_:1226+ self.writeline("else:")1227+ self.indent()1228+ self.blockvisit(node.else_, if_frame)1229+ self.outdent()1230+1231+ def visit_Macro(self, node, frame):1232+ macro_frame, macro_ref = self.macro_body(node, frame)1233+ self.newline()1234+ if frame.toplevel:1235+ if not node.name.startswith("_"):1236+ self.write("context.exported_vars.add(%r)" % node.name)1237+ self.writeline("context.vars[%r] = " % node.name)1238+ self.write("%s = " % frame.symbols.ref(node.name))1239+ self.macro_def(macro_ref, macro_frame)1240+1241+ def visit_CallBlock(self, node, frame):1242+ call_frame, macro_ref = self.macro_body(node, frame)1243+ self.writeline("caller = ")1244+ self.macro_def(macro_ref, call_frame)1245+ self.start_write(frame, node)1246+ self.visit_Call(node.call, frame, forward_caller=True)1247+ self.end_write(frame)1248+1249+ def visit_FilterBlock(self, node, frame):1250+ filter_frame = frame.inner()1251+ filter_frame.symbols.analyze_node(node)1252+ self.enter_frame(filter_frame)1253+ self.buffer(filter_frame)1254+ self.blockvisit(node.body, filter_frame)1255+ self.start_write(frame, node)1256+ self.visit_Filter(node.filter, filter_frame)1257+ self.end_write(frame)1258+ self.leave_frame(filter_frame)1259+1260+ def visit_With(self, node, frame):1261+ with_frame = frame.inner()1262+ with_frame.symbols.analyze_node(node)1263+ self.enter_frame(with_frame)1264+ for target, expr in izip(node.targets, node.values):1265+ self.newline()1266+ self.visit(target, with_frame)1267+ self.write(" = ")1268+ self.visit(expr, frame)1269+ self.blockvisit(node.body, with_frame)1270+ self.leave_frame(with_frame)1271+1272+ def visit_ExprStmt(self, node, frame):1273+ self.newline(node)1274+ self.visit(node.node, frame)1275+1276+ _FinalizeInfo = namedtuple("_FinalizeInfo", ("const", "src"))1277+ #: The default finalize function if the environment isn't configured1278+ #: with one. Or if the environment has one, this is called on that1279+ #: function's output for constants.1280+ _default_finalize = text_type1281+ _finalize = None1282+1283+ def _make_finalize(self):1284+ """Build the finalize function to be used on constants and at1285+ runtime. Cached so it's only created once for all output nodes.1286+1287+ Returns a ``namedtuple`` with the following attributes:1288+1289+ ``const``1290+ A function to finalize constant data at compile time.1291+1292+ ``src``1293+ Source code to output around nodes to be evaluated at1294+ runtime.1295+ """1296+ if self._finalize is not None:1297+ return self._finalize1298+1299+ finalize = default = self._default_finalize1300+ src = None1301+1302+ if self.environment.finalize:1303+ src = "environment.finalize("1304+ env_finalize = self.environment.finalize1305+1306+ def finalize(value):1307+ return default(env_finalize(value))1308+1309+ if getattr(env_finalize, "contextfunction", False):1310+ src += "context, "1311+ finalize = None # noqa: F8111312+ elif getattr(env_finalize, "evalcontextfunction", False):1313+ src += "context.eval_ctx, "1314+ finalize = None1315+ elif getattr(env_finalize, "environmentfunction", False):1316+ src += "environment, "1317+1318+ def finalize(value):1319+ return default(env_finalize(self.environment, value))1320+1321+ self._finalize = self._FinalizeInfo(finalize, src)1322+ return self._finalize1323+1324+ def _output_const_repr(self, group):1325+ """Given a group of constant values converted from ``Output``1326+ child nodes, produce a string to write to the template module1327+ source.1328+ """1329+ return repr(concat(group))1330+1331+ def _output_child_to_const(self, node, frame, finalize):1332+ """Try to optimize a child of an ``Output`` node by trying to1333+ convert it to constant, finalized data at compile time.1334+1335+ If :exc:`Impossible` is raised, the node is not constant and1336+ will be evaluated at runtime. Any other exception will also be1337+ evaluated at runtime for easier debugging.1338+ """1339+ const = node.as_const(frame.eval_ctx)1340+1341+ if frame.eval_ctx.autoescape:1342+ const = escape(const)1343+1344+ # Template data doesn't go through finalize.1345+ if isinstance(node, nodes.TemplateData):1346+ return text_type(const)1347+1348+ return finalize.const(const)1349+1350+ def _output_child_pre(self, node, frame, finalize):1351+ """Output extra source code before visiting a child of an1352+ ``Output`` node.1353+ """1354+ if frame.eval_ctx.volatile:1355+ self.write("(escape if context.eval_ctx.autoescape else to_string)(")1356+ elif frame.eval_ctx.autoescape:1357+ self.write("escape(")1358+ else:1359+ self.write("to_string(")1360+1361+ if finalize.src is not None:1362+ self.write(finalize.src)1363+1364+ def _output_child_post(self, node, frame, finalize):1365+ """Output extra source code after visiting a child of an1366+ ``Output`` node.1367+ """1368+ self.write(")")1369+1370+ if finalize.src is not None:1371+ self.write(")")1372+1373+ def visit_Output(self, node, frame):1374+ # If an extends is active, don't render outside a block.1375+ if frame.require_output_check:1376+ # A top-level extends is known to exist at compile time.1377+ if self.has_known_extends:1378+ return1379+1380+ self.writeline("if parent_template is None:")1381+ self.indent()1382+1383+ finalize = self._make_finalize()1384+ body = []1385+1386+ # Evaluate constants at compile time if possible. Each item in1387+ # body will be either a list of static data or a node to be1388+ # evaluated at runtime.1389+ for child in node.nodes:1390+ try:1391+ if not (1392+ # If the finalize function requires runtime context,1393+ # constants can't be evaluated at compile time.1394+ finalize.const1395+ # Unless it's basic template data that won't be1396+ # finalized anyway.1397+ or isinstance(child, nodes.TemplateData)1398+ ):1399+ raise nodes.Impossible()1400+1401+ const = self._output_child_to_const(child, frame, finalize)1402+ except (nodes.Impossible, Exception):1403+ # The node was not constant and needs to be evaluated at1404+ # runtime. Or another error was raised, which is easier1405+ # to debug at runtime.1406+ body.append(child)1407+ continue1408+1409+ if body and isinstance(body[-1], list):1410+ body[-1].append(const)1411+ else:1412+ body.append([const])1413+1414+ if frame.buffer is not None:1415+ if len(body) == 1:1416+ self.writeline("%s.append(" % frame.buffer)1417+ else:1418+ self.writeline("%s.extend((" % frame.buffer)1419+1420+ self.indent()1421+1422+ for item in body:1423+ if isinstance(item, list):1424+ # A group of constant data to join and output.1425+ val = self._output_const_repr(item)1426+1427+ if frame.buffer is None:1428+ self.writeline("yield " + val)1429+ else:1430+ self.writeline(val + ",")1431+ else:1432+ if frame.buffer is None:1433+ self.writeline("yield ", item)1434+ else:1435+ self.newline(item)1436+1437+ # A node to be evaluated at runtime.1438+ self._output_child_pre(item, frame, finalize)1439+ self.visit(item, frame)1440+ self._output_child_post(item, frame, finalize)1441+1442+ if frame.buffer is not None:1443+ self.write(",")1444+1445+ if frame.buffer is not None:1446+ self.outdent()1447+ self.writeline(")" if len(body) == 1 else "))")1448+1449+ if frame.require_output_check:1450+ self.outdent()1451+1452+ def visit_Assign(self, node, frame):1453+ self.push_assign_tracking()1454+ self.newline(node)1455+ self.visit(node.target, frame)1456+ self.write(" = ")1457+ self.visit(node.node, frame)1458+ self.pop_assign_tracking(frame)1459+1460+ def visit_AssignBlock(self, node, frame):1461+ self.push_assign_tracking()1462+ block_frame = frame.inner()1463+ # This is a special case. Since a set block always captures we1464+ # will disable output checks. This way one can use set blocks1465+ # toplevel even in extended templates.1466+ block_frame.require_output_check = False1467+ block_frame.symbols.analyze_node(node)1468+ self.enter_frame(block_frame)1469+ self.buffer(block_frame)1470+ self.blockvisit(node.body, block_frame)1471+ self.newline(node)1472+ self.visit(node.target, frame)1473+ self.write(" = (Markup if context.eval_ctx.autoescape else identity)(")1474+ if node.filter is not None:1475+ self.visit_Filter(node.filter, block_frame)1476+ else:1477+ self.write("concat(%s)" % block_frame.buffer)1478+ self.write(")")1479+ self.pop_assign_tracking(frame)1480+ self.leave_frame(block_frame)1481+1482+ # -- Expression Visitors1483+1484+ def visit_Name(self, node, frame):1485+ if node.ctx == "store" and frame.toplevel:1486+ if self._assign_stack:1487+ self._assign_stack[-1].add(node.name)1488+ ref = frame.symbols.ref(node.name)1489+1490+ # If we are looking up a variable we might have to deal with the1491+ # case where it's undefined. We can skip that case if the load1492+ # instruction indicates a parameter which are always defined.1493+ if node.ctx == "load":1494+ load = frame.symbols.find_load(ref)1495+ if not (1496+ load is not None1497+ and load[0] == VAR_LOAD_PARAMETER1498+ and not self.parameter_is_undeclared(ref)1499+ ):1500+ self.write(1501+ "(undefined(name=%r) if %s is missing else %s)"1502+ % (node.name, ref, ref)1503+ )1504+ return1505+1506+ self.write(ref)1507+1508+ def visit_NSRef(self, node, frame):1509+ # NSRefs can only be used to store values; since they use the normal1510+ # `foo.bar` notation they will be parsed as a normal attribute access1511+ # when used anywhere but in a `set` context1512+ ref = frame.symbols.ref(node.name)1513+ self.writeline("if not isinstance(%s, Namespace):" % ref)1514+ self.indent()1515+ self.writeline(1516+ "raise TemplateRuntimeError(%r)"1517+ % "cannot assign attribute on non-namespace object"1518+ )1519+ self.outdent()1520+ self.writeline("%s[%r]" % (ref, node.attr))1521+1522+ def visit_Const(self, node, frame):1523+ val = node.as_const(frame.eval_ctx)1524+ if isinstance(val, float):1525+ self.write(str(val))1526+ else:1527+ self.write(repr(val))1528+1529+ def visit_TemplateData(self, node, frame):1530+ try:1531+ self.write(repr(node.as_const(frame.eval_ctx)))1532+ except nodes.Impossible:1533+ self.write(1534+ "(Markup if context.eval_ctx.autoescape else identity)(%r)" % node.data1535+ )1536+1537+ def visit_Tuple(self, node, frame):1538+ self.write("(")1539+ idx = -11540+ for idx, item in enumerate(node.items):1541+ if idx:1542+ self.write(", ")1543+ self.visit(item, frame)1544+ self.write(idx == 0 and ",)" or ")")1545+1546+ def visit_List(self, node, frame):1547+ self.write("[")1548+ for idx, item in enumerate(node.items):1549+ if idx:1550+ self.write(", ")1551+ self.visit(item, frame)1552+ self.write("]")1553+1554+ def visit_Dict(self, node, frame):1555+ self.write("{")1556+ for idx, item in enumerate(node.items):1557+ if idx:1558+ self.write(", ")1559+ self.visit(item.key, frame)1560+ self.write(": ")1561+ self.visit(item.value, frame)1562+ self.write("}")1563+1564+ def binop(operator, interceptable=True): # noqa: B9021565+ @optimizeconst1566+ def visitor(self, node, frame):1567+ if (1568+ self.environment.sandboxed1569+ and operator in self.environment.intercepted_binops1570+ ):1571+ self.write("environment.call_binop(context, %r, " % operator)1572+ self.visit(node.left, frame)1573+ self.write(", ")1574+ self.visit(node.right, frame)1575+ else:1576+ self.write("(")1577+ self.visit(node.left, frame)1578+ self.write(" %s " % operator)1579+ self.visit(node.right, frame)1580+ self.write(")")1581+1582+ return visitor1583+1584+ def uaop(operator, interceptable=True): # noqa: B9021585+ @optimizeconst1586+ def visitor(self, node, frame):1587+ if (1588+ self.environment.sandboxed1589+ and operator in self.environment.intercepted_unops1590+ ):1591+ self.write("environment.call_unop(context, %r, " % operator)1592+ self.visit(node.node, frame)1593+ else:1594+ self.write("(" + operator)1595+ self.visit(node.node, frame)1596+ self.write(")")1597+1598+ return visitor1599+1600+ visit_Add = binop("+")1601+ visit_Sub = binop("-")1602+ visit_Mul = binop("*")1603+ visit_Div = binop("/")1604+ visit_FloorDiv = binop("//")1605+ visit_Pow = binop("**")1606+ visit_Mod = binop("%")1607+ visit_And = binop("and", interceptable=False)1608+ visit_Or = binop("or", interceptable=False)1609+ visit_Pos = uaop("+")1610+ visit_Neg = uaop("-")1611+ visit_Not = uaop("not ", interceptable=False)1612+ del binop, uaop1613+1614+ @optimizeconst1615+ def visit_Concat(self, node, frame):1616+ if frame.eval_ctx.volatile:1617+ func_name = "(context.eval_ctx.volatile and markup_join or unicode_join)"1618+ elif frame.eval_ctx.autoescape:1619+ func_name = "markup_join"1620+ else:1621+ func_name = "unicode_join"1622+ self.write("%s((" % func_name)1623+ for arg in node.nodes:1624+ self.visit(arg, frame)1625+ self.write(", ")1626+ self.write("))")1627+1628+ @optimizeconst1629+ def visit_Compare(self, node, frame):1630+ self.write("(")1631+ self.visit(node.expr, frame)1632+ for op in node.ops:1633+ self.visit(op, frame)1634+ self.write(")")1635+1636+ def visit_Operand(self, node, frame):1637+ self.write(" %s " % operators[node.op])1638+ self.visit(node.expr, frame)1639+1640+ @optimizeconst1641+ def visit_Getattr(self, node, frame):1642+ if self.environment.is_async:1643+ self.write("await auto_await(")1644+1645+ self.write("environment.getattr(")1646+ self.visit(node.node, frame)1647+ self.write(", %r)" % node.attr)1648+1649+ if self.environment.is_async:1650+ self.write(")")1651+1652+ @optimizeconst1653+ def visit_Getitem(self, node, frame):1654+ # slices bypass the environment getitem method.1655+ if isinstance(node.arg, nodes.Slice):1656+ self.visit(node.node, frame)1657+ self.write("[")1658+ self.visit(node.arg, frame)1659+ self.write("]")1660+ else:1661+ if self.environment.is_async:1662+ self.write("await auto_await(")1663+1664+ self.write("environment.getitem(")1665+ self.visit(node.node, frame)1666+ self.write(", ")1667+ self.visit(node.arg, frame)1668+ self.write(")")1669+1670+ if self.environment.is_async:1671+ self.write(")")1672+1673+ def visit_Slice(self, node, frame):1674+ if node.start is not None:1675+ self.visit(node.start, frame)1676+ self.write(":")1677+ if node.stop is not None:1678+ self.visit(node.stop, frame)1679+ if node.step is not None:1680+ self.write(":")1681+ self.visit(node.step, frame)1682+1683+ @optimizeconst1684+ def visit_Filter(self, node, frame):1685+ if self.environment.is_async:1686+ self.write("await auto_await(")1687+ self.write(self.filters[node.name] + "(")1688+ func = self.environment.filters.get(node.name)1689+ if func is None:1690+ self.fail("no filter named %r" % node.name, node.lineno)1691+ if getattr(func, "contextfilter", False):1692+ self.write("context, ")1693+ elif getattr(func, "evalcontextfilter", False):1694+ self.write("context.eval_ctx, ")1695+ elif getattr(func, "environmentfilter", False):1696+ self.write("environment, ")1697+1698+ # if the filter node is None we are inside a filter block1699+ # and want to write to the current buffer1700+ if node.node is not None:1701+ self.visit(node.node, frame)1702+ elif frame.eval_ctx.volatile:1703+ self.write(1704+ "(context.eval_ctx.autoescape and"1705+ " Markup(concat(%s)) or concat(%s))" % (frame.buffer, frame.buffer)1706+ )1707+ elif frame.eval_ctx.autoescape:1708+ self.write("Markup(concat(%s))" % frame.buffer)1709+ else:1710+ self.write("concat(%s)" % frame.buffer)1711+ self.signature(node, frame)1712+ self.write(")")1713+ if self.environment.is_async:1714+ self.write(")")1715+1716+ @optimizeconst1717+ def visit_Test(self, node, frame):1718+ self.write(self.tests[node.name] + "(")1719+ if node.name not in self.environment.tests:1720+ self.fail("no test named %r" % node.name, node.lineno)1721+ self.visit(node.node, frame)1722+ self.signature(node, frame)1723+ self.write(")")1724+1725+ @optimizeconst1726+ def visit_CondExpr(self, node, frame):1727+ def write_expr2():1728+ if node.expr2 is not None:1729+ return self.visit(node.expr2, frame)1730+ self.write(1731+ "cond_expr_undefined(%r)"1732+ % (1733+ "the inline if-"1734+ "expression on %s evaluated to false and "1735+ "no else section was defined." % self.position(node)1736+ )1737+ )1738+1739+ self.write("(")1740+ self.visit(node.expr1, frame)1741+ self.write(" if ")1742+ self.visit(node.test, frame)1743+ self.write(" else ")1744+ write_expr2()1745+ self.write(")")1746+1747+ @optimizeconst1748+ def visit_Call(self, node, frame, forward_caller=False):1749+ if self.environment.is_async:1750+ self.write("await auto_await(")1751+ if self.environment.sandboxed:1752+ self.write("environment.call(context, ")1753+ else:1754+ self.write("context.call(")1755+ self.visit(node.node, frame)1756+ extra_kwargs = forward_caller and {"caller": "caller"} or None1757+ self.signature(node, frame, extra_kwargs)1758+ self.write(")")1759+ if self.environment.is_async:1760+ self.write(")")1761+1762+ def visit_Keyword(self, node, frame):1763+ self.write(node.key + "=")1764+ self.visit(node.value, frame)1765+1766+ # -- Unused nodes for extensions1767+1768+ def visit_MarkSafe(self, node, frame):1769+ self.write("Markup(")1770+ self.visit(node.expr, frame)1771+ self.write(")")1772+1773+ def visit_MarkSafeIfAutoescape(self, node, frame):1774+ self.write("(context.eval_ctx.autoescape and Markup or identity)(")1775+ self.visit(node.expr, frame)1776+ self.write(")")1777+1778+ def visit_EnvironmentAttribute(self, node, frame):1779+ self.write("environment." + node.name)1780+1781+ def visit_ExtensionAttribute(self, node, frame):1782+ self.write("environment.extensions[%r].%s" % (node.identifier, node.name))1783+1784+ def visit_ImportedName(self, node, frame):1785+ self.write(self.import_aliases[node.importname])1786+1787+ def visit_InternalName(self, node, frame):1788+ self.write(node.name)1789+1790+ def visit_ContextReference(self, node, frame):1791+ self.write("context")1792+1793+ def visit_DerivedContextReference(self, node, frame):1794+ self.write(self.derive_context(frame))1795+1796+ def visit_Continue(self, node, frame):1797+ self.writeline("continue", node)1798+1799+ def visit_Break(self, node, frame):1800+ self.writeline("break", node)1801+1802+ def visit_Scope(self, node, frame):1803+ scope_frame = frame.inner()1804+ scope_frame.symbols.analyze_node(node)1805+ self.enter_frame(scope_frame)1806+ self.blockvisit(node.body, scope_frame)1807+ self.leave_frame(scope_frame)1808+1809+ def visit_OverlayScope(self, node, frame):1810+ ctx = self.temporary_identifier()1811+ self.writeline("%s = %s" % (ctx, self.derive_context(frame)))1812+ self.writeline("%s.vars = " % ctx)1813+ self.visit(node.context, frame)1814+ self.push_context_reference(ctx)1815+1816+ scope_frame = frame.inner(isolated=True)1817+ scope_frame.symbols.analyze_node(node)1818+ self.enter_frame(scope_frame)1819+ self.blockvisit(node.body, scope_frame)1820+ self.leave_frame(scope_frame)1821+ self.pop_context_reference()1822+1823+ def visit_EvalContextModifier(self, node, frame):1824+ for keyword in node.options:1825+ self.writeline("context.eval_ctx.%s = " % keyword.key)1826+ self.visit(keyword.value, frame)1827+ try:1828+ val = keyword.value.as_const(frame.eval_ctx)1829+ except nodes.Impossible:1830+ frame.eval_ctx.volatile = True1831+ else:1832+ setattr(frame.eval_ctx, keyword.key, val)1833+1834+ def visit_ScopedEvalContextModifier(self, node, frame):1835+ old_ctx_name = self.temporary_identifier()1836+ saved_ctx = frame.eval_ctx.save()1837+ self.writeline("%s = context.eval_ctx.save()" % old_ctx_name)1838+ self.visit_EvalContextModifier(node, frame)1839+ for child in node.body:1840+ self.visit(child, frame)1841+ frame.eval_ctx.revert(saved_ctx)1842+ self.writeline("context.eval_ctx.revert(%s)" % old_ctx_name)added:src/jinja2/constants.py+21 added
1+# -*- coding: utf-8 -*-2+#: list of lorem ipsum words used by the lipsum() helper function3+LOREM_IPSUM_WORDS = u"""\4+a ac accumsan ad adipiscing aenean aliquam aliquet amet ante aptent arcu at5+auctor augue bibendum blandit class commodo condimentum congue consectetuer6+consequat conubia convallis cras cubilia cum curabitur curae cursus dapibus7+diam dictum dictumst dignissim dis dolor donec dui duis egestas eget eleifend8+elementum elit enim erat eros est et etiam eu euismod facilisi facilisis fames9+faucibus felis fermentum feugiat fringilla fusce gravida habitant habitasse hac10+hendrerit hymenaeos iaculis id imperdiet in inceptos integer interdum ipsum11+justo lacinia lacus laoreet lectus leo libero ligula litora lobortis lorem12+luctus maecenas magna magnis malesuada massa mattis mauris metus mi molestie13+mollis montes morbi mus nam nascetur natoque nec neque netus nibh nisi nisl non14+nonummy nostra nulla nullam nunc odio orci ornare parturient pede pellentesque15+penatibus per pharetra phasellus placerat platea porta porttitor posuere16+potenti praesent pretium primis proin pulvinar purus quam quis quisque rhoncus17+ridiculus risus rutrum sagittis sapien scelerisque sed sem semper senectus sit18+sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor19+tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices20+ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus21+viverra volutpat vulputate"""added:src/jinja2/debug.py+271 added
1+import sys2+from types import CodeType3+4+from . import TemplateSyntaxError5+from ._compat import PYPY6+from .utils import internal_code7+from .utils import missing8+9+10+def rewrite_traceback_stack(source=None):11+ """Rewrite the current exception to replace any tracebacks from12+ within compiled template code with tracebacks that look like they13+ came from the template source.14+15+ This must be called within an ``except`` block.16+17+ :param exc_info: A :meth:`sys.exc_info` tuple. If not provided,18+ the current ``exc_info`` is used.19+ :param source: For ``TemplateSyntaxError``, the original source if20+ known.21+ :return: A :meth:`sys.exc_info` tuple that can be re-raised.22+ """23+ exc_type, exc_value, tb = sys.exc_info()24+25+ if isinstance(exc_value, TemplateSyntaxError) and not exc_value.translated:26+ exc_value.translated = True27+ exc_value.source = source28+29+ try:30+ # Remove the old traceback on Python 3, otherwise the frames31+ # from the compiler still show up.32+ exc_value.with_traceback(None)33+ except AttributeError:34+ pass35+36+ # Outside of runtime, so the frame isn't executing template37+ # code, but it still needs to point at the template.38+ tb = fake_traceback(39+ exc_value, None, exc_value.filename or "<unknown>", exc_value.lineno40+ )41+ else:42+ # Skip the frame for the render function.43+ tb = tb.tb_next44+45+ stack = []46+47+ # Build the stack of traceback object, replacing any in template48+ # code with the source file and line information.49+ while tb is not None:50+ # Skip frames decorated with @internalcode. These are internal51+ # calls that aren't useful in template debugging output.52+ if tb.tb_frame.f_code in internal_code:53+ tb = tb.tb_next54+ continue55+56+ template = tb.tb_frame.f_globals.get("__jinja_template__")57+58+ if template is not None:59+ lineno = template.get_corresponding_lineno(tb.tb_lineno)60+ fake_tb = fake_traceback(exc_value, tb, template.filename, lineno)61+ stack.append(fake_tb)62+ else:63+ stack.append(tb)64+65+ tb = tb.tb_next66+67+ tb_next = None68+69+ # Assign tb_next in reverse to avoid circular references.70+ for tb in reversed(stack):71+ tb_next = tb_set_next(tb, tb_next)72+73+ return exc_type, exc_value, tb_next74+75+76+def fake_traceback(exc_value, tb, filename, lineno):77+ """Produce a new traceback object that looks like it came from the78+ template source instead of the compiled code. The filename, line79+ number, and location name will point to the template, and the local80+ variables will be the current template context.81+82+ :param exc_value: The original exception to be re-raised to create83+ the new traceback.84+ :param tb: The original traceback to get the local variables and85+ code info from.86+ :param filename: The template filename.87+ :param lineno: The line number in the template source.88+ """89+ if tb is not None:90+ # Replace the real locals with the context that would be91+ # available at that point in the template.92+ locals = get_template_locals(tb.tb_frame.f_locals)93+ locals.pop("__jinja_exception__", None)94+ else:95+ locals = {}96+97+ globals = {98+ "__name__": filename,99+ "__file__": filename,100+ "__jinja_exception__": exc_value,101+ }102+ # Raise an exception at the correct line number.103+ code = compile("\n" * (lineno - 1) + "raise __jinja_exception__", filename, "exec")104+105+ # Build a new code object that points to the template file and106+ # replaces the location with a block name.107+ try:108+ location = "template"109+110+ if tb is not None:111+ function = tb.tb_frame.f_code.co_name112+113+ if function == "root":114+ location = "top-level template code"115+ elif function.startswith("block_"):116+ location = 'block "%s"' % function[6:]117+118+ # Collect arguments for the new code object. CodeType only119+ # accepts positional arguments, and arguments were inserted in120+ # new Python versions.121+ code_args = []122+123+ for attr in (124+ "argcount",125+ "posonlyargcount", # Python 3.8126+ "kwonlyargcount", # Python 3127+ "nlocals",128+ "stacksize",129+ "flags",130+ "code", # codestring131+ "consts", # constants132+ "names",133+ "varnames",134+ ("filename", filename),135+ ("name", location),136+ "firstlineno",137+ "lnotab",138+ "freevars",139+ "cellvars",140+ ):141+ if isinstance(attr, tuple):142+ # Replace with given value.143+ code_args.append(attr[1])144+ continue145+146+ try:147+ # Copy original value if it exists.148+ code_args.append(getattr(code, "co_" + attr))149+ except AttributeError:150+ # Some arguments were added later.151+ continue152+153+ code = CodeType(*code_args)154+ except Exception:155+ # Some environments such as Google App Engine don't support156+ # modifying code objects.157+ pass158+159+ # Execute the new code, which is guaranteed to raise, and return160+ # the new traceback without this frame.161+ try:162+ exec(code, globals, locals)163+ except BaseException:164+ return sys.exc_info()[2].tb_next165+166+167+def get_template_locals(real_locals):168+ """Based on the runtime locals, get the context that would be169+ available at that point in the template.170+ """171+ # Start with the current template context.172+ ctx = real_locals.get("context")173+174+ if ctx:175+ data = ctx.get_all().copy()176+ else:177+ data = {}178+179+ # Might be in a derived context that only sets local variables180+ # rather than pushing a context. Local variables follow the scheme181+ # l_depth_name. Find the highest-depth local that has a value for182+ # each name.183+ local_overrides = {}184+185+ for name, value in real_locals.items():186+ if not name.startswith("l_") or value is missing:187+ # Not a template variable, or no longer relevant.188+ continue189+190+ try:191+ _, depth, name = name.split("_", 2)192+ depth = int(depth)193+ except ValueError:194+ continue195+196+ cur_depth = local_overrides.get(name, (-1,))[0]197+198+ if cur_depth < depth:199+ local_overrides[name] = (depth, value)200+201+ # Modify the context with any derived context.202+ for name, (_, value) in local_overrides.items():203+ if value is missing:204+ data.pop(name, None)205+ else:206+ data[name] = value207+208+ return data209+210+211+if sys.version_info >= (3, 7):212+ # tb_next is directly assignable as of Python 3.7213+ def tb_set_next(tb, tb_next):214+ tb.tb_next = tb_next215+ return tb216+217+218+elif PYPY:219+ # PyPy might have special support, and won't work with ctypes.220+ try:221+ import tputil222+ except ImportError:223+ # Without tproxy support, use the original traceback.224+ def tb_set_next(tb, tb_next):225+ return tb226+227+ else:228+ # With tproxy support, create a proxy around the traceback that229+ # returns the new tb_next.230+ def tb_set_next(tb, tb_next):231+ def controller(op):232+ if op.opname == "__getattribute__" and op.args[0] == "tb_next":233+ return tb_next234+235+ return op.delegate()236+237+ return tputil.make_proxy(controller, obj=tb)238+239+240+else:241+ # Use ctypes to assign tb_next at the C level since it's read-only242+ # from Python.243+ import ctypes244+245+ class _CTraceback(ctypes.Structure):246+ _fields_ = [247+ # Extra PyObject slots when compiled with Py_TRACE_REFS.248+ (249+ "PyObject_HEAD",250+ ctypes.c_byte * (32 if hasattr(sys, "getobjects") else 16),251+ ),252+ # Only care about tb_next as an object, not a traceback.253+ ("tb_next", ctypes.py_object),254+ ]255+256+ def tb_set_next(tb, tb_next):257+ c_tb = _CTraceback.from_address(id(tb))258+259+ # Clear out the old tb_next.260+ if tb.tb_next is not None:261+ c_tb_next = ctypes.py_object(tb.tb_next)262+ c_tb.tb_next = ctypes.py_object()263+ ctypes.pythonapi.Py_DecRef(c_tb_next)264+265+ # Assign the new tb_next.266+ if tb_next is not None:267+ c_tb_next = ctypes.py_object(tb_next)268+ ctypes.pythonapi.Py_IncRef(c_tb_next)269+ c_tb.tb_next = c_tb_next270+271+ return tbadded:src/jinja2/defaults.py+47 added
1+# -*- coding: utf-8 -*-2+from ._compat import range_type3+from .filters import FILTERS as DEFAULT_FILTERS # noqa: F4014+from .tests import TESTS as DEFAULT_TESTS # noqa: F4015+from .utils import Cycler6+from .utils import generate_lorem_ipsum7+from .utils import Joiner8+from .utils import Namespace9+10+# defaults for the parser / lexer11+BLOCK_START_STRING = "{%"12+BLOCK_END_STRING = "%}"13+VARIABLE_START_STRING = "{{"14+VARIABLE_END_STRING = "}}"15+COMMENT_START_STRING = "{#"16+COMMENT_END_STRING = "#}"17+LINE_STATEMENT_PREFIX = None18+LINE_COMMENT_PREFIX = None19+TRIM_BLOCKS = False20+LSTRIP_BLOCKS = False21+NEWLINE_SEQUENCE = "\n"22+KEEP_TRAILING_NEWLINE = False23+24+# default filters, tests and namespace25+26+DEFAULT_NAMESPACE = {27+ "range": range_type,28+ "dict": dict,29+ "lipsum": generate_lorem_ipsum,30+ "cycler": Cycler,31+ "joiner": Joiner,32+ "namespace": Namespace,33+}34+35+# default policies36+DEFAULT_POLICIES = {37+ "compiler.ascii_str": True,38+ "urlize.rel": "noopener",39+ "urlize.target": None,40+ "truncate.leeway": 5,41+ "json.dumps_function": None,42+ "json.dumps_kwargs": {"sort_keys": True},43+ "ext.i18n.trimmed": False,44+}45+46+# export all constants47+__all__ = tuple(x for x in locals().keys() if x.isupper())added:src/jinja2/environment.py+1361 added
1+# -*- coding: utf-8 -*-2+"""Classes for managing templates and their runtime and compile time3+options.4+"""5+import os6+import sys7+import weakref8+from functools import partial9+from functools import reduce10+11+from . import nodes12+from ._compat import encode_filename13+from ._compat import implements_iterator14+from ._compat import implements_to_string15+from ._compat import iteritems16+from ._compat import PY217+from ._compat import PYPY18+from ._compat import reraise19+from ._compat import string_types20+from ._compat import text_type21+from .compiler import CodeGenerator22+from .compiler import generate23+from .defaults import BLOCK_END_STRING24+from .defaults import BLOCK_START_STRING25+from .defaults import COMMENT_END_STRING26+from .defaults import COMMENT_START_STRING27+from .defaults import DEFAULT_FILTERS28+from .defaults import DEFAULT_NAMESPACE29+from .defaults import DEFAULT_POLICIES30+from .defaults import DEFAULT_TESTS31+from .defaults import KEEP_TRAILING_NEWLINE32+from .defaults import LINE_COMMENT_PREFIX33+from .defaults import LINE_STATEMENT_PREFIX34+from .defaults import LSTRIP_BLOCKS35+from .defaults import NEWLINE_SEQUENCE36+from .defaults import TRIM_BLOCKS37+from .defaults import VARIABLE_END_STRING38+from .defaults import VARIABLE_START_STRING39+from .exceptions import TemplateNotFound40+from .exceptions import TemplateRuntimeError41+from .exceptions import TemplatesNotFound42+from .exceptions import TemplateSyntaxError43+from .exceptions import UndefinedError44+from .lexer import get_lexer45+from .lexer import TokenStream46+from .nodes import EvalContext47+from .parser import Parser48+from .runtime import Context49+from .runtime import new_context50+from .runtime import Undefined51+from .utils import concat52+from .utils import consume53+from .utils import have_async_gen54+from .utils import import_string55+from .utils import internalcode56+from .utils import LRUCache57+from .utils import Markup58+from .utils import missing59+60+# for direct template usage we have up to ten living environments61+_spontaneous_environments = LRUCache(10)62+63+64+def get_spontaneous_environment(cls, *args):65+ """Return a new spontaneous environment. A spontaneous environment66+ is used for templates created directly rather than through an67+ existing environment.68+69+ :param cls: Environment class to create.70+ :param args: Positional arguments passed to environment.71+ """72+ key = (cls, args)73+74+ try:75+ return _spontaneous_environments[key]76+ except KeyError:77+ _spontaneous_environments[key] = env = cls(*args)78+ env.shared = True79+ return env80+81+82+def create_cache(size):83+ """Return the cache class for the given size."""84+ if size == 0:85+ return None86+ if size < 0:87+ return {}88+ return LRUCache(size)89+90+91+def copy_cache(cache):92+ """Create an empty copy of the given cache."""93+ if cache is None:94+ return None95+ elif type(cache) is dict:96+ return {}97+ return LRUCache(cache.capacity)98+99+100+def load_extensions(environment, extensions):101+ """Load the extensions from the list and bind it to the environment.102+ Returns a dict of instantiated environments.103+ """104+ result = {}105+ for extension in extensions:106+ if isinstance(extension, string_types):107+ extension = import_string(extension)108+ result[extension.identifier] = extension(environment)109+ return result110+111+112+def fail_for_missing_callable(string, name):113+ msg = string % name114+ if isinstance(name, Undefined):115+ try:116+ name._fail_with_undefined_error()117+ except Exception as e:118+ msg = "%s (%s; did you forget to quote the callable name?)" % (msg, e)119+ raise TemplateRuntimeError(msg)120+121+122+def _environment_sanity_check(environment):123+ """Perform a sanity check on the environment."""124+ assert issubclass(125+ environment.undefined, Undefined126+ ), "undefined must be a subclass of undefined because filters depend on it."127+ assert (128+ environment.block_start_string129+ != environment.variable_start_string130+ != environment.comment_start_string131+ ), "block, variable and comment start strings must be different"132+ assert environment.newline_sequence in (133+ "\r",134+ "\r\n",135+ "\n",136+ ), "newline_sequence set to unknown line ending string."137+ return environment138+139+140+class Environment(object):141+ r"""The core component of Jinja is the `Environment`. It contains142+ important shared variables like configuration, filters, tests,143+ globals and others. Instances of this class may be modified if144+ they are not shared and if no template was loaded so far.145+ Modifications on environments after the first template was loaded146+ will lead to surprising effects and undefined behavior.147+148+ Here are the possible initialization parameters:149+150+ `block_start_string`151+ The string marking the beginning of a block. Defaults to ``'{%'``.152+153+ `block_end_string`154+ The string marking the end of a block. Defaults to ``'%}'``.155+156+ `variable_start_string`157+ The string marking the beginning of a print statement.158+ Defaults to ``'{{'``.159+160+ `variable_end_string`161+ The string marking the end of a print statement. Defaults to162+ ``'}}'``.163+164+ `comment_start_string`165+ The string marking the beginning of a comment. Defaults to ``'{#'``.166+167+ `comment_end_string`168+ The string marking the end of a comment. Defaults to ``'#}'``.169+170+ `line_statement_prefix`171+ If given and a string, this will be used as prefix for line based172+ statements. See also :ref:`line-statements`.173+174+ `line_comment_prefix`175+ If given and a string, this will be used as prefix for line based176+ comments. See also :ref:`line-statements`.177+178+ .. versionadded:: 2.2179+180+ `trim_blocks`181+ If this is set to ``True`` the first newline after a block is182+ removed (block, not variable tag!). Defaults to `False`.183+184+ `lstrip_blocks`185+ If this is set to ``True`` leading spaces and tabs are stripped186+ from the start of a line to a block. Defaults to `False`.187+188+ `newline_sequence`189+ The sequence that starts a newline. Must be one of ``'\r'``,190+ ``'\n'`` or ``'\r\n'``. The default is ``'\n'`` which is a191+ useful default for Linux and OS X systems as well as web192+ applications.193+194+ `keep_trailing_newline`195+ Preserve the trailing newline when rendering templates.196+ The default is ``False``, which causes a single newline,197+ if present, to be stripped from the end of the template.198+199+ .. versionadded:: 2.7200+201+ `extensions`202+ List of Jinja extensions to use. This can either be import paths203+ as strings or extension classes. For more information have a204+ look at :ref:`the extensions documentation <jinja-extensions>`.205+206+ `optimized`207+ should the optimizer be enabled? Default is ``True``.208+209+ `undefined`210+ :class:`Undefined` or a subclass of it that is used to represent211+ undefined values in the template.212+213+ `finalize`214+ A callable that can be used to process the result of a variable215+ expression before it is output. For example one can convert216+ ``None`` implicitly into an empty string here.217+218+ `autoescape`219+ If set to ``True`` the XML/HTML autoescaping feature is enabled by220+ default. For more details about autoescaping see221+ :class:`~jinja2.utils.Markup`. As of Jinja 2.4 this can also222+ be a callable that is passed the template name and has to223+ return ``True`` or ``False`` depending on autoescape should be224+ enabled by default.225+226+ .. versionchanged:: 2.4227+ `autoescape` can now be a function228+229+ `loader`230+ The template loader for this environment.231+232+ `cache_size`233+ The size of the cache. Per default this is ``400`` which means234+ that if more than 400 templates are loaded the loader will clean235+ out the least recently used template. If the cache size is set to236+ ``0`` templates are recompiled all the time, if the cache size is237+ ``-1`` the cache will not be cleaned.238+239+ .. versionchanged:: 2.8240+ The cache size was increased to 400 from a low 50.241+242+ `auto_reload`243+ Some loaders load templates from locations where the template244+ sources may change (ie: file system or database). If245+ ``auto_reload`` is set to ``True`` (default) every time a template is246+ requested the loader checks if the source changed and if yes, it247+ will reload the template. For higher performance it's possible to248+ disable that.249+250+ `bytecode_cache`251+ If set to a bytecode cache object, this object will provide a252+ cache for the internal Jinja bytecode so that templates don't253+ have to be parsed if they were not changed.254+255+ See :ref:`bytecode-cache` for more information.256+257+ `enable_async`258+ If set to true this enables async template execution which allows259+ you to take advantage of newer Python features. This requires260+ Python 3.6 or later.261+ """262+263+ #: if this environment is sandboxed. Modifying this variable won't make264+ #: the environment sandboxed though. For a real sandboxed environment265+ #: have a look at jinja2.sandbox. This flag alone controls the code266+ #: generation by the compiler.267+ sandboxed = False268+269+ #: True if the environment is just an overlay270+ overlayed = False271+272+ #: the environment this environment is linked to if it is an overlay273+ linked_to = None274+275+ #: shared environments have this set to `True`. A shared environment276+ #: must not be modified277+ shared = False278+279+ #: the class that is used for code generation. See280+ #: :class:`~jinja2.compiler.CodeGenerator` for more information.281+ code_generator_class = CodeGenerator282+283+ #: the context class thatis used for templates. See284+ #: :class:`~jinja2.runtime.Context` for more information.285+ context_class = Context286+287+ def __init__(288+ self,289+ block_start_string=BLOCK_START_STRING,290+ block_end_string=BLOCK_END_STRING,291+ variable_start_string=VARIABLE_START_STRING,292+ variable_end_string=VARIABLE_END_STRING,293+ comment_start_string=COMMENT_START_STRING,294+ comment_end_string=COMMENT_END_STRING,295+ line_statement_prefix=LINE_STATEMENT_PREFIX,296+ line_comment_prefix=LINE_COMMENT_PREFIX,297+ trim_blocks=TRIM_BLOCKS,298+ lstrip_blocks=LSTRIP_BLOCKS,299+ newline_sequence=NEWLINE_SEQUENCE,300+ keep_trailing_newline=KEEP_TRAILING_NEWLINE,301+ extensions=(),302+ optimized=True,303+ undefined=Undefined,304+ finalize=None,305+ autoescape=False,306+ loader=None,307+ cache_size=400,308+ auto_reload=True,309+ bytecode_cache=None,310+ enable_async=False,311+ ):312+ # !!Important notice!!313+ # The constructor accepts quite a few arguments that should be314+ # passed by keyword rather than position. However it's important to315+ # not change the order of arguments because it's used at least316+ # internally in those cases:317+ # - spontaneous environments (i18n extension and Template)318+ # - unittests319+ # If parameter changes are required only add parameters at the end320+ # and don't change the arguments (or the defaults!) of the arguments321+ # existing already.322+323+ # lexer / parser information324+ self.block_start_string = block_start_string325+ self.block_end_string = block_end_string326+ self.variable_start_string = variable_start_string327+ self.variable_end_string = variable_end_string328+ self.comment_start_string = comment_start_string329+ self.comment_end_string = comment_end_string330+ self.line_statement_prefix = line_statement_prefix331+ self.line_comment_prefix = line_comment_prefix332+ self.trim_blocks = trim_blocks333+ self.lstrip_blocks = lstrip_blocks334+ self.newline_sequence = newline_sequence335+ self.keep_trailing_newline = keep_trailing_newline336+337+ # runtime information338+ self.undefined = undefined339+ self.optimized = optimized340+ self.finalize = finalize341+ self.autoescape = autoescape342+343+ # defaults344+ self.filters = DEFAULT_FILTERS.copy()345+ self.tests = DEFAULT_TESTS.copy()346+ self.globals = DEFAULT_NAMESPACE.copy()347+348+ # set the loader provided349+ self.loader = loader350+ self.cache = create_cache(cache_size)351+ self.bytecode_cache = bytecode_cache352+ self.auto_reload = auto_reload353+354+ # configurable policies355+ self.policies = DEFAULT_POLICIES.copy()356+357+ # load extensions358+ self.extensions = load_extensions(self, extensions)359+360+ self.enable_async = enable_async361+ self.is_async = self.enable_async and have_async_gen362+ if self.is_async:363+ # runs patch_all() to enable async support364+ from . import asyncsupport # noqa: F401365+366+ _environment_sanity_check(self)367+368+ def add_extension(self, extension):369+ """Adds an extension after the environment was created.370+371+ .. versionadded:: 2.5372+ """373+ self.extensions.update(load_extensions(self, [extension]))374+375+ def extend(self, **attributes):376+ """Add the items to the instance of the environment if they do not exist377+ yet. This is used by :ref:`extensions <writing-extensions>` to register378+ callbacks and configuration values without breaking inheritance.379+ """380+ for key, value in iteritems(attributes):381+ if not hasattr(self, key):382+ setattr(self, key, value)383+384+ def overlay(385+ self,386+ block_start_string=missing,387+ block_end_string=missing,388+ variable_start_string=missing,389+ variable_end_string=missing,390+ comment_start_string=missing,391+ comment_end_string=missing,392+ line_statement_prefix=missing,393+ line_comment_prefix=missing,394+ trim_blocks=missing,395+ lstrip_blocks=missing,396+ extensions=missing,397+ optimized=missing,398+ undefined=missing,399+ finalize=missing,400+ autoescape=missing,401+ loader=missing,402+ cache_size=missing,403+ auto_reload=missing,404+ bytecode_cache=missing,405+ ):406+ """Create a new overlay environment that shares all the data with the407+ current environment except for cache and the overridden attributes.408+ Extensions cannot be removed for an overlayed environment. An overlayed409+ environment automatically gets all the extensions of the environment it410+ is linked to plus optional extra extensions.411+412+ Creating overlays should happen after the initial environment was set413+ up completely. Not all attributes are truly linked, some are just414+ copied over so modifications on the original environment may not shine415+ through.416+ """417+ args = dict(locals())418+ del args["self"], args["cache_size"], args["extensions"]419+420+ rv = object.__new__(self.__class__)421+ rv.__dict__.update(self.__dict__)422+ rv.overlayed = True423+ rv.linked_to = self424+425+ for key, value in iteritems(args):426+ if value is not missing:427+ setattr(rv, key, value)428+429+ if cache_size is not missing:430+ rv.cache = create_cache(cache_size)431+ else:432+ rv.cache = copy_cache(self.cache)433+434+ rv.extensions = {}435+ for key, value in iteritems(self.extensions):436+ rv.extensions[key] = value.bind(rv)437+ if extensions is not missing:438+ rv.extensions.update(load_extensions(rv, extensions))439+440+ return _environment_sanity_check(rv)441+442+ lexer = property(get_lexer, doc="The lexer for this environment.")443+444+ def iter_extensions(self):445+ """Iterates over the extensions by priority."""446+ return iter(sorted(self.extensions.values(), key=lambda x: x.priority))447+448+ def getitem(self, obj, argument):449+ """Get an item or attribute of an object but prefer the item."""450+ try:451+ return obj[argument]452+ except (AttributeError, TypeError, LookupError):453+ if isinstance(argument, string_types):454+ try:455+ attr = str(argument)456+ except Exception:457+ pass458+ else:459+ try:460+ return getattr(obj, attr)461+ except AttributeError:462+ pass463+ return self.undefined(obj=obj, name=argument)464+465+ def getattr(self, obj, attribute):466+ """Get an item or attribute of an object but prefer the attribute.467+ Unlike :meth:`getitem` the attribute *must* be a bytestring.468+ """469+ try:470+ return getattr(obj, attribute)471+ except AttributeError:472+ pass473+ try:474+ return obj[attribute]475+ except (TypeError, LookupError, AttributeError):476+ return self.undefined(obj=obj, name=attribute)477+478+ def call_filter(479+ self, name, value, args=None, kwargs=None, context=None, eval_ctx=None480+ ):481+ """Invokes a filter on a value the same way the compiler does it.482+483+ Note that on Python 3 this might return a coroutine in case the484+ filter is running from an environment in async mode and the filter485+ supports async execution. It's your responsibility to await this486+ if needed.487+488+ .. versionadded:: 2.7489+ """490+ func = self.filters.get(name)491+ if func is None:492+ fail_for_missing_callable("no filter named %r", name)493+ args = [value] + list(args or ())494+ if getattr(func, "contextfilter", False):495+ if context is None:496+ raise TemplateRuntimeError(497+ "Attempted to invoke context filter without context"498+ )499+ args.insert(0, context)500+ elif getattr(func, "evalcontextfilter", False):501+ if eval_ctx is None:502+ if context is not None:503+ eval_ctx = context.eval_ctx504+ else:505+ eval_ctx = EvalContext(self)506+ args.insert(0, eval_ctx)507+ elif getattr(func, "environmentfilter", False):508+ args.insert(0, self)509+ return func(*args, **(kwargs or {}))510+511+ def call_test(self, name, value, args=None, kwargs=None):512+ """Invokes a test on a value the same way the compiler does it.513+514+ .. versionadded:: 2.7515+ """516+ func = self.tests.get(name)517+ if func is None:518+ fail_for_missing_callable("no test named %r", name)519+ return func(value, *(args or ()), **(kwargs or {}))520+521+ @internalcode522+ def parse(self, source, name=None, filename=None):523+ """Parse the sourcecode and return the abstract syntax tree. This524+ tree of nodes is used by the compiler to convert the template into525+ executable source- or bytecode. This is useful for debugging or to526+ extract information from templates.527+528+ If you are :ref:`developing Jinja extensions <writing-extensions>`529+ this gives you a good overview of the node tree generated.530+ """531+ try:532+ return self._parse(source, name, filename)533+ except TemplateSyntaxError:534+ self.handle_exception(source=source)535+536+ def _parse(self, source, name, filename):537+ """Internal parsing function used by `parse` and `compile`."""538+ return Parser(self, source, name, encode_filename(filename)).parse()539+540+ def lex(self, source, name=None, filename=None):541+ """Lex the given sourcecode and return a generator that yields542+ tokens as tuples in the form ``(lineno, token_type, value)``.543+ This can be useful for :ref:`extension development <writing-extensions>`544+ and debugging templates.545+546+ This does not perform preprocessing. If you want the preprocessing547+ of the extensions to be applied you have to filter source through548+ the :meth:`preprocess` method.549+ """550+ source = text_type(source)551+ try:552+ return self.lexer.tokeniter(source, name, filename)553+ except TemplateSyntaxError:554+ self.handle_exception(source=source)555+556+ def preprocess(self, source, name=None, filename=None):557+ """Preprocesses the source with all extensions. This is automatically558+ called for all parsing and compiling methods but *not* for :meth:`lex`559+ because there you usually only want the actual source tokenized.560+ """561+ return reduce(562+ lambda s, e: e.preprocess(s, name, filename),563+ self.iter_extensions(),564+ text_type(source),565+ )566+567+ def _tokenize(self, source, name, filename=None, state=None):568+ """Called by the parser to do the preprocessing and filtering569+ for all the extensions. Returns a :class:`~jinja2.lexer.TokenStream`.570+ """571+ source = self.preprocess(source, name, filename)572+ stream = self.lexer.tokenize(source, name, filename, state)573+ for ext in self.iter_extensions():574+ stream = ext.filter_stream(stream)575+ if not isinstance(stream, TokenStream):576+ stream = TokenStream(stream, name, filename)577+ return stream578+579+ def _generate(self, source, name, filename, defer_init=False):580+ """Internal hook that can be overridden to hook a different generate581+ method in.582+583+ .. versionadded:: 2.5584+ """585+ return generate(586+ source,587+ self,588+ name,589+ filename,590+ defer_init=defer_init,591+ optimized=self.optimized,592+ )593+594+ def _compile(self, source, filename):595+ """Internal hook that can be overridden to hook a different compile596+ method in.597+598+ .. versionadded:: 2.5599+ """600+ return compile(source, filename, "exec")601+602+ @internalcode603+ def compile(self, source, name=None, filename=None, raw=False, defer_init=False):604+ """Compile a node or template source code. The `name` parameter is605+ the load name of the template after it was joined using606+ :meth:`join_path` if necessary, not the filename on the file system.607+ the `filename` parameter is the estimated filename of the template on608+ the file system. If the template came from a database or memory this609+ can be omitted.610+611+ The return value of this method is a python code object. If the `raw`612+ parameter is `True` the return value will be a string with python613+ code equivalent to the bytecode returned otherwise. This method is614+ mainly used internally.615+616+ `defer_init` is use internally to aid the module code generator. This617+ causes the generated code to be able to import without the global618+ environment variable to be set.619+620+ .. versionadded:: 2.4621+ `defer_init` parameter added.622+ """623+ source_hint = None624+ try:625+ if isinstance(source, string_types):626+ source_hint = source627+ source = self._parse(source, name, filename)628+ source = self._generate(source, name, filename, defer_init=defer_init)629+ if raw:630+ return source631+ if filename is None:632+ filename = "<template>"633+ else:634+ filename = encode_filename(filename)635+ return self._compile(source, filename)636+ except TemplateSyntaxError:637+ self.handle_exception(source=source_hint)638+639+ def compile_expression(self, source, undefined_to_none=True):640+ """A handy helper method that returns a callable that accepts keyword641+ arguments that appear as variables in the expression. If called it642+ returns the result of the expression.643+644+ This is useful if applications want to use the same rules as Jinja645+ in template "configuration files" or similar situations.646+647+ Example usage:648+649+ >>> env = Environment()650+ >>> expr = env.compile_expression('foo == 42')651+ >>> expr(foo=23)652+ False653+ >>> expr(foo=42)654+ True655+656+ Per default the return value is converted to `None` if the657+ expression returns an undefined value. This can be changed658+ by setting `undefined_to_none` to `False`.659+660+ >>> env.compile_expression('var')() is None661+ True662+ >>> env.compile_expression('var', undefined_to_none=False)()663+ Undefined664+665+ .. versionadded:: 2.1666+ """667+ parser = Parser(self, source, state="variable")668+ try:669+ expr = parser.parse_expression()670+ if not parser.stream.eos:671+ raise TemplateSyntaxError(672+ "chunk after expression", parser.stream.current.lineno, None, None673+ )674+ expr.set_environment(self)675+ except TemplateSyntaxError:676+ if sys.exc_info() is not None:677+ self.handle_exception(source=source)678+679+ body = [nodes.Assign(nodes.Name("result", "store"), expr, lineno=1)]680+ template = self.from_string(nodes.Template(body, lineno=1))681+ return TemplateExpression(template, undefined_to_none)682+683+ def compile_templates(684+ self,685+ target,686+ extensions=None,687+ filter_func=None,688+ zip="deflated",689+ log_function=None,690+ ignore_errors=True,691+ py_compile=False,692+ ):693+ """Finds all the templates the loader can find, compiles them694+ and stores them in `target`. If `zip` is `None`, instead of in a695+ zipfile, the templates will be stored in a directory.696+ By default a deflate zip algorithm is used. To switch to697+ the stored algorithm, `zip` can be set to ``'stored'``.698+699+ `extensions` and `filter_func` are passed to :meth:`list_templates`.700+ Each template returned will be compiled to the target folder or701+ zipfile.702+703+ By default template compilation errors are ignored. In case a704+ log function is provided, errors are logged. If you want template705+ syntax errors to abort the compilation you can set `ignore_errors`706+ to `False` and you will get an exception on syntax errors.707+708+ If `py_compile` is set to `True` .pyc files will be written to the709+ target instead of standard .py files. This flag does not do anything710+ on pypy and Python 3 where pyc files are not picked up by itself and711+ don't give much benefit.712+713+ .. versionadded:: 2.4714+ """715+ from .loaders import ModuleLoader716+717+ if log_function is None:718+719+ def log_function(x):720+ pass721+722+ if py_compile:723+ if not PY2 or PYPY:724+ import warnings725+726+ warnings.warn(727+ "'py_compile=True' has no effect on PyPy or Python"728+ " 3 and will be removed in version 3.0",729+ DeprecationWarning,730+ stacklevel=2,731+ )732+ py_compile = False733+ else:734+ import imp735+ import marshal736+737+ py_header = imp.get_magic() + u"\xff\xff\xff\xff".encode("iso-8859-15")738+739+ # Python 3.3 added a source filesize to the header740+ if sys.version_info >= (3, 3):741+ py_header += u"\x00\x00\x00\x00".encode("iso-8859-15")742+743+ def write_file(filename, data):744+ if zip:745+ info = ZipInfo(filename)746+ info.external_attr = 0o755 << 16747+ zip_file.writestr(info, data)748+ else:749+ if isinstance(data, text_type):750+ data = data.encode("utf8")751+752+ with open(os.path.join(target, filename), "wb") as f:753+ f.write(data)754+755+ if zip is not None:756+ from zipfile import ZipFile, ZipInfo, ZIP_DEFLATED, ZIP_STORED757+758+ zip_file = ZipFile(759+ target, "w", dict(deflated=ZIP_DEFLATED, stored=ZIP_STORED)[zip]760+ )761+ log_function('Compiling into Zip archive "%s"' % target)762+ else:763+ if not os.path.isdir(target):764+ os.makedirs(target)765+ log_function('Compiling into folder "%s"' % target)766+767+ try:768+ for name in self.list_templates(extensions, filter_func):769+ source, filename, _ = self.loader.get_source(self, name)770+ try:771+ code = self.compile(source, name, filename, True, True)772+ except TemplateSyntaxError as e:773+ if not ignore_errors:774+ raise775+ log_function('Could not compile "%s": %s' % (name, e))776+ continue777+778+ filename = ModuleLoader.get_module_filename(name)779+780+ if py_compile:781+ c = self._compile(code, encode_filename(filename))782+ write_file(filename + "c", py_header + marshal.dumps(c))783+ log_function('Byte-compiled "%s" as %s' % (name, filename + "c"))784+ else:785+ write_file(filename, code)786+ log_function('Compiled "%s" as %s' % (name, filename))787+ finally:788+ if zip:789+ zip_file.close()790+791+ log_function("Finished compiling templates")792+793+ def list_templates(self, extensions=None, filter_func=None):794+ """Returns a list of templates for this environment. This requires795+ that the loader supports the loader's796+ :meth:`~BaseLoader.list_templates` method.797+798+ If there are other files in the template folder besides the799+ actual templates, the returned list can be filtered. There are two800+ ways: either `extensions` is set to a list of file extensions for801+ templates, or a `filter_func` can be provided which is a callable that802+ is passed a template name and should return `True` if it should end up803+ in the result list.804+805+ If the loader does not support that, a :exc:`TypeError` is raised.806+807+ .. versionadded:: 2.4808+ """809+ names = self.loader.list_templates()810+811+ if extensions is not None:812+ if filter_func is not None:813+ raise TypeError(814+ "either extensions or filter_func can be passed, but not both"815+ )816+817+ def filter_func(x):818+ return "." in x and x.rsplit(".", 1)[1] in extensions819+820+ if filter_func is not None:821+ names = [name for name in names if filter_func(name)]822+823+ return names824+825+ def handle_exception(self, source=None):826+ """Exception handling helper. This is used internally to either raise827+ rewritten exceptions or return a rendered traceback for the template.828+ """829+ from .debug import rewrite_traceback_stack830+831+ reraise(*rewrite_traceback_stack(source=source))832+833+ def join_path(self, template, parent):834+ """Join a template with the parent. By default all the lookups are835+ relative to the loader root so this method returns the `template`836+ parameter unchanged, but if the paths should be relative to the837+ parent template, this function can be used to calculate the real838+ template name.839+840+ Subclasses may override this method and implement template path841+ joining here.842+ """843+ return template844+845+ @internalcode846+ def _load_template(self, name, globals):847+ if self.loader is None:848+ raise TypeError("no loader for this environment specified")849+ cache_key = (weakref.ref(self.loader), name)850+ if self.cache is not None:851+ template = self.cache.get(cache_key)852+ if template is not None and (853+ not self.auto_reload or template.is_up_to_date854+ ):855+ return template856+ template = self.loader.load(self, name, globals)857+ if self.cache is not None:858+ self.cache[cache_key] = template859+ return template860+861+ @internalcode862+ def get_template(self, name, parent=None, globals=None):863+ """Load a template from the loader. If a loader is configured this864+ method asks the loader for the template and returns a :class:`Template`.865+ If the `parent` parameter is not `None`, :meth:`join_path` is called866+ to get the real template name before loading.867+868+ The `globals` parameter can be used to provide template wide globals.869+ These variables are available in the context at render time.870+871+ If the template does not exist a :exc:`TemplateNotFound` exception is872+ raised.873+874+ .. versionchanged:: 2.4875+ If `name` is a :class:`Template` object it is returned from the876+ function unchanged.877+ """878+ if isinstance(name, Template):879+ return name880+ if parent is not None:881+ name = self.join_path(name, parent)882+ return self._load_template(name, self.make_globals(globals))883+884+ @internalcode885+ def select_template(self, names, parent=None, globals=None):886+ """Works like :meth:`get_template` but tries a number of templates887+ before it fails. If it cannot find any of the templates, it will888+ raise a :exc:`TemplatesNotFound` exception.889+890+ .. versionchanged:: 2.11891+ If names is :class:`Undefined`, an :exc:`UndefinedError` is892+ raised instead. If no templates were found and names893+ contains :class:`Undefined`, the message is more helpful.894+895+ .. versionchanged:: 2.4896+ If `names` contains a :class:`Template` object it is returned897+ from the function unchanged.898+899+ .. versionadded:: 2.3900+ """901+ if isinstance(names, Undefined):902+ names._fail_with_undefined_error()903+904+ if not names:905+ raise TemplatesNotFound(906+ message=u"Tried to select from an empty list " u"of templates."907+ )908+ globals = self.make_globals(globals)909+ for name in names:910+ if isinstance(name, Template):911+ return name912+ if parent is not None:913+ name = self.join_path(name, parent)914+ try:915+ return self._load_template(name, globals)916+ except (TemplateNotFound, UndefinedError):917+ pass918+ raise TemplatesNotFound(names)919+920+ @internalcode921+ def get_or_select_template(self, template_name_or_list, parent=None, globals=None):922+ """Does a typecheck and dispatches to :meth:`select_template`923+ if an iterable of template names is given, otherwise to924+ :meth:`get_template`.925+926+ .. versionadded:: 2.3927+ """928+ if isinstance(template_name_or_list, (string_types, Undefined)):929+ return self.get_template(template_name_or_list, parent, globals)930+ elif isinstance(template_name_or_list, Template):931+ return template_name_or_list932+ return self.select_template(template_name_or_list, parent, globals)933+934+ def from_string(self, source, globals=None, template_class=None):935+ """Load a template from a string. This parses the source given and936+ returns a :class:`Template` object.937+ """938+ globals = self.make_globals(globals)939+ cls = template_class or self.template_class940+ return cls.from_code(self, self.compile(source), globals, None)941+942+ def make_globals(self, d):943+ """Return a dict for the globals."""944+ if not d:945+ return self.globals946+ return dict(self.globals, **d)947+948+949+class Template(object):950+ """The central template object. This class represents a compiled template951+ and is used to evaluate it.952+953+ Normally the template object is generated from an :class:`Environment` but954+ it also has a constructor that makes it possible to create a template955+ instance directly using the constructor. It takes the same arguments as956+ the environment constructor but it's not possible to specify a loader.957+958+ Every template object has a few methods and members that are guaranteed959+ to exist. However it's important that a template object should be960+ considered immutable. Modifications on the object are not supported.961+962+ Template objects created from the constructor rather than an environment963+ do have an `environment` attribute that points to a temporary environment964+ that is probably shared with other templates created with the constructor965+ and compatible settings.966+967+ >>> template = Template('Hello {{ name }}!')968+ >>> template.render(name='John Doe') == u'Hello John Doe!'969+ True970+ >>> stream = template.stream(name='John Doe')971+ >>> next(stream) == u'Hello John Doe!'972+ True973+ >>> next(stream)974+ Traceback (most recent call last):975+ ...976+ StopIteration977+ """978+979+ #: Type of environment to create when creating a template directly980+ #: rather than through an existing environment.981+ environment_class = Environment982+983+ def __new__(984+ cls,985+ source,986+ block_start_string=BLOCK_START_STRING,987+ block_end_string=BLOCK_END_STRING,988+ variable_start_string=VARIABLE_START_STRING,989+ variable_end_string=VARIABLE_END_STRING,990+ comment_start_string=COMMENT_START_STRING,991+ comment_end_string=COMMENT_END_STRING,992+ line_statement_prefix=LINE_STATEMENT_PREFIX,993+ line_comment_prefix=LINE_COMMENT_PREFIX,994+ trim_blocks=TRIM_BLOCKS,995+ lstrip_blocks=LSTRIP_BLOCKS,996+ newline_sequence=NEWLINE_SEQUENCE,997+ keep_trailing_newline=KEEP_TRAILING_NEWLINE,998+ extensions=(),999+ optimized=True,1000+ undefined=Undefined,1001+ finalize=None,1002+ autoescape=False,1003+ enable_async=False,1004+ ):1005+ env = get_spontaneous_environment(1006+ cls.environment_class,1007+ block_start_string,1008+ block_end_string,1009+ variable_start_string,1010+ variable_end_string,1011+ comment_start_string,1012+ comment_end_string,1013+ line_statement_prefix,1014+ line_comment_prefix,1015+ trim_blocks,1016+ lstrip_blocks,1017+ newline_sequence,1018+ keep_trailing_newline,1019+ frozenset(extensions),1020+ optimized,1021+ undefined,1022+ finalize,1023+ autoescape,1024+ None,1025+ 0,1026+ False,1027+ None,1028+ enable_async,1029+ )1030+ return env.from_string(source, template_class=cls)1031+1032+ @classmethod1033+ def from_code(cls, environment, code, globals, uptodate=None):1034+ """Creates a template object from compiled code and the globals. This1035+ is used by the loaders and environment to create a template object.1036+ """1037+ namespace = {"environment": environment, "__file__": code.co_filename}1038+ exec(code, namespace)1039+ rv = cls._from_namespace(environment, namespace, globals)1040+ rv._uptodate = uptodate1041+ return rv1042+1043+ @classmethod1044+ def from_module_dict(cls, environment, module_dict, globals):1045+ """Creates a template object from a module. This is used by the1046+ module loader to create a template object.1047+1048+ .. versionadded:: 2.41049+ """1050+ return cls._from_namespace(environment, module_dict, globals)1051+1052+ @classmethod1053+ def _from_namespace(cls, environment, namespace, globals):1054+ t = object.__new__(cls)1055+ t.environment = environment1056+ t.globals = globals1057+ t.name = namespace["name"]1058+ t.filename = namespace["__file__"]1059+ t.blocks = namespace["blocks"]1060+1061+ # render function and module1062+ t.root_render_func = namespace["root"]1063+ t._module = None1064+1065+ # debug and loader helpers1066+ t._debug_info = namespace["debug_info"]1067+ t._uptodate = None1068+1069+ # store the reference1070+ namespace["environment"] = environment1071+ namespace["__jinja_template__"] = t1072+1073+ return t1074+1075+ def render(self, *args, **kwargs):1076+ """This method accepts the same arguments as the `dict` constructor:1077+ A dict, a dict subclass or some keyword arguments. If no arguments1078+ are given the context will be empty. These two calls do the same::1079+1080+ template.render(knights='that say nih')1081+ template.render({'knights': 'that say nih'})1082+1083+ This will return the rendered template as unicode string.1084+ """1085+ vars = dict(*args, **kwargs)1086+ try:1087+ return concat(self.root_render_func(self.new_context(vars)))1088+ except Exception:1089+ self.environment.handle_exception()1090+1091+ def render_async(self, *args, **kwargs):1092+ """This works similar to :meth:`render` but returns a coroutine1093+ that when awaited returns the entire rendered template string. This1094+ requires the async feature to be enabled.1095+1096+ Example usage::1097+1098+ await template.render_async(knights='that say nih; asynchronously')1099+ """1100+ # see asyncsupport for the actual implementation1101+ raise NotImplementedError(1102+ "This feature is not available for this version of Python"1103+ )1104+1105+ def stream(self, *args, **kwargs):1106+ """Works exactly like :meth:`generate` but returns a1107+ :class:`TemplateStream`.1108+ """1109+ return TemplateStream(self.generate(*args, **kwargs))1110+1111+ def generate(self, *args, **kwargs):1112+ """For very large templates it can be useful to not render the whole1113+ template at once but evaluate each statement after another and yield1114+ piece for piece. This method basically does exactly that and returns1115+ a generator that yields one item after another as unicode strings.1116+1117+ It accepts the same arguments as :meth:`render`.1118+ """1119+ vars = dict(*args, **kwargs)1120+ try:1121+ for event in self.root_render_func(self.new_context(vars)):1122+ yield event1123+ except Exception:1124+ yield self.environment.handle_exception()1125+1126+ def generate_async(self, *args, **kwargs):1127+ """An async version of :meth:`generate`. Works very similarly but1128+ returns an async iterator instead.1129+ """1130+ # see asyncsupport for the actual implementation1131+ raise NotImplementedError(1132+ "This feature is not available for this version of Python"1133+ )1134+1135+ def new_context(self, vars=None, shared=False, locals=None):1136+ """Create a new :class:`Context` for this template. The vars1137+ provided will be passed to the template. Per default the globals1138+ are added to the context. If shared is set to `True` the data1139+ is passed as is to the context without adding the globals.1140+1141+ `locals` can be a dict of local variables for internal usage.1142+ """1143+ return new_context(1144+ self.environment, self.name, self.blocks, vars, shared, self.globals, locals1145+ )1146+1147+ def make_module(self, vars=None, shared=False, locals=None):1148+ """This method works like the :attr:`module` attribute when called1149+ without arguments but it will evaluate the template on every call1150+ rather than caching it. It's also possible to provide1151+ a dict which is then used as context. The arguments are the same1152+ as for the :meth:`new_context` method.1153+ """1154+ return TemplateModule(self, self.new_context(vars, shared, locals))1155+1156+ def make_module_async(self, vars=None, shared=False, locals=None):1157+ """As template module creation can invoke template code for1158+ asynchronous executions this method must be used instead of the1159+ normal :meth:`make_module` one. Likewise the module attribute1160+ becomes unavailable in async mode.1161+ """1162+ # see asyncsupport for the actual implementation1163+ raise NotImplementedError(1164+ "This feature is not available for this version of Python"1165+ )1166+1167+ @internalcode1168+ def _get_default_module(self):1169+ if self._module is not None:1170+ return self._module1171+ self._module = rv = self.make_module()1172+ return rv1173+1174+ @property1175+ def module(self):1176+ """The template as module. This is used for imports in the1177+ template runtime but is also useful if one wants to access1178+ exported template variables from the Python layer:1179+1180+ >>> t = Template('{% macro foo() %}42{% endmacro %}23')1181+ >>> str(t.module)1182+ '23'1183+ >>> t.module.foo() == u'42'1184+ True1185+1186+ This attribute is not available if async mode is enabled.1187+ """1188+ return self._get_default_module()1189+1190+ def get_corresponding_lineno(self, lineno):1191+ """Return the source line number of a line number in the1192+ generated bytecode as they are not in sync.1193+ """1194+ for template_line, code_line in reversed(self.debug_info):1195+ if code_line <= lineno:1196+ return template_line1197+ return 11198+1199+ @property1200+ def is_up_to_date(self):1201+ """If this variable is `False` there is a newer version available."""1202+ if self._uptodate is None:1203+ return True1204+ return self._uptodate()1205+1206+ @property1207+ def debug_info(self):1208+ """The debug info mapping."""1209+ if self._debug_info:1210+ return [tuple(map(int, x.split("="))) for x in self._debug_info.split("&")]1211+ return []1212+1213+ def __repr__(self):1214+ if self.name is None:1215+ name = "memory:%x" % id(self)1216+ else:1217+ name = repr(self.name)1218+ return "<%s %s>" % (self.__class__.__name__, name)1219+1220+1221+@implements_to_string1222+class TemplateModule(object):1223+ """Represents an imported template. All the exported names of the1224+ template are available as attributes on this object. Additionally1225+ converting it into an unicode- or bytestrings renders the contents.1226+ """1227+1228+ def __init__(self, template, context, body_stream=None):1229+ if body_stream is None:1230+ if context.environment.is_async:1231+ raise RuntimeError(1232+ "Async mode requires a body stream "1233+ "to be passed to a template module. Use "1234+ "the async methods of the API you are "1235+ "using."1236+ )1237+ body_stream = list(template.root_render_func(context))1238+ self._body_stream = body_stream1239+ self.__dict__.update(context.get_exported())1240+ self.__name__ = template.name1241+1242+ def __html__(self):1243+ return Markup(concat(self._body_stream))1244+1245+ def __str__(self):1246+ return concat(self._body_stream)1247+1248+ def __repr__(self):1249+ if self.__name__ is None:1250+ name = "memory:%x" % id(self)1251+ else:1252+ name = repr(self.__name__)1253+ return "<%s %s>" % (self.__class__.__name__, name)1254+1255+1256+class TemplateExpression(object):1257+ """The :meth:`jinja2.Environment.compile_expression` method returns an1258+ instance of this object. It encapsulates the expression-like access1259+ to the template with an expression it wraps.1260+ """1261+1262+ def __init__(self, template, undefined_to_none):1263+ self._template = template1264+ self._undefined_to_none = undefined_to_none1265+1266+ def __call__(self, *args, **kwargs):1267+ context = self._template.new_context(dict(*args, **kwargs))1268+ consume(self._template.root_render_func(context))1269+ rv = context.vars["result"]1270+ if self._undefined_to_none and isinstance(rv, Undefined):1271+ rv = None1272+ return rv1273+1274+1275+@implements_iterator1276+class TemplateStream(object):1277+ """A template stream works pretty much like an ordinary python generator1278+ but it can buffer multiple items to reduce the number of total iterations.1279+ Per default the output is unbuffered which means that for every unbuffered1280+ instruction in the template one unicode string is yielded.1281+1282+ If buffering is enabled with a buffer size of 5, five items are combined1283+ into a new unicode string. This is mainly useful if you are streaming1284+ big templates to a client via WSGI which flushes after each iteration.1285+ """1286+1287+ def __init__(self, gen):1288+ self._gen = gen1289+ self.disable_buffering()1290+1291+ def dump(self, fp, encoding=None, errors="strict"):1292+ """Dump the complete stream into a file or file-like object.1293+ Per default unicode strings are written, if you want to encode1294+ before writing specify an `encoding`.1295+1296+ Example usage::1297+1298+ Template('Hello {{ name }}!').stream(name='foo').dump('hello.html')1299+ """1300+ close = False1301+ if isinstance(fp, string_types):1302+ if encoding is None:1303+ encoding = "utf-8"1304+ fp = open(fp, "wb")1305+ close = True1306+ try:1307+ if encoding is not None:1308+ iterable = (x.encode(encoding, errors) for x in self)1309+ else:1310+ iterable = self1311+ if hasattr(fp, "writelines"):1312+ fp.writelines(iterable)1313+ else:1314+ for item in iterable:1315+ fp.write(item)1316+ finally:1317+ if close:1318+ fp.close()1319+1320+ def disable_buffering(self):1321+ """Disable the output buffering."""1322+ self._next = partial(next, self._gen)1323+ self.buffered = False1324+1325+ def _buffered_generator(self, size):1326+ buf = []1327+ c_size = 01328+ push = buf.append1329+1330+ while 1:1331+ try:1332+ while c_size < size:1333+ c = next(self._gen)1334+ push(c)1335+ if c:1336+ c_size += 11337+ except StopIteration:1338+ if not c_size:1339+ return1340+ yield concat(buf)1341+ del buf[:]1342+ c_size = 01343+1344+ def enable_buffering(self, size=5):1345+ """Enable buffering. Buffer `size` items before yielding them."""1346+ if size <= 1:1347+ raise ValueError("buffer size too small")1348+1349+ self.buffered = True1350+ self._next = partial(next, self._buffered_generator(size))1351+1352+ def __iter__(self):1353+ return self1354+1355+ def __next__(self):1356+ return self._next()1357+1358+1359+# hook in default template class. if anyone reads this comment: ignore that1360+# it's possible to use custom templates ;-)1361+Environment.template_class = Templateadded:src/jinja2/exceptions.py+177 added
1+# -*- coding: utf-8 -*-2+from ._compat import imap3+from ._compat import implements_to_string4+from ._compat import PY25+from ._compat import text_type6+7+8+class TemplateError(Exception):9+ """Baseclass for all template errors."""10+11+ if PY2:12+13+ def __init__(self, message=None):14+ if message is not None:15+ message = text_type(message).encode("utf-8")16+ Exception.__init__(self, message)17+18+ @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")24+25+ def __unicode__(self):26+ return self.message or u""27+28+ else:29+30+ def __init__(self, message=None):31+ Exception.__init__(self, message)32+33+ @property34+ def message(self):35+ if self.args:36+ message = self.args[0]37+ if message is not None:38+ return message39+40+41+@implements_to_string42+class TemplateNotFound(IOError, LookupError, TemplateError):43+ """Raised if a template does not exist.44+45+ .. versionchanged:: 2.1146+ If the given name is :class:`Undefined` and no message was47+ provided, an :exc:`UndefinedError` is raised.48+ """49+50+ # looks weird, but removes the warning descriptor that just51+ # bogusly warns us about message being deprecated52+ message = None53+54+ def __init__(self, name, message=None):55+ IOError.__init__(self, name)56+57+ if message is None:58+ from .runtime import Undefined59+60+ if isinstance(name, Undefined):61+ name._fail_with_undefined_error()62+63+ message = name64+65+ self.message = message66+ self.name = name67+ self.templates = [name]68+69+ def __str__(self):70+ return self.message71+72+73+class TemplatesNotFound(TemplateNotFound):74+ """Like :class:`TemplateNotFound` but raised if multiple templates75+ are selected. This is a subclass of :class:`TemplateNotFound`76+ exception, so just catching the base exception will catch both.77+78+ .. versionchanged:: 2.1179+ If a name in the list of names is :class:`Undefined`, a message80+ about it being undefined is shown rather than the empty string.81+82+ .. versionadded:: 2.283+ """84+85+ def __init__(self, names=(), message=None):86+ if message is None:87+ from .runtime import Undefined88+89+ parts = []90+91+ for name in names:92+ if isinstance(name, Undefined):93+ parts.append(name._undefined_message)94+ else:95+ parts.append(name)96+97+ message = u"none of the templates given were found: " + u", ".join(98+ imap(text_type, parts)99+ )100+ TemplateNotFound.__init__(self, names and names[-1] or None, message)101+ self.templates = list(names)102+103+104+@implements_to_string105+class TemplateSyntaxError(TemplateError):106+ """Raised to tell the user that there is a problem with the template."""107+108+ def __init__(self, message, lineno, name=None, filename=None):109+ TemplateError.__init__(self, message)110+ self.lineno = lineno111+ self.name = name112+ self.filename = filename113+ self.source = None114+115+ # this is set to True if the debug.translate_syntax_error116+ # function translated the syntax error into a new traceback117+ self.translated = False118+119+ def __str__(self):120+ # for translated errors we only return the message121+ if self.translated:122+ return self.message123+124+ # otherwise attach some stuff125+ location = "line %d" % self.lineno126+ name = self.filename or self.name127+ if name:128+ location = 'File "%s", %s' % (name, location)129+ lines = [self.message, " " + location]130+131+ # if the source is set, add the line to the output132+ if self.source is not None:133+ try:134+ line = self.source.splitlines()[self.lineno - 1]135+ except IndexError:136+ line = None137+ if line:138+ lines.append(" " + line.strip())139+140+ return u"\n".join(lines)141+142+ def __reduce__(self):143+ # https://bugs.python.org/issue1692335 Exceptions that take144+ # multiple required arguments have problems with pickling.145+ # Without this, raises TypeError: __init__() missing 1 required146+ # positional argument: 'lineno'147+ return self.__class__, (self.message, self.lineno, self.name, self.filename)148+149+150+class TemplateAssertionError(TemplateSyntaxError):151+ """Like a template syntax error, but covers cases where something in the152+ template caused an error at compile time that wasn't necessarily caused153+ by a syntax error. However it's a direct subclass of154+ :exc:`TemplateSyntaxError` and has the same attributes.155+ """156+157+158+class TemplateRuntimeError(TemplateError):159+ """A generic runtime error in the template engine. Under some situations160+ Jinja may raise this exception.161+ """162+163+164+class UndefinedError(TemplateRuntimeError):165+ """Raised if a template tries to operate on :class:`Undefined`."""166+167+168+class SecurityError(TemplateRuntimeError):169+ """Raised if a template tries to do something insecure if the170+ sandbox is enabled.171+ """172+173+174+class FilterArgumentError(TemplateRuntimeError):175+ """This error is raised if a filter was called with inappropriate176+ arguments177+ """added:src/jinja2/ext.py+703 added
1+# -*- coding: utf-8 -*-2+"""Extension API for adding custom tags and behavior."""3+import pprint4+import re5+from sys import version_info6+7+from . import nodes8+from ._compat import iteritems9+from ._compat import string_types10+from ._compat import with_metaclass11+from .defaults import BLOCK_END_STRING12+from .defaults import BLOCK_START_STRING13+from .defaults import COMMENT_END_STRING14+from .defaults import COMMENT_START_STRING15+from .defaults import KEEP_TRAILING_NEWLINE16+from .defaults import LINE_COMMENT_PREFIX17+from .defaults import LINE_STATEMENT_PREFIX18+from .defaults import LSTRIP_BLOCKS19+from .defaults import NEWLINE_SEQUENCE20+from .defaults import TRIM_BLOCKS21+from .defaults import VARIABLE_END_STRING22+from .defaults import VARIABLE_START_STRING23+from .environment import Environment24+from .exceptions import TemplateAssertionError25+from .exceptions import TemplateSyntaxError26+from .nodes import ContextReference27+from .runtime import concat28+from .utils import contextfunction29+from .utils import import_string30+from .utils import Markup31+32+# the only real useful gettext functions for a Jinja template. Note33+# that ugettext must be assigned to gettext as Jinja doesn't support34+# non unicode strings.35+GETTEXT_FUNCTIONS = ("_", "gettext", "ngettext")36+37+_ws_re = re.compile(r"\s*\n\s*")38+39+40+class ExtensionRegistry(type):41+ """Gives the extension an unique identifier."""42+43+ def __new__(mcs, name, bases, d):44+ rv = type.__new__(mcs, name, bases, d)45+ rv.identifier = rv.__module__ + "." + rv.__name__46+ return rv47+48+49+class Extension(with_metaclass(ExtensionRegistry, object)):50+ """Extensions can be used to add extra functionality to the Jinja template51+ system at the parser level. Custom extensions are bound to an environment52+ but may not store environment specific data on `self`. The reason for53+ this is that an extension can be bound to another environment (for54+ overlays) by creating a copy and reassigning the `environment` attribute.55+56+ As extensions are created by the environment they cannot accept any57+ arguments for configuration. One may want to work around that by using58+ a factory function, but that is not possible as extensions are identified59+ by their import name. The correct way to configure the extension is60+ storing the configuration values on the environment. Because this way the61+ environment ends up acting as central configuration storage the62+ attributes may clash which is why extensions have to ensure that the names63+ they choose for configuration are not too generic. ``prefix`` for example64+ is a terrible name, ``fragment_cache_prefix`` on the other hand is a good65+ name as includes the name of the extension (fragment cache).66+ """67+68+ #: if this extension parses this is the list of tags it's listening to.69+ tags = set()70+71+ #: the priority of that extension. This is especially useful for72+ #: extensions that preprocess values. A lower value means higher73+ #: priority.74+ #:75+ #: .. versionadded:: 2.476+ priority = 10077+78+ def __init__(self, environment):79+ self.environment = environment80+81+ def bind(self, environment):82+ """Create a copy of this extension bound to another environment."""83+ rv = object.__new__(self.__class__)84+ rv.__dict__.update(self.__dict__)85+ rv.environment = environment86+ return rv87+88+ def preprocess(self, source, name, filename=None):89+ """This method is called before the actual lexing and can be used to90+ preprocess the source. The `filename` is optional. The return value91+ must be the preprocessed source.92+ """93+ return source94+95+ def filter_stream(self, stream):96+ """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used97+ to filter tokens returned. This method has to return an iterable of98+ :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a99+ :class:`~jinja2.lexer.TokenStream`.100+ """101+ return stream102+103+ def parse(self, parser):104+ """If any of the :attr:`tags` matched this method is called with the105+ parser as first argument. The token the parser stream is pointing at106+ is the name token that matched. This method has to return one or a107+ list of multiple nodes.108+ """109+ raise NotImplementedError()110+111+ def attr(self, name, lineno=None):112+ """Return an attribute node for the current extension. This is useful113+ to pass constants on extensions to generated template code.114+115+ ::116+117+ self.attr('_my_attribute', lineno=lineno)118+ """119+ return nodes.ExtensionAttribute(self.identifier, name, lineno=lineno)120+121+ def call_method(122+ self, name, args=None, kwargs=None, dyn_args=None, dyn_kwargs=None, lineno=None123+ ):124+ """Call a method of the extension. This is a shortcut for125+ :meth:`attr` + :class:`jinja2.nodes.Call`.126+ """127+ if args is None:128+ args = []129+ if kwargs is None:130+ kwargs = []131+ return nodes.Call(132+ self.attr(name, lineno=lineno),133+ args,134+ kwargs,135+ dyn_args,136+ dyn_kwargs,137+ lineno=lineno,138+ )139+140+141+@contextfunction142+def _gettext_alias(__context, *args, **kwargs):143+ return __context.call(__context.resolve("gettext"), *args, **kwargs)144+145+146+def _make_new_gettext(func):147+ @contextfunction148+ def gettext(__context, __string, **variables):149+ rv = __context.call(func, __string)150+ if __context.eval_ctx.autoescape:151+ rv = Markup(rv)152+ # Always treat as a format string, even if there are no153+ # variables. This makes translation strings more consistent154+ # and predictable. This requires escaping155+ return rv % variables156+157+ return gettext158+159+160+def _make_new_ngettext(func):161+ @contextfunction162+ def ngettext(__context, __singular, __plural, __num, **variables):163+ variables.setdefault("num", __num)164+ rv = __context.call(func, __singular, __plural, __num)165+ if __context.eval_ctx.autoescape:166+ rv = Markup(rv)167+ # Always treat as a format string, see gettext comment above.168+ return rv % variables169+170+ return ngettext171+172+173+class InternationalizationExtension(Extension):174+ """This extension adds gettext support to Jinja."""175+176+ tags = {"trans"}177+178+ # TODO: the i18n extension is currently reevaluating values in a few179+ # situations. Take this example:180+ # {% trans count=something() %}{{ count }} foo{% pluralize181+ # %}{{ count }} fooss{% endtrans %}182+ # something is called twice here. One time for the gettext value and183+ # the other time for the n-parameter of the ngettext function.184+185+ def __init__(self, environment):186+ Extension.__init__(self, environment)187+ environment.globals["_"] = _gettext_alias188+ environment.extend(189+ install_gettext_translations=self._install,190+ install_null_translations=self._install_null,191+ install_gettext_callables=self._install_callables,192+ uninstall_gettext_translations=self._uninstall,193+ extract_translations=self._extract,194+ newstyle_gettext=False,195+ )196+197+ def _install(self, translations, newstyle=None):198+ gettext = getattr(translations, "ugettext", None)199+ if gettext is None:200+ gettext = translations.gettext201+ ngettext = getattr(translations, "ungettext", None)202+ if ngettext is None:203+ ngettext = translations.ngettext204+ self._install_callables(gettext, ngettext, newstyle)205+206+ def _install_null(self, newstyle=None):207+ self._install_callables(208+ lambda x: x, lambda s, p, n: (n != 1 and (p,) or (s,))[0], newstyle209+ )210+211+ def _install_callables(self, gettext, ngettext, newstyle=None):212+ if newstyle is not None:213+ self.environment.newstyle_gettext = newstyle214+ if self.environment.newstyle_gettext:215+ gettext = _make_new_gettext(gettext)216+ ngettext = _make_new_ngettext(ngettext)217+ self.environment.globals.update(gettext=gettext, ngettext=ngettext)218+219+ def _uninstall(self, translations):220+ for key in "gettext", "ngettext":221+ self.environment.globals.pop(key, None)222+223+ def _extract(self, source, gettext_functions=GETTEXT_FUNCTIONS):224+ if isinstance(source, string_types):225+ source = self.environment.parse(source)226+ return extract_from_ast(source, gettext_functions)227+228+ def parse(self, parser):229+ """Parse a translatable tag."""230+ lineno = next(parser.stream).lineno231+ num_called_num = False232+233+ # find all the variables referenced. Additionally a variable can be234+ # defined in the body of the trans block too, but this is checked at235+ # a later state.236+ plural_expr = None237+ plural_expr_assignment = None238+ variables = {}239+ trimmed = None240+ while parser.stream.current.type != "block_end":241+ if variables:242+ parser.stream.expect("comma")243+244+ # skip colon for python compatibility245+ if parser.stream.skip_if("colon"):246+ break247+248+ name = parser.stream.expect("name")249+ if name.value in variables:250+ parser.fail(251+ "translatable variable %r defined twice." % name.value,252+ name.lineno,253+ exc=TemplateAssertionError,254+ )255+256+ # expressions257+ if parser.stream.current.type == "assign":258+ next(parser.stream)259+ variables[name.value] = var = parser.parse_expression()260+ elif trimmed is None and name.value in ("trimmed", "notrimmed"):261+ trimmed = name.value == "trimmed"262+ continue263+ else:264+ variables[name.value] = var = nodes.Name(name.value, "load")265+266+ if plural_expr is None:267+ if isinstance(var, nodes.Call):268+ plural_expr = nodes.Name("_trans", "load")269+ variables[name.value] = plural_expr270+ plural_expr_assignment = nodes.Assign(271+ nodes.Name("_trans", "store"), var272+ )273+ else:274+ plural_expr = var275+ num_called_num = name.value == "num"276+277+ parser.stream.expect("block_end")278+279+ plural = None280+ have_plural = False281+ referenced = set()282+283+ # now parse until endtrans or pluralize284+ singular_names, singular = self._parse_block(parser, True)285+ if singular_names:286+ referenced.update(singular_names)287+ if plural_expr is None:288+ plural_expr = nodes.Name(singular_names[0], "load")289+ num_called_num = singular_names[0] == "num"290+291+ # if we have a pluralize block, we parse that too292+ if parser.stream.current.test("name:pluralize"):293+ have_plural = True294+ next(parser.stream)295+ if parser.stream.current.type != "block_end":296+ name = parser.stream.expect("name")297+ if name.value not in variables:298+ parser.fail(299+ "unknown variable %r for pluralization" % name.value,300+ name.lineno,301+ exc=TemplateAssertionError,302+ )303+ plural_expr = variables[name.value]304+ num_called_num = name.value == "num"305+ parser.stream.expect("block_end")306+ plural_names, plural = self._parse_block(parser, False)307+ next(parser.stream)308+ referenced.update(plural_names)309+ else:310+ next(parser.stream)311+312+ # register free names as simple name expressions313+ for var in referenced:314+ if var not in variables:315+ variables[var] = nodes.Name(var, "load")316+317+ if not have_plural:318+ plural_expr = None319+ elif plural_expr is None:320+ parser.fail("pluralize without variables", lineno)321+322+ if trimmed is None:323+ trimmed = self.environment.policies["ext.i18n.trimmed"]324+ if trimmed:325+ singular = self._trim_whitespace(singular)326+ if plural:327+ plural = self._trim_whitespace(plural)328+329+ node = self._make_node(330+ singular,331+ plural,332+ variables,333+ plural_expr,334+ bool(referenced),335+ num_called_num and have_plural,336+ )337+ node.set_lineno(lineno)338+ if plural_expr_assignment is not None:339+ return [plural_expr_assignment, node]340+ else:341+ return node342+343+ def _trim_whitespace(self, string, _ws_re=_ws_re):344+ return _ws_re.sub(" ", string.strip())345+346+ def _parse_block(self, parser, allow_pluralize):347+ """Parse until the next block tag with a given name."""348+ referenced = []349+ buf = []350+ while 1:351+ if parser.stream.current.type == "data":352+ buf.append(parser.stream.current.value.replace("%", "%%"))353+ next(parser.stream)354+ elif parser.stream.current.type == "variable_begin":355+ next(parser.stream)356+ name = parser.stream.expect("name").value357+ referenced.append(name)358+ buf.append("%%(%s)s" % name)359+ parser.stream.expect("variable_end")360+ elif parser.stream.current.type == "block_begin":361+ next(parser.stream)362+ if parser.stream.current.test("name:endtrans"):363+ break364+ elif parser.stream.current.test("name:pluralize"):365+ if allow_pluralize:366+ break367+ parser.fail(368+ "a translatable section can have only one pluralize section"369+ )370+ parser.fail(371+ "control structures in translatable sections are not allowed"372+ )373+ elif parser.stream.eos:374+ parser.fail("unclosed translation block")375+ else:376+ raise RuntimeError("internal parser error")377+378+ return referenced, concat(buf)379+380+ def _make_node(381+ self, singular, plural, variables, plural_expr, vars_referenced, num_called_num382+ ):383+ """Generates a useful node from the data provided."""384+ # no variables referenced? no need to escape for old style385+ # gettext invocations only if there are vars.386+ if not vars_referenced and not self.environment.newstyle_gettext:387+ singular = singular.replace("%%", "%")388+ if plural:389+ plural = plural.replace("%%", "%")390+391+ # singular only:392+ if plural_expr is None:393+ gettext = nodes.Name("gettext", "load")394+ node = nodes.Call(gettext, [nodes.Const(singular)], [], None, None)395+396+ # singular and plural397+ else:398+ ngettext = nodes.Name("ngettext", "load")399+ node = nodes.Call(400+ ngettext,401+ [nodes.Const(singular), nodes.Const(plural), plural_expr],402+ [],403+ None,404+ None,405+ )406+407+ # in case newstyle gettext is used, the method is powerful408+ # enough to handle the variable expansion and autoescape409+ # handling itself410+ if self.environment.newstyle_gettext:411+ for key, value in iteritems(variables):412+ # the function adds that later anyways in case num was413+ # called num, so just skip it.414+ if num_called_num and key == "num":415+ continue416+ node.kwargs.append(nodes.Keyword(key, value))417+418+ # otherwise do that here419+ else:420+ # mark the return value as safe if we are in an421+ # environment with autoescaping turned on422+ node = nodes.MarkSafeIfAutoescape(node)423+ if variables:424+ node = nodes.Mod(425+ node,426+ nodes.Dict(427+ [428+ nodes.Pair(nodes.Const(key), value)429+ for key, value in variables.items()430+ ]431+ ),432+ )433+ return nodes.Output([node])434+435+436+class ExprStmtExtension(Extension):437+ """Adds a `do` tag to Jinja that works like the print statement just438+ that it doesn't print the return value.439+ """440+441+ tags = set(["do"])442+443+ def parse(self, parser):444+ node = nodes.ExprStmt(lineno=next(parser.stream).lineno)445+ node.node = parser.parse_tuple()446+ return node447+448+449+class LoopControlExtension(Extension):450+ """Adds break and continue to the template engine."""451+452+ tags = set(["break", "continue"])453+454+ def parse(self, parser):455+ token = next(parser.stream)456+ if token.value == "break":457+ return nodes.Break(lineno=token.lineno)458+ return nodes.Continue(lineno=token.lineno)459+460+461+class WithExtension(Extension):462+ pass463+464+465+class AutoEscapeExtension(Extension):466+ pass467+468+469+class DebugExtension(Extension):470+ """A ``{% debug %}`` tag that dumps the available variables,471+ filters, and tests.472+473+ .. code-block:: html+jinja474+475+ <pre>{% debug %}</pre>476+477+ .. code-block:: text478+479+ {'context': {'cycler': <class 'jinja2.utils.Cycler'>,480+ ...,481+ 'namespace': <class 'jinja2.utils.Namespace'>},482+ 'filters': ['abs', 'attr', 'batch', 'capitalize', 'center', 'count', 'd',483+ ..., 'urlencode', 'urlize', 'wordcount', 'wordwrap', 'xmlattr'],484+ 'tests': ['!=', '<', '<=', '==', '>', '>=', 'callable', 'defined',485+ ..., 'odd', 'sameas', 'sequence', 'string', 'undefined', 'upper']}486+487+ .. versionadded:: 2.11.0488+ """489+490+ tags = {"debug"}491+492+ def parse(self, parser):493+ lineno = parser.stream.expect("name:debug").lineno494+ context = ContextReference()495+ result = self.call_method("_render", [context], lineno=lineno)496+ return nodes.Output([result], lineno=lineno)497+498+ def _render(self, context):499+ result = {500+ "context": context.get_all(),501+ "filters": sorted(self.environment.filters.keys()),502+ "tests": sorted(self.environment.tests.keys()),503+ }504+505+ # Set the depth since the intent is to show the top few names.506+ if version_info[:2] >= (3, 4):507+ return pprint.pformat(result, depth=3, compact=True)508+ else:509+ return pprint.pformat(result, depth=3)510+511+512+def extract_from_ast(node, gettext_functions=GETTEXT_FUNCTIONS, babel_style=True):513+ """Extract localizable strings from the given template node. Per514+ default this function returns matches in babel style that means non string515+ parameters as well as keyword arguments are returned as `None`. This516+ allows Babel to figure out what you really meant if you are using517+ gettext functions that allow keyword arguments for placeholder expansion.518+ If you don't want that behavior set the `babel_style` parameter to `False`519+ which causes only strings to be returned and parameters are always stored520+ in tuples. As a consequence invalid gettext calls (calls without a single521+ string parameter or string parameters after non-string parameters) are522+ skipped.523+524+ This example explains the behavior:525+526+ >>> from jinja2 import Environment527+ >>> env = Environment()528+ >>> node = env.parse('{{ (_("foo"), _(), ngettext("foo", "bar", 42)) }}')529+ >>> list(extract_from_ast(node))530+ [(1, '_', 'foo'), (1, '_', ()), (1, 'ngettext', ('foo', 'bar', None))]531+ >>> list(extract_from_ast(node, babel_style=False))532+ [(1, '_', ('foo',)), (1, 'ngettext', ('foo', 'bar'))]533+534+ For every string found this function yields a ``(lineno, function,535+ message)`` tuple, where:536+537+ * ``lineno`` is the number of the line on which the string was found,538+ * ``function`` is the name of the ``gettext`` function used (if the539+ string was extracted from embedded Python code), and540+ * ``message`` is the string itself (a ``unicode`` object, or a tuple541+ of ``unicode`` objects for functions with multiple string arguments).542+543+ This extraction function operates on the AST and is because of that unable544+ to extract any comments. For comment support you have to use the babel545+ extraction interface or extract comments yourself.546+ """547+ for node in node.find_all(nodes.Call):548+ if (549+ not isinstance(node.node, nodes.Name)550+ or node.node.name not in gettext_functions551+ ):552+ continue553+554+ strings = []555+ for arg in node.args:556+ if isinstance(arg, nodes.Const) and isinstance(arg.value, string_types):557+ strings.append(arg.value)558+ else:559+ strings.append(None)560+561+ for _ in node.kwargs:562+ strings.append(None)563+ if node.dyn_args is not None:564+ strings.append(None)565+ if node.dyn_kwargs is not None:566+ strings.append(None)567+568+ if not babel_style:569+ strings = tuple(x for x in strings if x is not None)570+ if not strings:571+ continue572+ else:573+ if len(strings) == 1:574+ strings = strings[0]575+ else:576+ strings = tuple(strings)577+ yield node.lineno, node.node.name, strings578+579+580+class _CommentFinder(object):581+ """Helper class to find comments in a token stream. Can only582+ find comments for gettext calls forwards. Once the comment583+ from line 4 is found, a comment for line 1 will not return a584+ usable value.585+ """586+587+ def __init__(self, tokens, comment_tags):588+ self.tokens = tokens589+ self.comment_tags = comment_tags590+ self.offset = 0591+ self.last_lineno = 0592+593+ def find_backwards(self, offset):594+ try:595+ for _, token_type, token_value in reversed(596+ self.tokens[self.offset : offset]597+ ):598+ if token_type in ("comment", "linecomment"):599+ try:600+ prefix, comment = token_value.split(None, 1)601+ except ValueError:602+ continue603+ if prefix in self.comment_tags:604+ return [comment.rstrip()]605+ return []606+ finally:607+ self.offset = offset608+609+ def find_comments(self, lineno):610+ if not self.comment_tags or self.last_lineno > lineno:611+ return []612+ for idx, (token_lineno, _, _) in enumerate(self.tokens[self.offset :]):613+ if token_lineno > lineno:614+ return self.find_backwards(self.offset + idx)615+ return self.find_backwards(len(self.tokens))616+617+618+def babel_extract(fileobj, keywords, comment_tags, options):619+ """Babel extraction method for Jinja templates.620+621+ .. versionchanged:: 2.3622+ Basic support for translation comments was added. If `comment_tags`623+ is now set to a list of keywords for extraction, the extractor will624+ try to find the best preceding comment that begins with one of the625+ keywords. For best results, make sure to not have more than one626+ gettext call in one line of code and the matching comment in the627+ same line or the line before.628+629+ .. versionchanged:: 2.5.1630+ The `newstyle_gettext` flag can be set to `True` to enable newstyle631+ gettext calls.632+633+ .. versionchanged:: 2.7634+ A `silent` option can now be provided. If set to `False` template635+ syntax errors are propagated instead of being ignored.636+637+ :param fileobj: the file-like object the messages should be extracted from638+ :param keywords: a list of keywords (i.e. function names) that should be639+ recognized as translation functions640+ :param comment_tags: a list of translator tags to search for and include641+ in the results.642+ :param options: a dictionary of additional options (optional)643+ :return: an iterator over ``(lineno, funcname, message, comments)`` tuples.644+ (comments will be empty currently)645+ """646+ extensions = set()647+ for extension in options.get("extensions", "").split(","):648+ extension = extension.strip()649+ if not extension:650+ continue651+ extensions.add(import_string(extension))652+ if InternationalizationExtension not in extensions:653+ extensions.add(InternationalizationExtension)654+655+ def getbool(options, key, default=False):656+ return options.get(key, str(default)).lower() in ("1", "on", "yes", "true")657+658+ silent = getbool(options, "silent", True)659+ environment = Environment(660+ options.get("block_start_string", BLOCK_START_STRING),661+ options.get("block_end_string", BLOCK_END_STRING),662+ options.get("variable_start_string", VARIABLE_START_STRING),663+ options.get("variable_end_string", VARIABLE_END_STRING),664+ options.get("comment_start_string", COMMENT_START_STRING),665+ options.get("comment_end_string", COMMENT_END_STRING),666+ options.get("line_statement_prefix") or LINE_STATEMENT_PREFIX,667+ options.get("line_comment_prefix") or LINE_COMMENT_PREFIX,668+ getbool(options, "trim_blocks", TRIM_BLOCKS),669+ getbool(options, "lstrip_blocks", LSTRIP_BLOCKS),670+ NEWLINE_SEQUENCE,671+ getbool(options, "keep_trailing_newline", KEEP_TRAILING_NEWLINE),672+ frozenset(extensions),673+ cache_size=0,674+ auto_reload=False,675+ )676+677+ if getbool(options, "trimmed"):678+ environment.policies["ext.i18n.trimmed"] = True679+ if getbool(options, "newstyle_gettext"):680+ environment.newstyle_gettext = True681+682+ source = fileobj.read().decode(options.get("encoding", "utf-8"))683+ try:684+ node = environment.parse(source)685+ tokens = list(environment.lex(environment.preprocess(source)))686+ except TemplateSyntaxError:687+ if not silent:688+ raise689+ # skip templates with syntax errors690+ return691+692+ finder = _CommentFinder(tokens, comment_tags)693+ for lineno, func, message in extract_from_ast(node, keywords):694+ yield lineno, func, message, finder.find_comments(lineno)695+696+697+#: nicer import names698+i18n = InternationalizationExtension699+do = ExprStmtExtension700+loopcontrols = LoopControlExtension701+with_ = WithExtension702+autoescape = AutoEscapeExtension703+debug = DebugExtensionadded:src/jinja2/filters.py+1382 added
1+# -*- coding: utf-8 -*-2+"""Built-in template filters used with the ``|`` operator."""3+import math4+import random5+import re6+import warnings7+from collections import namedtuple8+from itertools import chain9+from itertools import groupby10+11+from markupsafe import escape12+from markupsafe import Markup13+from markupsafe import soft_unicode14+15+from ._compat import abc16+from ._compat import imap17+from ._compat import iteritems18+from ._compat import string_types19+from ._compat import text_type20+from .exceptions import FilterArgumentError21+from .runtime import Undefined22+from .utils import htmlsafe_json_dumps23+from .utils import pformat24+from .utils import unicode_urlencode25+from .utils import urlize26+27+_word_re = re.compile(r"\w+", re.UNICODE)28+_word_beginning_split_re = re.compile(r"([-\s\(\{\[\<]+)", re.UNICODE)29+30+31+def contextfilter(f):32+ """Decorator for marking context dependent filters. The current33+ :class:`Context` will be passed as first argument.34+ """35+ f.contextfilter = True36+ return f37+38+39+def evalcontextfilter(f):40+ """Decorator for marking eval-context dependent filters. An eval41+ context object is passed as first argument. For more information42+ about the eval context, see :ref:`eval-context`.43+44+ .. versionadded:: 2.445+ """46+ f.evalcontextfilter = True47+ return f48+49+50+def environmentfilter(f):51+ """Decorator for marking environment dependent filters. The current52+ :class:`Environment` is passed to the filter as first argument.53+ """54+ f.environmentfilter = True55+ return f56+57+58+def ignore_case(value):59+ """For use as a postprocessor for :func:`make_attrgetter`. Converts strings60+ to lowercase and returns other types as-is."""61+ return value.lower() if isinstance(value, string_types) else value62+63+64+def make_attrgetter(environment, attribute, postprocess=None, default=None):65+ """Returns a callable that looks up the given attribute from a66+ passed object with the rules of the environment. Dots are allowed67+ to access attributes of attributes. Integer parts in paths are68+ looked up as integers.69+ """70+ attribute = _prepare_attribute_parts(attribute)71+72+ def attrgetter(item):73+ for part in attribute:74+ item = environment.getitem(item, part)75+76+ if default and isinstance(item, Undefined):77+ item = default78+79+ if postprocess is not None:80+ item = postprocess(item)81+82+ return item83+84+ return attrgetter85+86+87+def make_multi_attrgetter(environment, attribute, postprocess=None):88+ """Returns a callable that looks up the given comma separated89+ attributes from a passed object with the rules of the environment.90+ Dots are allowed to access attributes of each attribute. Integer91+ parts in paths are looked up as integers.92+93+ The value returned by the returned callable is a list of extracted94+ attribute values.95+96+ Examples of attribute: "attr1,attr2", "attr1.inner1.0,attr2.inner2.0", etc.97+ """98+ attribute_parts = (99+ attribute.split(",") if isinstance(attribute, string_types) else [attribute]100+ )101+ attribute = [102+ _prepare_attribute_parts(attribute_part) for attribute_part in attribute_parts103+ ]104+105+ def attrgetter(item):106+ items = [None] * len(attribute)107+ for i, attribute_part in enumerate(attribute):108+ item_i = item109+ for part in attribute_part:110+ item_i = environment.getitem(item_i, part)111+112+ if postprocess is not None:113+ item_i = postprocess(item_i)114+115+ items[i] = item_i116+ return items117+118+ return attrgetter119+120+121+def _prepare_attribute_parts(attr):122+ if attr is None:123+ return []124+ elif isinstance(attr, string_types):125+ return [int(x) if x.isdigit() else x for x in attr.split(".")]126+ else:127+ return [attr]128+129+130+def do_forceescape(value):131+ """Enforce HTML escaping. This will probably double escape variables."""132+ if hasattr(value, "__html__"):133+ value = value.__html__()134+ return escape(text_type(value))135+136+137+def do_urlencode(value):138+ """Quote data for use in a URL path or query using UTF-8.139+140+ Basic wrapper around :func:`urllib.parse.quote` when given a141+ string, or :func:`urllib.parse.urlencode` for a dict or iterable.142+143+ :param value: Data to quote. A string will be quoted directly. A144+ dict or iterable of ``(key, value)`` pairs will be joined as a145+ query string.146+147+ When given a string, "/" is not quoted. HTTP servers treat "/" and148+ "%2F" equivalently in paths. If you need quoted slashes, use the149+ ``|replace("/", "%2F")`` filter.150+151+ .. versionadded:: 2.7152+ """153+ if isinstance(value, string_types) or not isinstance(value, abc.Iterable):154+ return unicode_urlencode(value)155+156+ if isinstance(value, dict):157+ items = iteritems(value)158+ else:159+ items = iter(value)160+161+ return u"&".join(162+ "%s=%s" % (unicode_urlencode(k, for_qs=True), unicode_urlencode(v, for_qs=True))163+ for k, v in items164+ )165+166+167+@evalcontextfilter168+def do_replace(eval_ctx, s, old, new, count=None):169+ """Return a copy of the value with all occurrences of a substring170+ replaced with a new one. The first argument is the substring171+ that should be replaced, the second is the replacement string.172+ If the optional third argument ``count`` is given, only the first173+ ``count`` occurrences are replaced:174+175+ .. sourcecode:: jinja176+177+ {{ "Hello World"|replace("Hello", "Goodbye") }}178+ -> Goodbye World179+180+ {{ "aaaaargh"|replace("a", "d'oh, ", 2) }}181+ -> d'oh, d'oh, aaargh182+ """183+ if count is None:184+ count = -1185+ if not eval_ctx.autoescape:186+ return text_type(s).replace(text_type(old), text_type(new), count)187+ if (188+ hasattr(old, "__html__")189+ or hasattr(new, "__html__")190+ and not hasattr(s, "__html__")191+ ):192+ s = escape(s)193+ else:194+ s = soft_unicode(s)195+ return s.replace(soft_unicode(old), soft_unicode(new), count)196+197+198+def do_upper(s):199+ """Convert a value to uppercase."""200+ return soft_unicode(s).upper()201+202+203+def do_lower(s):204+ """Convert a value to lowercase."""205+ return soft_unicode(s).lower()206+207+208+@evalcontextfilter209+def do_xmlattr(_eval_ctx, d, autospace=True):210+ """Create an SGML/XML attribute string based on the items in a dict.211+ All values that are neither `none` nor `undefined` are automatically212+ escaped:213+214+ .. sourcecode:: html+jinja215+216+ <ul{{ {'class': 'my_list', 'missing': none,217+ 'id': 'list-%d'|format(variable)}|xmlattr }}>218+ ...219+ </ul>220+221+ Results in something like this:222+223+ .. sourcecode:: html224+225+ <ul class="my_list" id="list-42">226+ ...227+ </ul>228+229+ As you can see it automatically prepends a space in front of the item230+ if the filter returned something unless the second parameter is false.231+ """232+ rv = u" ".join(233+ u'%s="%s"' % (escape(key), escape(value))234+ for key, value in iteritems(d)235+ if value is not None and not isinstance(value, Undefined)236+ )237+ if autospace and rv:238+ rv = u" " + rv239+ if _eval_ctx.autoescape:240+ rv = Markup(rv)241+ return rv242+243+244+def do_capitalize(s):245+ """Capitalize a value. The first character will be uppercase, all others246+ lowercase.247+ """248+ return soft_unicode(s).capitalize()249+250+251+def do_title(s):252+ """Return a titlecased version of the value. I.e. words will start with253+ uppercase letters, all remaining characters are lowercase.254+ """255+ return "".join(256+ [257+ item[0].upper() + item[1:].lower()258+ for item in _word_beginning_split_re.split(soft_unicode(s))259+ if item260+ ]261+ )262+263+264+def do_dictsort(value, case_sensitive=False, by="key", reverse=False):265+ """Sort a dict and yield (key, value) pairs. Because python dicts are266+ unsorted you may want to use this function to order them by either267+ key or value:268+269+ .. sourcecode:: jinja270+271+ {% for item in mydict|dictsort %}272+ sort the dict by key, case insensitive273+274+ {% for item in mydict|dictsort(reverse=true) %}275+ sort the dict by key, case insensitive, reverse order276+277+ {% for item in mydict|dictsort(true) %}278+ sort the dict by key, case sensitive279+280+ {% for item in mydict|dictsort(false, 'value') %}281+ sort the dict by value, case insensitive282+ """283+ if by == "key":284+ pos = 0285+ elif by == "value":286+ pos = 1287+ else:288+ raise FilterArgumentError('You can only sort by either "key" or "value"')289+290+ def sort_func(item):291+ value = item[pos]292+293+ if not case_sensitive:294+ value = ignore_case(value)295+296+ return value297+298+ return sorted(value.items(), key=sort_func, reverse=reverse)299+300+301+@environmentfilter302+def do_sort(environment, value, reverse=False, case_sensitive=False, attribute=None):303+ """Sort an iterable using Python's :func:`sorted`.304+305+ .. sourcecode:: jinja306+307+ {% for city in cities|sort %}308+ ...309+ {% endfor %}310+311+ :param reverse: Sort descending instead of ascending.312+ :param case_sensitive: When sorting strings, sort upper and lower313+ case separately.314+ :param attribute: When sorting objects or dicts, an attribute or315+ key to sort by. Can use dot notation like ``"address.city"``.316+ Can be a list of attributes like ``"age,name"``.317+318+ The sort is stable, it does not change the relative order of319+ elements that compare equal. This makes it is possible to chain320+ sorts on different attributes and ordering.321+322+ .. sourcecode:: jinja323+324+ {% for user in users|sort(attribute="name")325+ |sort(reverse=true, attribute="age") %}326+ ...327+ {% endfor %}328+329+ As a shortcut to chaining when the direction is the same for all330+ attributes, pass a comma separate list of attributes.331+332+ .. sourcecode:: jinja333+334+ {% for user users|sort(attribute="age,name") %}335+ ...336+ {% endfor %}337+338+ .. versionchanged:: 2.11.0339+ The ``attribute`` parameter can be a comma separated list of340+ attributes, e.g. ``"age,name"``.341+342+ .. versionchanged:: 2.6343+ The ``attribute`` parameter was added.344+ """345+ key_func = make_multi_attrgetter(346+ environment, attribute, postprocess=ignore_case if not case_sensitive else None347+ )348+ return sorted(value, key=key_func, reverse=reverse)349+350+351+@environmentfilter352+def do_unique(environment, value, case_sensitive=False, attribute=None):353+ """Returns a list of unique items from the given iterable.354+355+ .. sourcecode:: jinja356+357+ {{ ['foo', 'bar', 'foobar', 'FooBar']|unique|list }}358+ -> ['foo', 'bar', 'foobar']359+360+ The unique items are yielded in the same order as their first occurrence in361+ the iterable passed to the filter.362+363+ :param case_sensitive: Treat upper and lower case strings as distinct.364+ :param attribute: Filter objects with unique values for this attribute.365+ """366+ getter = make_attrgetter(367+ environment, attribute, postprocess=ignore_case if not case_sensitive else None368+ )369+ seen = set()370+371+ for item in value:372+ key = getter(item)373+374+ if key not in seen:375+ seen.add(key)376+ yield item377+378+379+def _min_or_max(environment, value, func, case_sensitive, attribute):380+ it = iter(value)381+382+ try:383+ first = next(it)384+ except StopIteration:385+ return environment.undefined("No aggregated item, sequence was empty.")386+387+ key_func = make_attrgetter(388+ environment, attribute, postprocess=ignore_case if not case_sensitive else None389+ )390+ return func(chain([first], it), key=key_func)391+392+393+@environmentfilter394+def do_min(environment, value, case_sensitive=False, attribute=None):395+ """Return the smallest item from the sequence.396+397+ .. sourcecode:: jinja398+399+ {{ [1, 2, 3]|min }}400+ -> 1401+402+ :param case_sensitive: Treat upper and lower case strings as distinct.403+ :param attribute: Get the object with the min value of this attribute.404+ """405+ return _min_or_max(environment, value, min, case_sensitive, attribute)406+407+408+@environmentfilter409+def do_max(environment, value, case_sensitive=False, attribute=None):410+ """Return the largest item from the sequence.411+412+ .. sourcecode:: jinja413+414+ {{ [1, 2, 3]|max }}415+ -> 3416+417+ :param case_sensitive: Treat upper and lower case strings as distinct.418+ :param attribute: Get the object with the max value of this attribute.419+ """420+ return _min_or_max(environment, value, max, case_sensitive, attribute)421+422+423+def do_default(value, default_value=u"", boolean=False):424+ """If the value is undefined it will return the passed default value,425+ otherwise the value of the variable:426+427+ .. sourcecode:: jinja428+429+ {{ my_variable|default('my_variable is not defined') }}430+431+ This will output the value of ``my_variable`` if the variable was432+ defined, otherwise ``'my_variable is not defined'``. If you want433+ to use default with variables that evaluate to false you have to434+ set the second parameter to `true`:435+436+ .. sourcecode:: jinja437+438+ {{ ''|default('the string was empty', true) }}439+440+ .. versionchanged:: 2.11441+ It's now possible to configure the :class:`~jinja2.Environment` with442+ :class:`~jinja2.ChainableUndefined` to make the `default` filter work443+ on nested elements and attributes that may contain undefined values444+ in the chain without getting an :exc:`~jinja2.UndefinedError`.445+ """446+ if isinstance(value, Undefined) or (boolean and not value):447+ return default_value448+ return value449+450+451+@evalcontextfilter452+def do_join(eval_ctx, value, d=u"", attribute=None):453+ """Return a string which is the concatenation of the strings in the454+ sequence. The separator between elements is an empty string per455+ default, you can define it with the optional parameter:456+457+ .. sourcecode:: jinja458+459+ {{ [1, 2, 3]|join('|') }}460+ -> 1|2|3461+462+ {{ [1, 2, 3]|join }}463+ -> 123464+465+ It is also possible to join certain attributes of an object:466+467+ .. sourcecode:: jinja468+469+ {{ users|join(', ', attribute='username') }}470+471+ .. versionadded:: 2.6472+ The `attribute` parameter was added.473+ """474+ if attribute is not None:475+ value = imap(make_attrgetter(eval_ctx.environment, attribute), value)476+477+ # no automatic escaping? joining is a lot easier then478+ if not eval_ctx.autoescape:479+ return text_type(d).join(imap(text_type, value))480+481+ # if the delimiter doesn't have an html representation we check482+ # if any of the items has. If yes we do a coercion to Markup483+ if not hasattr(d, "__html__"):484+ value = list(value)485+ do_escape = False486+ for idx, item in enumerate(value):487+ if hasattr(item, "__html__"):488+ do_escape = True489+ else:490+ value[idx] = text_type(item)491+ if do_escape:492+ d = escape(d)493+ else:494+ d = text_type(d)495+ return d.join(value)496+497+ # no html involved, to normal joining498+ return soft_unicode(d).join(imap(soft_unicode, value))499+500+501+def do_center(value, width=80):502+ """Centers the value in a field of a given width."""503+ return text_type(value).center(width)504+505+506+@environmentfilter507+def do_first(environment, seq):508+ """Return the first item of a sequence."""509+ try:510+ return next(iter(seq))511+ except StopIteration:512+ return environment.undefined("No first item, sequence was empty.")513+514+515+@environmentfilter516+def do_last(environment, seq):517+ """518+ Return the last item of a sequence.519+520+ Note: Does not work with generators. You may want to explicitly521+ convert it to a list:522+523+ .. sourcecode:: jinja524+525+ {{ data | selectattr('name', '==', 'Jinja') | list | last }}526+ """527+ try:528+ return next(iter(reversed(seq)))529+ except StopIteration:530+ return environment.undefined("No last item, sequence was empty.")531+532+533+@contextfilter534+def do_random(context, seq):535+ """Return a random item from the sequence."""536+ try:537+ return random.choice(seq)538+ except IndexError:539+ return context.environment.undefined("No random item, sequence was empty.")540+541+542+def do_filesizeformat(value, binary=False):543+ """Format the value like a 'human-readable' file size (i.e. 13 kB,544+ 4.1 MB, 102 Bytes, etc). Per default decimal prefixes are used (Mega,545+ Giga, etc.), if the second parameter is set to `True` the binary546+ prefixes are used (Mebi, Gibi).547+ """548+ bytes = float(value)549+ base = binary and 1024 or 1000550+ prefixes = [551+ (binary and "KiB" or "kB"),552+ (binary and "MiB" or "MB"),553+ (binary and "GiB" or "GB"),554+ (binary and "TiB" or "TB"),555+ (binary and "PiB" or "PB"),556+ (binary and "EiB" or "EB"),557+ (binary and "ZiB" or "ZB"),558+ (binary and "YiB" or "YB"),559+ ]560+ if bytes == 1:561+ return "1 Byte"562+ elif bytes < base:563+ return "%d Bytes" % bytes564+ else:565+ for i, prefix in enumerate(prefixes):566+ unit = base ** (i + 2)567+ if bytes < unit:568+ return "%.1f %s" % ((base * bytes / unit), prefix)569+ return "%.1f %s" % ((base * bytes / unit), prefix)570+571+572+def do_pprint(value, verbose=False):573+ """Pretty print a variable. Useful for debugging.574+575+ 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)579+580+581+@evalcontextfilter582+def do_urlize(583+ eval_ctx, value, trim_url_limit=None, nofollow=False, target=None, rel=None584+):585+ """Converts URLs in plain text into clickable links.586+587+ If you pass the filter an additional integer it will shorten the urls588+ to that number. Also a third argument exists that makes the urls589+ "nofollow":590+591+ .. sourcecode:: jinja592+593+ {{ mytext|urlize(40, true) }}594+ links are shortened to 40 chars and defined with rel="nofollow"595+596+ If *target* is specified, the ``target`` attribute will be added to the597+ ``<a>`` tag:598+599+ .. sourcecode:: jinja600+601+ {{ mytext|urlize(40, target='_blank') }}602+603+ .. versionchanged:: 2.8+604+ The *target* parameter was added.605+ """606+ policies = eval_ctx.environment.policies607+ rel = set((rel or "").split() or [])608+ if nofollow:609+ rel.add("nofollow")610+ rel.update((policies["urlize.rel"] or "").split())611+ if target is None:612+ target = policies["urlize.target"]613+ rel = " ".join(sorted(rel)) or None614+ rv = urlize(value, trim_url_limit, rel=rel, target=target)615+ if eval_ctx.autoescape:616+ rv = Markup(rv)617+ return rv618+619+620+def do_indent(s, width=4, first=False, blank=False, indentfirst=None):621+ """Return a copy of the string with each line indented by 4 spaces. The622+ first line and blank lines are not indented by default.623+624+ :param width: Number of spaces to indent by.625+ :param first: Don't skip indenting the first line.626+ :param blank: Don't skip indenting empty lines.627+628+ .. versionchanged:: 2.10629+ Blank lines are not indented by default.630+631+ Rename the ``indentfirst`` argument to ``first``.632+ """633+ if indentfirst is not None:634+ warnings.warn(635+ "The 'indentfirst' argument is renamed to 'first' and will"636+ " be removed in version 3.0.",637+ DeprecationWarning,638+ stacklevel=2,639+ )640+ first = indentfirst641+642+ indention = u" " * width643+ newline = u"\n"644+645+ if isinstance(s, Markup):646+ indention = Markup(indention)647+ newline = Markup(newline)648+649+ s += newline # this quirk is necessary for splitlines method650+651+ if blank:652+ rv = (newline + indention).join(s.splitlines())653+ else:654+ lines = s.splitlines()655+ rv = lines.pop(0)656+657+ if lines:658+ rv += newline + newline.join(659+ indention + line if line else line for line in lines660+ )661+662+ if first:663+ rv = indention + rv664+665+ return rv666+667+668+@environmentfilter669+def do_truncate(env, s, length=255, killwords=False, end="...", leeway=None):670+ """Return a truncated copy of the string. The length is specified671+ with the first parameter which defaults to ``255``. If the second672+ parameter is ``true`` the filter will cut the text at length. Otherwise673+ it will discard the last word. If the text was in fact674+ truncated it will append an ellipsis sign (``"..."``). If you want a675+ different ellipsis sign than ``"..."`` you can specify it using the676+ third parameter. Strings that only exceed the length by the tolerance677+ margin given in the fourth parameter will not be truncated.678+679+ .. sourcecode:: jinja680+681+ {{ "foo bar baz qux"|truncate(9) }}682+ -> "foo..."683+ {{ "foo bar baz qux"|truncate(9, True) }}684+ -> "foo ba..."685+ {{ "foo bar baz qux"|truncate(11) }}686+ -> "foo bar baz qux"687+ {{ "foo bar baz qux"|truncate(11, False, '...', 0) }}688+ -> "foo bar..."689+690+ The default leeway on newer Jinja versions is 5 and was 0 before but691+ can be reconfigured globally.692+ """693+ if leeway is None:694+ leeway = env.policies["truncate.leeway"]695+ assert length >= len(end), "expected length >= %s, got %s" % (len(end), length)696+ assert leeway >= 0, "expected leeway >= 0, got %s" % leeway697+ if len(s) <= length + leeway:698+ return s699+ if killwords:700+ return s[: length - len(end)] + end701+ result = s[: length - len(end)].rsplit(" ", 1)[0]702+ return result + end703+704+705+@environmentfilter706+def do_wordwrap(707+ environment,708+ s,709+ width=79,710+ break_long_words=True,711+ wrapstring=None,712+ break_on_hyphens=True,713+):714+ """Wrap a string to the given width. Existing newlines are treated715+ as paragraphs to be wrapped separately.716+717+ :param s: Original text to wrap.718+ :param width: Maximum length of wrapped lines.719+ :param break_long_words: If a word is longer than ``width``, break720+ it across lines.721+ :param break_on_hyphens: If a word contains hyphens, it may be split722+ across lines.723+ :param wrapstring: String to join each wrapped line. Defaults to724+ :attr:`Environment.newline_sequence`.725+726+ .. versionchanged:: 2.11727+ Existing newlines are treated as paragraphs wrapped separately.728+729+ .. versionchanged:: 2.11730+ Added the ``break_on_hyphens`` parameter.731+732+ .. versionchanged:: 2.7733+ Added the ``wrapstring`` parameter.734+ """735+736+ import textwrap737+738+ if not wrapstring:739+ wrapstring = environment.newline_sequence740+741+ # textwrap.wrap doesn't consider existing newlines when wrapping.742+ # If the string has a newline before width, wrap will still insert743+ # a newline at width, resulting in a short line. Instead, split and744+ # wrap each paragraph individually.745+ return wrapstring.join(746+ [747+ wrapstring.join(748+ textwrap.wrap(749+ line,750+ width=width,751+ expand_tabs=False,752+ replace_whitespace=False,753+ break_long_words=break_long_words,754+ break_on_hyphens=break_on_hyphens,755+ )756+ )757+ for line in s.splitlines()758+ ]759+ )760+761+762+def do_wordcount(s):763+ """Count the words in that string."""764+ return len(_word_re.findall(s))765+766+767+def do_int(value, default=0, base=10):768+ """Convert the value into an integer. If the769+ conversion doesn't work it will return ``0``. You can770+ override this default using the first parameter. You771+ can also override the default base (10) in the second772+ parameter, which handles input with prefixes such as773+ 0b, 0o and 0x for bases 2, 8 and 16 respectively.774+ The base is ignored for decimal numbers and non-string values.775+ """776+ try:777+ if isinstance(value, string_types):778+ return int(value, base)779+ return int(value)780+ except (TypeError, ValueError):781+ # this quirk is necessary so that "42.23"|int gives 42.782+ try:783+ return int(float(value))784+ except (TypeError, ValueError):785+ return default786+787+788+def do_float(value, default=0.0):789+ """Convert the value into a floating point number. If the790+ conversion doesn't work it will return ``0.0``. You can791+ override this default using the first parameter.792+ """793+ try:794+ return float(value)795+ except (TypeError, ValueError):796+ return default797+798+799+def do_format(value, *args, **kwargs):800+ """Apply the given values to a `printf-style`_ format string, like801+ ``string % values``.802+803+ .. sourcecode:: jinja804+805+ {{ "%s, %s!"|format(greeting, name) }}806+ Hello, World!807+808+ In most cases it should be more convenient and efficient to use the809+ ``%`` operator or :meth:`str.format`.810+811+ .. code-block:: text812+813+ {{ "%s, %s!" % (greeting, name) }}814+ {{ "{}, {}!".format(greeting, name) }}815+816+ .. _printf-style: https://docs.python.org/library/stdtypes.html817+ #printf-style-string-formatting818+ """819+ if args and kwargs:820+ raise FilterArgumentError(821+ "can't handle positional and keyword arguments at the same time"822+ )823+ return soft_unicode(value) % (kwargs or args)824+825+826+def do_trim(value, chars=None):827+ """Strip leading and trailing characters, by default whitespace."""828+ return soft_unicode(value).strip(chars)829+830+831+def do_striptags(value):832+ """Strip SGML/XML tags and replace adjacent whitespace by one space."""833+ if hasattr(value, "__html__"):834+ value = value.__html__()835+ return Markup(text_type(value)).striptags()836+837+838+def do_slice(value, slices, fill_with=None):839+ """Slice an iterator and return a list of lists containing840+ those items. Useful if you want to create a div containing841+ three ul tags that represent columns:842+843+ .. sourcecode:: html+jinja844+845+ <div class="columnwrapper">846+ {%- for column in items|slice(3) %}847+ <ul class="column-{{ loop.index }}">848+ {%- for item in column %}849+ <li>{{ item }}</li>850+ {%- endfor %}851+ </ul>852+ {%- endfor %}853+ </div>854+855+ If you pass it a second argument it's used to fill missing856+ values on the last iteration.857+ """858+ seq = list(value)859+ length = len(seq)860+ items_per_slice = length // slices861+ slices_with_extra = length % slices862+ offset = 0863+ for slice_number in range(slices):864+ start = offset + slice_number * items_per_slice865+ if slice_number < slices_with_extra:866+ offset += 1867+ end = offset + (slice_number + 1) * items_per_slice868+ tmp = seq[start:end]869+ if fill_with is not None and slice_number >= slices_with_extra:870+ tmp.append(fill_with)871+ yield tmp872+873+874+def do_batch(value, linecount, fill_with=None):875+ """876+ A filter that batches items. It works pretty much like `slice`877+ just the other way round. It returns a list of lists with the878+ given number of items. If you provide a second parameter this879+ is used to fill up missing items. See this example:880+881+ .. sourcecode:: html+jinja882+883+ <table>884+ {%- for row in items|batch(3, ' ') %}885+ <tr>886+ {%- for column in row %}887+ <td>{{ column }}</td>888+ {%- endfor %}889+ </tr>890+ {%- endfor %}891+ </table>892+ """893+ tmp = []894+ for item in value:895+ if len(tmp) == linecount:896+ yield tmp897+ tmp = []898+ tmp.append(item)899+ if tmp:900+ if fill_with is not None and len(tmp) < linecount:901+ tmp += [fill_with] * (linecount - len(tmp))902+ yield tmp903+904+905+def do_round(value, precision=0, method="common"):906+ """Round the number to a given precision. The first907+ parameter specifies the precision (default is ``0``), the908+ second the rounding method:909+910+ - ``'common'`` rounds either up or down911+ - ``'ceil'`` always rounds up912+ - ``'floor'`` always rounds down913+914+ If you don't specify a method ``'common'`` is used.915+916+ .. sourcecode:: jinja917+918+ {{ 42.55|round }}919+ -> 43.0920+ {{ 42.55|round(1, 'floor') }}921+ -> 42.5922+923+ Note that even if rounded to 0 precision, a float is returned. If924+ you need a real integer, pipe it through `int`:925+926+ .. sourcecode:: jinja927+928+ {{ 42.55|round|int }}929+ -> 43930+ """931+ if method not in {"common", "ceil", "floor"}:932+ raise FilterArgumentError("method must be common, ceil or floor")933+ if method == "common":934+ return round(value, precision)935+ func = getattr(math, method)936+ return func(value * (10 ** precision)) / (10 ** precision)937+938+939+# Use a regular tuple repr here. This is what we did in the past and we940+# really want to hide this custom type as much as possible. In particular941+# we do not want to accidentally expose an auto generated repr in case942+# people start to print this out in comments or something similar for943+# debugging.944+_GroupTuple = namedtuple("_GroupTuple", ["grouper", "list"])945+_GroupTuple.__repr__ = tuple.__repr__946+_GroupTuple.__str__ = tuple.__str__947+948+949+@environmentfilter950+def do_groupby(environment, value, attribute):951+ """Group a sequence of objects by an attribute using Python's952+ :func:`itertools.groupby`. The attribute can use dot notation for953+ nested access, like ``"address.city"``. Unlike Python's ``groupby``,954+ the values are sorted first so only one group is returned for each955+ unique value.956+957+ For example, a list of ``User`` objects with a ``city`` attribute958+ can be rendered in groups. In this example, ``grouper`` refers to959+ the ``city`` value of the group.960+961+ .. sourcecode:: html+jinja962+963+ <ul>{% for city, items in users|groupby("city") %}964+ <li>{{ city }}965+ <ul>{% for user in items %}966+ <li>{{ user.name }}967+ {% endfor %}</ul>968+ </li>969+ {% endfor %}</ul>970+971+ ``groupby`` yields namedtuples of ``(grouper, list)``, which972+ can be used instead of the tuple unpacking above. ``grouper`` is the973+ value of the attribute, and ``list`` is the items with that value.974+975+ .. sourcecode:: html+jinja976+977+ <ul>{% for group in users|groupby("city") %}978+ <li>{{ group.grouper }}: {{ group.list|join(", ") }}979+ {% endfor %}</ul>980+981+ .. versionchanged:: 2.6982+ The attribute supports dot notation for nested access.983+ """984+ expr = make_attrgetter(environment, attribute)985+ return [986+ _GroupTuple(key, list(values))987+ for key, values in groupby(sorted(value, key=expr), expr)988+ ]989+990+991+@environmentfilter992+def do_sum(environment, iterable, attribute=None, start=0):993+ """Returns the sum of a sequence of numbers plus the value of parameter994+ 'start' (which defaults to 0). When the sequence is empty it returns995+ start.996+997+ It is also possible to sum up only certain attributes:998+999+ .. sourcecode:: jinja1000+1001+ Total: {{ items|sum(attribute='price') }}1002+1003+ .. versionchanged:: 2.61004+ The `attribute` parameter was added to allow suming up over1005+ attributes. Also the `start` parameter was moved on to the right.1006+ """1007+ if attribute is not None:1008+ iterable = imap(make_attrgetter(environment, attribute), iterable)1009+ return sum(iterable, start)1010+1011+1012+def do_list(value):1013+ """Convert the value into a list. If it was a string the returned list1014+ will be a list of characters.1015+ """1016+ return list(value)1017+1018+1019+def do_mark_safe(value):1020+ """Mark the value as safe which means that in an environment with automatic1021+ escaping enabled this variable will not be escaped.1022+ """1023+ return Markup(value)1024+1025+1026+def do_mark_unsafe(value):1027+ """Mark a value as unsafe. This is the reverse operation for :func:`safe`."""1028+ return text_type(value)1029+1030+1031+def do_reverse(value):1032+ """Reverse the object or return an iterator that iterates over it the other1033+ way round.1034+ """1035+ if isinstance(value, string_types):1036+ return value[::-1]1037+ try:1038+ return reversed(value)1039+ except TypeError:1040+ try:1041+ rv = list(value)1042+ rv.reverse()1043+ return rv1044+ except TypeError:1045+ raise FilterArgumentError("argument must be iterable")1046+1047+1048+@environmentfilter1049+def do_attr(environment, obj, name):1050+ """Get an attribute of an object. ``foo|attr("bar")`` works like1051+ ``foo.bar`` just that always an attribute is returned and items are not1052+ looked up.1053+1054+ See :ref:`Notes on subscriptions <notes-on-subscriptions>` for more details.1055+ """1056+ try:1057+ name = str(name)1058+ except UnicodeError:1059+ pass1060+ else:1061+ try:1062+ value = getattr(obj, name)1063+ except AttributeError:1064+ pass1065+ else:1066+ if environment.sandboxed and not environment.is_safe_attribute(1067+ obj, name, value1068+ ):1069+ return environment.unsafe_undefined(obj, name)1070+ return value1071+ return environment.undefined(obj=obj, name=name)1072+1073+1074+@contextfilter1075+def do_map(*args, **kwargs):1076+ """Applies a filter on a sequence of objects or looks up an attribute.1077+ This is useful when dealing with lists of objects but you are really1078+ only interested in a certain value of it.1079+1080+ The basic usage is mapping on an attribute. Imagine you have a list1081+ of users but you are only interested in a list of usernames:1082+1083+ .. sourcecode:: jinja1084+1085+ Users on this page: {{ users|map(attribute='username')|join(', ') }}1086+1087+ You can specify a ``default`` value to use if an object in the list1088+ does not have the given attribute.1089+1090+ .. sourcecode:: jinja1091+1092+ {{ users|map(attribute="username", default="Anonymous")|join(", ") }}1093+1094+ Alternatively you can let it invoke a filter by passing the name of the1095+ filter and the arguments afterwards. A good example would be applying a1096+ text conversion filter on a sequence:1097+1098+ .. sourcecode:: jinja1099+1100+ Users on this page: {{ titles|map('lower')|join(', ') }}1101+1102+ Similar to a generator comprehension such as:1103+1104+ .. code-block:: python1105+1106+ (u.username for u in users)1107+ (u.username or "Anonymous" for u in users)1108+ (do_lower(x) for x in titles)1109+1110+ .. versionchanged:: 2.11.01111+ Added the ``default`` parameter.1112+1113+ .. versionadded:: 2.71114+ """1115+ seq, func = prepare_map(args, kwargs)1116+ if seq:1117+ for item in seq:1118+ yield func(item)1119+1120+1121+@contextfilter1122+def do_select(*args, **kwargs):1123+ """Filters a sequence of objects by applying a test to each object,1124+ and only selecting the objects with the test succeeding.1125+1126+ If no test is specified, each object will be evaluated as a boolean.1127+1128+ Example usage:1129+1130+ .. sourcecode:: jinja1131+1132+ {{ numbers|select("odd") }}1133+ {{ numbers|select("odd") }}1134+ {{ numbers|select("divisibleby", 3) }}1135+ {{ numbers|select("lessthan", 42) }}1136+ {{ strings|select("equalto", "mystring") }}1137+1138+ Similar to a generator comprehension such as:1139+1140+ .. code-block:: python1141+1142+ (n for n in numbers if test_odd(n))1143+ (n for n in numbers if test_divisibleby(n, 3))1144+1145+ .. versionadded:: 2.71146+ """1147+ return select_or_reject(args, kwargs, lambda x: x, False)1148+1149+1150+@contextfilter1151+def do_reject(*args, **kwargs):1152+ """Filters a sequence of objects by applying a test to each object,1153+ and rejecting the objects with the test succeeding.1154+1155+ If no test is specified, each object will be evaluated as a boolean.1156+1157+ Example usage:1158+1159+ .. sourcecode:: jinja1160+1161+ {{ numbers|reject("odd") }}1162+1163+ Similar to a generator comprehension such as:1164+1165+ .. code-block:: python1166+1167+ (n for n in numbers if not test_odd(n))1168+1169+ .. versionadded:: 2.71170+ """1171+ return select_or_reject(args, kwargs, lambda x: not x, False)1172+1173+1174+@contextfilter1175+def do_selectattr(*args, **kwargs):1176+ """Filters a sequence of objects by applying a test to the specified1177+ attribute of each object, and only selecting the objects with the1178+ test succeeding.1179+1180+ If no test is specified, the attribute's value will be evaluated as1181+ a boolean.1182+1183+ Example usage:1184+1185+ .. sourcecode:: jinja1186+1187+ {{ users|selectattr("is_active") }}1188+ {{ users|selectattr("email", "none") }}1189+1190+ Similar to a generator comprehension such as:1191+1192+ .. code-block:: python1193+1194+ (u for user in users if user.is_active)1195+ (u for user in users if test_none(user.email))1196+1197+ .. versionadded:: 2.71198+ """1199+ return select_or_reject(args, kwargs, lambda x: x, True)1200+1201+1202+@contextfilter1203+def do_rejectattr(*args, **kwargs):1204+ """Filters a sequence of objects by applying a test to the specified1205+ attribute of each object, and rejecting the objects with the test1206+ succeeding.1207+1208+ If no test is specified, the attribute's value will be evaluated as1209+ a boolean.1210+1211+ .. sourcecode:: jinja1212+1213+ {{ users|rejectattr("is_active") }}1214+ {{ users|rejectattr("email", "none") }}1215+1216+ Similar to a generator comprehension such as:1217+1218+ .. code-block:: python1219+1220+ (u for user in users if not user.is_active)1221+ (u for user in users if not test_none(user.email))1222+1223+ .. versionadded:: 2.71224+ """1225+ return select_or_reject(args, kwargs, lambda x: not x, True)1226+1227+1228+@evalcontextfilter1229+def do_tojson(eval_ctx, value, indent=None):1230+ """Dumps a structure to JSON so that it's safe to use in ``<script>``1231+ tags. It accepts the same arguments and returns a JSON string. Note that1232+ this is available in templates through the ``|tojson`` filter which will1233+ also mark the result as safe. Due to how this function escapes certain1234+ characters this is safe even if used outside of ``<script>`` tags.1235+1236+ The following characters are escaped in strings:1237+1238+ - ``<``1239+ - ``>``1240+ - ``&``1241+ - ``'``1242+1243+ This makes it safe to embed such strings in any place in HTML with the1244+ notable exception of double quoted attributes. In that case single1245+ quote your attributes or HTML escape it in addition.1246+1247+ The indent parameter can be used to enable pretty printing. Set it to1248+ the number of spaces that the structures should be indented with.1249+1250+ Note that this filter is for use in HTML contexts only.1251+1252+ .. versionadded:: 2.91253+ """1254+ policies = eval_ctx.environment.policies1255+ dumper = policies["json.dumps_function"]1256+ options = policies["json.dumps_kwargs"]1257+ if indent is not None:1258+ options = dict(options)1259+ options["indent"] = indent1260+ return htmlsafe_json_dumps(value, dumper=dumper, **options)1261+1262+1263+def prepare_map(args, kwargs):1264+ context = args[0]1265+ seq = args[1]1266+ default = None1267+1268+ if len(args) == 2 and "attribute" in kwargs:1269+ attribute = kwargs.pop("attribute")1270+ default = kwargs.pop("default", None)1271+ if kwargs:1272+ raise FilterArgumentError(1273+ "Unexpected keyword argument %r" % next(iter(kwargs))1274+ )1275+ func = make_attrgetter(context.environment, attribute, default=default)1276+ else:1277+ try:1278+ name = args[2]1279+ args = args[3:]1280+ except LookupError:1281+ raise FilterArgumentError("map requires a filter argument")1282+1283+ def func(item):1284+ return context.environment.call_filter(1285+ name, item, args, kwargs, context=context1286+ )1287+1288+ return seq, func1289+1290+1291+def prepare_select_or_reject(args, kwargs, modfunc, lookup_attr):1292+ context = args[0]1293+ seq = args[1]1294+ if lookup_attr:1295+ try:1296+ attr = args[2]1297+ except LookupError:1298+ raise FilterArgumentError("Missing parameter for attribute name")1299+ transfunc = make_attrgetter(context.environment, attr)1300+ off = 11301+ else:1302+ off = 01303+1304+ def transfunc(x):1305+ return x1306+1307+ try:1308+ name = args[2 + off]1309+ args = args[3 + off :]1310+1311+ def func(item):1312+ return context.environment.call_test(name, item, args, kwargs)1313+1314+ except LookupError:1315+ func = bool1316+1317+ return seq, lambda item: modfunc(func(transfunc(item)))1318+1319+1320+def select_or_reject(args, kwargs, modfunc, lookup_attr):1321+ seq, func = prepare_select_or_reject(args, kwargs, modfunc, lookup_attr)1322+ if seq:1323+ for item in seq:1324+ if func(item):1325+ yield item1326+1327+1328+FILTERS = {1329+ "abs": abs,1330+ "attr": do_attr,1331+ "batch": do_batch,1332+ "capitalize": do_capitalize,1333+ "center": do_center,1334+ "count": len,1335+ "d": do_default,1336+ "default": do_default,1337+ "dictsort": do_dictsort,1338+ "e": escape,1339+ "escape": escape,1340+ "filesizeformat": do_filesizeformat,1341+ "first": do_first,1342+ "float": do_float,1343+ "forceescape": do_forceescape,1344+ "format": do_format,1345+ "groupby": do_groupby,1346+ "indent": do_indent,1347+ "int": do_int,1348+ "join": do_join,1349+ "last": do_last,1350+ "length": len,1351+ "list": do_list,1352+ "lower": do_lower,1353+ "map": do_map,1354+ "min": do_min,1355+ "max": do_max,1356+ "pprint": do_pprint,1357+ "random": do_random,1358+ "reject": do_reject,1359+ "rejectattr": do_rejectattr,1360+ "replace": do_replace,1361+ "reverse": do_reverse,1362+ "round": do_round,1363+ "safe": do_mark_safe,1364+ "select": do_select,1365+ "selectattr": do_selectattr,1366+ "slice": do_slice,1367+ "sort": do_sort,1368+ "string": soft_unicode,1369+ "striptags": do_striptags,1370+ "sum": do_sum,1371+ "title": do_title,1372+ "trim": do_trim,1373+ "truncate": do_truncate,1374+ "unique": do_unique,1375+ "upper": do_upper,1376+ "urlencode": do_urlencode,1377+ "urlize": do_urlize,1378+ "wordcount": do_wordcount,1379+ "wordwrap": do_wordwrap,1380+ "xmlattr": do_xmlattr,1381+ "tojson": do_tojson,1382+}added:src/jinja2/idtracking.py+290 added
1+from ._compat import iteritems2+from .visitor import NodeVisitor3+4+VAR_LOAD_PARAMETER = "param"5+VAR_LOAD_RESOLVE = "resolve"6+VAR_LOAD_ALIAS = "alias"7+VAR_LOAD_UNDEFINED = "undefined"8+9+10+def find_symbols(nodes, parent_symbols=None):11+ sym = Symbols(parent=parent_symbols)12+ visitor = FrameSymbolVisitor(sym)13+ for node in nodes:14+ visitor.visit(node)15+ return sym16+17+18+def symbols_for_node(node, parent_symbols=None):19+ sym = Symbols(parent=parent_symbols)20+ sym.analyze_node(node)21+ return sym22+23+24+class Symbols(object):25+ def __init__(self, parent=None, level=None):26+ if level is None:27+ if parent is None:28+ level = 029+ else:30+ level = parent.level + 131+ self.level = level32+ self.parent = parent33+ self.refs = {}34+ self.loads = {}35+ self.stores = set()36+37+ def analyze_node(self, node, **kwargs):38+ visitor = RootVisitor(self)39+ visitor.visit(node, **kwargs)40+41+ def _define_ref(self, name, load=None):42+ ident = "l_%d_%s" % (self.level, name)43+ self.refs[name] = ident44+ if load is not None:45+ self.loads[ident] = load46+ return ident47+48+ def find_load(self, target):49+ if target in self.loads:50+ return self.loads[target]51+ if self.parent is not None:52+ return self.parent.find_load(target)53+54+ def find_ref(self, name):55+ if name in self.refs:56+ return self.refs[name]57+ if self.parent is not None:58+ return self.parent.find_ref(name)59+60+ def ref(self, name):61+ rv = self.find_ref(name)62+ if rv is None:63+ raise AssertionError(64+ "Tried to resolve a name to a reference that "65+ "was unknown to the frame (%r)" % name66+ )67+ return rv68+69+ def copy(self):70+ rv = object.__new__(self.__class__)71+ rv.__dict__.update(self.__dict__)72+ rv.refs = self.refs.copy()73+ rv.loads = self.loads.copy()74+ rv.stores = self.stores.copy()75+ return rv76+77+ def store(self, name):78+ self.stores.add(name)79+80+ # If we have not see the name referenced yet, we need to figure81+ # out what to set it to.82+ if name not in self.refs:83+ # If there is a parent scope we check if the name has a84+ # reference there. If it does it means we might have to alias85+ # to a variable there.86+ if self.parent is not None:87+ outer_ref = self.parent.find_ref(name)88+ if outer_ref is not None:89+ self._define_ref(name, load=(VAR_LOAD_ALIAS, outer_ref))90+ return91+92+ # Otherwise we can just set it to undefined.93+ self._define_ref(name, load=(VAR_LOAD_UNDEFINED, None))94+95+ def declare_parameter(self, name):96+ self.stores.add(name)97+ return self._define_ref(name, load=(VAR_LOAD_PARAMETER, None))98+99+ def load(self, name):100+ target = self.find_ref(name)101+ if target is None:102+ self._define_ref(name, load=(VAR_LOAD_RESOLVE, name))103+104+ def branch_update(self, branch_symbols):105+ stores = {}106+ for branch in branch_symbols:107+ for target in branch.stores:108+ if target in self.stores:109+ continue110+ stores[target] = stores.get(target, 0) + 1111+112+ for sym in branch_symbols:113+ self.refs.update(sym.refs)114+ self.loads.update(sym.loads)115+ self.stores.update(sym.stores)116+117+ for name, branch_count in iteritems(stores):118+ if branch_count == len(branch_symbols):119+ continue120+ target = self.find_ref(name)121+ assert target is not None, "should not happen"122+123+ if self.parent is not None:124+ outer_target = self.parent.find_ref(name)125+ if outer_target is not None:126+ self.loads[target] = (VAR_LOAD_ALIAS, outer_target)127+ continue128+ self.loads[target] = (VAR_LOAD_RESOLVE, name)129+130+ def dump_stores(self):131+ rv = {}132+ node = self133+ while node is not None:134+ for name in node.stores:135+ if name not in rv:136+ rv[name] = self.find_ref(name)137+ node = node.parent138+ return rv139+140+ def dump_param_targets(self):141+ rv = set()142+ node = self143+ while node is not None:144+ for target, (instr, _) in iteritems(self.loads):145+ if instr == VAR_LOAD_PARAMETER:146+ rv.add(target)147+ node = node.parent148+ return rv149+150+151+class RootVisitor(NodeVisitor):152+ def __init__(self, symbols):153+ self.sym_visitor = FrameSymbolVisitor(symbols)154+155+ def _simple_visit(self, node, **kwargs):156+ for child in node.iter_child_nodes():157+ self.sym_visitor.visit(child)158+159+ visit_Template = (160+ visit_Block161+ ) = (162+ visit_Macro163+ ) = (164+ visit_FilterBlock165+ ) = visit_Scope = visit_If = visit_ScopedEvalContextModifier = _simple_visit166+167+ def visit_AssignBlock(self, node, **kwargs):168+ for child in node.body:169+ self.sym_visitor.visit(child)170+171+ def visit_CallBlock(self, node, **kwargs):172+ for child in node.iter_child_nodes(exclude=("call",)):173+ self.sym_visitor.visit(child)174+175+ def visit_OverlayScope(self, node, **kwargs):176+ for child in node.body:177+ self.sym_visitor.visit(child)178+179+ def visit_For(self, node, for_branch="body", **kwargs):180+ if for_branch == "body":181+ self.sym_visitor.visit(node.target, store_as_param=True)182+ branch = node.body183+ elif for_branch == "else":184+ branch = node.else_185+ elif for_branch == "test":186+ self.sym_visitor.visit(node.target, store_as_param=True)187+ if node.test is not None:188+ self.sym_visitor.visit(node.test)189+ return190+ else:191+ raise RuntimeError("Unknown for branch")192+ for item in branch or ():193+ self.sym_visitor.visit(item)194+195+ def visit_With(self, node, **kwargs):196+ for target in node.targets:197+ self.sym_visitor.visit(target)198+ for child in node.body:199+ self.sym_visitor.visit(child)200+201+ def generic_visit(self, node, *args, **kwargs):202+ raise NotImplementedError(203+ "Cannot find symbols for %r" % node.__class__.__name__204+ )205+206+207+class FrameSymbolVisitor(NodeVisitor):208+ """A visitor for `Frame.inspect`."""209+210+ def __init__(self, symbols):211+ self.symbols = symbols212+213+ def visit_Name(self, node, store_as_param=False, **kwargs):214+ """All assignments to names go through this function."""215+ if store_as_param or node.ctx == "param":216+ self.symbols.declare_parameter(node.name)217+ elif node.ctx == "store":218+ self.symbols.store(node.name)219+ elif node.ctx == "load":220+ self.symbols.load(node.name)221+222+ def visit_NSRef(self, node, **kwargs):223+ self.symbols.load(node.name)224+225+ def visit_If(self, node, **kwargs):226+ self.visit(node.test, **kwargs)227+228+ original_symbols = self.symbols229+230+ def inner_visit(nodes):231+ self.symbols = rv = original_symbols.copy()232+ for subnode in nodes:233+ self.visit(subnode, **kwargs)234+ self.symbols = original_symbols235+ return rv236+237+ body_symbols = inner_visit(node.body)238+ elif_symbols = inner_visit(node.elif_)239+ else_symbols = inner_visit(node.else_ or ())240+241+ self.symbols.branch_update([body_symbols, elif_symbols, else_symbols])242+243+ def visit_Macro(self, node, **kwargs):244+ self.symbols.store(node.name)245+246+ def visit_Import(self, node, **kwargs):247+ self.generic_visit(node, **kwargs)248+ self.symbols.store(node.target)249+250+ def visit_FromImport(self, node, **kwargs):251+ self.generic_visit(node, **kwargs)252+ for name in node.names:253+ if isinstance(name, tuple):254+ self.symbols.store(name[1])255+ else:256+ self.symbols.store(name)257+258+ def visit_Assign(self, node, **kwargs):259+ """Visit assignments in the correct order."""260+ self.visit(node.node, **kwargs)261+ self.visit(node.target, **kwargs)262+263+ def visit_For(self, node, **kwargs):264+ """Visiting stops at for blocks. However the block sequence265+ is visited as part of the outer scope.266+ """267+ self.visit(node.iter, **kwargs)268+269+ def visit_CallBlock(self, node, **kwargs):270+ self.visit(node.call, **kwargs)271+272+ def visit_FilterBlock(self, node, **kwargs):273+ self.visit(node.filter, **kwargs)274+275+ def visit_With(self, node, **kwargs):276+ for target in node.values:277+ self.visit(target)278+279+ def visit_AssignBlock(self, node, **kwargs):280+ """Stop visiting at block assigns."""281+ self.visit(node.target, **kwargs)282+283+ def visit_Scope(self, node, **kwargs):284+ """Stop visiting at scopes."""285+286+ def visit_Block(self, node, **kwargs):287+ """Stop visiting at blocks."""288+289+ def visit_OverlayScope(self, node, **kwargs):290+ """Do not visit into overlay scopes."""added:src/jinja2/lexer.py+841 added
1+# -*- coding: utf-8 -*-2+"""Implements a Jinja / Python combination lexer. The ``Lexer`` class3+is used to do some preprocessing. It filters out invalid operators like4+the bitshift operators we don't allow in templates. It separates5+template code and python code in expressions.6+"""7+import re8+from ast import literal_eval9+from collections import deque10+from operator import itemgetter11+12+from ._compat import implements_iterator13+from ._compat import intern14+from ._compat import iteritems15+from ._compat import text_type16+from .exceptions import TemplateSyntaxError17+from .utils import LRUCache18+19+# cache for the lexers. Exists in order to be able to have multiple20+# environments with the same lexer21+_lexer_cache = LRUCache(50)22+23+# static regular expressions24+whitespace_re = re.compile(r"\s+", re.U)25+newline_re = re.compile(r"(\r\n|\r|\n)")26+string_re = re.compile(27+ r"('([^'\\]*(?:\\.[^'\\]*)*)'" r'|"([^"\\]*(?:\\.[^"\\]*)*)")', re.S28+)29+integer_re = re.compile(r"(\d+_)*\d+")30+float_re = re.compile(31+ r"""32+ (?<!\.) # doesn't start with a .33+ (\d+_)*\d+ # digits, possibly _ separated34+ (35+ (\.(\d+_)*\d+)? # optional fractional part36+ e[+\-]?(\d+_)*\d+ # exponent part37+ |38+ \.(\d+_)*\d+ # required fractional part39+ )40+ """,41+ re.IGNORECASE | re.VERBOSE,42+)43+44+try:45+ # check if this Python supports Unicode identifiers46+ compile("föö", "<unknown>", "eval")47+except 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 = False51+else: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_re55+56+ check_ident = True57+58+# internal the tokens and keep references to them59+TOKEN_ADD = intern("add")60+TOKEN_ASSIGN = intern("assign")61+TOKEN_COLON = intern("colon")62+TOKEN_COMMA = intern("comma")63+TOKEN_DIV = intern("div")64+TOKEN_DOT = intern("dot")65+TOKEN_EQ = intern("eq")66+TOKEN_FLOORDIV = intern("floordiv")67+TOKEN_GT = intern("gt")68+TOKEN_GTEQ = intern("gteq")69+TOKEN_LBRACE = intern("lbrace")70+TOKEN_LBRACKET = intern("lbracket")71+TOKEN_LPAREN = intern("lparen")72+TOKEN_LT = intern("lt")73+TOKEN_LTEQ = intern("lteq")74+TOKEN_MOD = intern("mod")75+TOKEN_MUL = intern("mul")76+TOKEN_NE = intern("ne")77+TOKEN_PIPE = intern("pipe")78+TOKEN_POW = intern("pow")79+TOKEN_RBRACE = intern("rbrace")80+TOKEN_RBRACKET = intern("rbracket")81+TOKEN_RPAREN = intern("rparen")82+TOKEN_SEMICOLON = intern("semicolon")83+TOKEN_SUB = intern("sub")84+TOKEN_TILDE = intern("tilde")85+TOKEN_WHITESPACE = intern("whitespace")86+TOKEN_FLOAT = intern("float")87+TOKEN_INTEGER = intern("integer")88+TOKEN_NAME = intern("name")89+TOKEN_STRING = intern("string")90+TOKEN_OPERATOR = intern("operator")91+TOKEN_BLOCK_BEGIN = intern("block_begin")92+TOKEN_BLOCK_END = intern("block_end")93+TOKEN_VARIABLE_BEGIN = intern("variable_begin")94+TOKEN_VARIABLE_END = intern("variable_end")95+TOKEN_RAW_BEGIN = intern("raw_begin")96+TOKEN_RAW_END = intern("raw_end")97+TOKEN_COMMENT_BEGIN = intern("comment_begin")98+TOKEN_COMMENT_END = intern("comment_end")99+TOKEN_COMMENT = intern("comment")100+TOKEN_LINESTATEMENT_BEGIN = intern("linestatement_begin")101+TOKEN_LINESTATEMENT_END = intern("linestatement_end")102+TOKEN_LINECOMMENT_BEGIN = intern("linecomment_begin")103+TOKEN_LINECOMMENT_END = intern("linecomment_end")104+TOKEN_LINECOMMENT = intern("linecomment")105+TOKEN_DATA = intern("data")106+TOKEN_INITIAL = intern("initial")107+TOKEN_EOF = intern("eof")108+109+# bind operators to token types110+operators = {111+ "+": TOKEN_ADD,112+ "-": TOKEN_SUB,113+ "/": TOKEN_DIV,114+ "//": TOKEN_FLOORDIV,115+ "*": TOKEN_MUL,116+ "%": TOKEN_MOD,117+ "**": TOKEN_POW,118+ "~": TOKEN_TILDE,119+ "[": TOKEN_LBRACKET,120+ "]": TOKEN_RBRACKET,121+ "(": TOKEN_LPAREN,122+ ")": TOKEN_RPAREN,123+ "{": TOKEN_LBRACE,124+ "}": TOKEN_RBRACE,125+ "==": TOKEN_EQ,126+ "!=": TOKEN_NE,127+ ">": TOKEN_GT,128+ ">=": TOKEN_GTEQ,129+ "<": TOKEN_LT,130+ "<=": TOKEN_LTEQ,131+ "=": TOKEN_ASSIGN,132+ ".": TOKEN_DOT,133+ ":": TOKEN_COLON,134+ "|": TOKEN_PIPE,135+ ",": TOKEN_COMMA,136+ ";": TOKEN_SEMICOLON,137+}138+139+reverse_operators = dict([(v, k) for k, v in iteritems(operators)])140+assert len(operators) == len(reverse_operators), "operators dropped"141+operator_re = re.compile(142+ "(%s)" % "|".join(re.escape(x) for x in sorted(operators, key=lambda x: -len(x)))143+)144+145+ignored_tokens = frozenset(146+ [147+ TOKEN_COMMENT_BEGIN,148+ TOKEN_COMMENT,149+ TOKEN_COMMENT_END,150+ TOKEN_WHITESPACE,151+ TOKEN_LINECOMMENT_BEGIN,152+ TOKEN_LINECOMMENT_END,153+ TOKEN_LINECOMMENT,154+ ]155+)156+ignore_if_empty = frozenset(157+ [TOKEN_WHITESPACE, TOKEN_DATA, TOKEN_COMMENT, TOKEN_LINECOMMENT]158+)159+160+161+def _describe_token_type(token_type):162+ if token_type in reverse_operators:163+ return reverse_operators[token_type]164+ return {165+ TOKEN_COMMENT_BEGIN: "begin of comment",166+ TOKEN_COMMENT_END: "end of comment",167+ TOKEN_COMMENT: "comment",168+ TOKEN_LINECOMMENT: "comment",169+ TOKEN_BLOCK_BEGIN: "begin of statement block",170+ TOKEN_BLOCK_END: "end of statement block",171+ TOKEN_VARIABLE_BEGIN: "begin of print statement",172+ TOKEN_VARIABLE_END: "end of print statement",173+ TOKEN_LINESTATEMENT_BEGIN: "begin of line statement",174+ TOKEN_LINESTATEMENT_END: "end of line statement",175+ TOKEN_DATA: "template data / text",176+ TOKEN_EOF: "end of template",177+ }.get(token_type, token_type)178+179+180+def describe_token(token):181+ """Returns a description of the token."""182+ if token.type == TOKEN_NAME:183+ return token.value184+ return _describe_token_type(token.type)185+186+187+def describe_token_expr(expr):188+ """Like `describe_token` but for token expressions."""189+ if ":" in expr:190+ type, value = expr.split(":", 1)191+ if type == TOKEN_NAME:192+ return value193+ else:194+ type = expr195+ return _describe_token_type(type)196+197+198+def count_newlines(value):199+ """Count the number of newline characters in the string. This is200+ useful for extensions that filter a stream.201+ """202+ return len(newline_re.findall(value))203+204+205+def compile_rules(environment):206+ """Compiles all the rules from the environment into a list of rules."""207+ e = re.escape208+ rules = [209+ (210+ len(environment.comment_start_string),211+ TOKEN_COMMENT_BEGIN,212+ e(environment.comment_start_string),213+ ),214+ (215+ len(environment.block_start_string),216+ TOKEN_BLOCK_BEGIN,217+ e(environment.block_start_string),218+ ),219+ (220+ len(environment.variable_start_string),221+ TOKEN_VARIABLE_BEGIN,222+ e(environment.variable_start_string),223+ ),224+ ]225+226+ if environment.line_statement_prefix is not None:227+ rules.append(228+ (229+ len(environment.line_statement_prefix),230+ TOKEN_LINESTATEMENT_BEGIN,231+ r"^[ \t\v]*" + e(environment.line_statement_prefix),232+ )233+ )234+ if environment.line_comment_prefix is not None:235+ rules.append(236+ (237+ len(environment.line_comment_prefix),238+ TOKEN_LINECOMMENT_BEGIN,239+ r"(?:^|(?<=\S))[^\S\r\n]*" + e(environment.line_comment_prefix),240+ )241+ )242+243+ return [x[1:] for x in sorted(rules, reverse=True)]244+245+246+class Failure(object):247+ """Class that raises a `TemplateSyntaxError` if called.248+ Used by the `Lexer` to specify known errors.249+ """250+251+ def __init__(self, message, cls=TemplateSyntaxError):252+ self.message = message253+ self.error_class = cls254+255+ def __call__(self, lineno, filename):256+ raise self.error_class(self.message, lineno, filename)257+258+259+class Token(tuple):260+ """Token class."""261+262+ __slots__ = ()263+ lineno, type, value = (property(itemgetter(x)) for x in range(3))264+265+ def __new__(cls, lineno, type, value):266+ return tuple.__new__(cls, (lineno, intern(str(type)), value))267+268+ def __str__(self):269+ if self.type in reverse_operators:270+ return reverse_operators[self.type]271+ elif self.type == "name":272+ return self.value273+ return self.type274+275+ def test(self, expr):276+ """Test a token against a token expression. This can either be a277+ token type or ``'token_type:token_value'``. This can only test278+ against string values and types.279+ """280+ # here we do a regular string equality check as test_any is usually281+ # passed an iterable of not interned strings.282+ if self.type == expr:283+ return True284+ elif ":" in expr:285+ return expr.split(":", 1) == [self.type, self.value]286+ return False287+288+ def test_any(self, *iterable):289+ """Test against multiple token expressions."""290+ for expr in iterable:291+ if self.test(expr):292+ return True293+ return False294+295+ def __repr__(self):296+ return "Token(%r, %r, %r)" % (self.lineno, self.type, self.value)297+298+299+@implements_iterator300+class TokenStreamIterator(object):301+ """The iterator for tokenstreams. Iterate over the stream302+ until the eof token is reached.303+ """304+305+ def __init__(self, stream):306+ self.stream = stream307+308+ def __iter__(self):309+ return self310+311+ def __next__(self):312+ token = self.stream.current313+ if token.type is TOKEN_EOF:314+ self.stream.close()315+ raise StopIteration()316+ next(self.stream)317+ return token318+319+320+@implements_iterator321+class TokenStream(object):322+ """A token stream is an iterable that yields :class:`Token`\\s. The323+ parser however does not iterate over it but calls :meth:`next` to go324+ one token ahead. The current active token is stored as :attr:`current`.325+ """326+327+ def __init__(self, generator, name, filename):328+ self._iter = iter(generator)329+ self._pushed = deque()330+ self.name = name331+ self.filename = filename332+ self.closed = False333+ self.current = Token(1, TOKEN_INITIAL, "")334+ next(self)335+336+ def __iter__(self):337+ return TokenStreamIterator(self)338+339+ def __bool__(self):340+ return bool(self._pushed) or self.current.type is not TOKEN_EOF341+342+ __nonzero__ = __bool__ # py2343+344+ @property345+ def eos(self):346+ """Are we at the end of the stream?"""347+ return not self348+349+ def push(self, token):350+ """Push a token back to the stream."""351+ self._pushed.append(token)352+353+ def look(self):354+ """Look at the next token."""355+ old_token = next(self)356+ result = self.current357+ self.push(result)358+ self.current = old_token359+ return result360+361+ def skip(self, n=1):362+ """Got n tokens ahead."""363+ for _ in range(n):364+ next(self)365+366+ def next_if(self, expr):367+ """Perform the token test and return the token if it matched.368+ Otherwise the return value is `None`.369+ """370+ if self.current.test(expr):371+ return next(self)372+373+ def skip_if(self, expr):374+ """Like :meth:`next_if` but only returns `True` or `False`."""375+ return self.next_if(expr) is not None376+377+ def __next__(self):378+ """Go one token ahead and return the old one.379+380+ Use the built-in :func:`next` instead of calling this directly.381+ """382+ rv = self.current383+ if self._pushed:384+ self.current = self._pushed.popleft()385+ elif self.current.type is not TOKEN_EOF:386+ try:387+ self.current = next(self._iter)388+ except StopIteration:389+ self.close()390+ return rv391+392+ def close(self):393+ """Close the stream."""394+ self.current = Token(self.current.lineno, TOKEN_EOF, "")395+ self._iter = None396+ self.closed = True397+398+ def expect(self, expr):399+ """Expect a given token type and return it. This accepts the same400+ argument as :meth:`jinja2.lexer.Token.test`.401+ """402+ if not self.current.test(expr):403+ expr = describe_token_expr(expr)404+ if self.current.type is TOKEN_EOF:405+ raise TemplateSyntaxError(406+ "unexpected end of template, expected %r." % expr,407+ self.current.lineno,408+ self.name,409+ self.filename,410+ )411+ raise TemplateSyntaxError(412+ "expected token %r, got %r" % (expr, describe_token(self.current)),413+ self.current.lineno,414+ self.name,415+ self.filename,416+ )417+ try:418+ return self.current419+ finally:420+ next(self)421+422+423+def get_lexer(environment):424+ """Return a lexer which is probably cached."""425+ key = (426+ environment.block_start_string,427+ environment.block_end_string,428+ environment.variable_start_string,429+ environment.variable_end_string,430+ environment.comment_start_string,431+ environment.comment_end_string,432+ environment.line_statement_prefix,433+ environment.line_comment_prefix,434+ environment.trim_blocks,435+ environment.lstrip_blocks,436+ environment.newline_sequence,437+ environment.keep_trailing_newline,438+ )439+ lexer = _lexer_cache.get(key)440+ if lexer is None:441+ lexer = Lexer(environment)442+ _lexer_cache[key] = lexer443+ return lexer444+445+446+class OptionalLStrip(tuple):447+ """A special tuple for marking a point in the state that can have448+ lstrip applied.449+ """450+451+ __slots__ = ()452+453+ # Even though it looks like a no-op, creating instances fails454+ # without this.455+ def __new__(cls, *members, **kwargs):456+ return super(OptionalLStrip, cls).__new__(cls, members)457+458+459+class Lexer(object):460+ """Class that implements a lexer for a given environment. Automatically461+ created by the environment class, usually you don't have to do that.462+463+ Note that the lexer is not automatically bound to an environment.464+ Multiple environments can share the same lexer.465+ """466+467+ def __init__(self, environment):468+ # shortcuts469+ e = re.escape470+471+ def c(x):472+ return re.compile(x, re.M | re.S)473+474+ # lexing rules for tags475+ tag_rules = [476+ (whitespace_re, TOKEN_WHITESPACE, None),477+ (float_re, TOKEN_FLOAT, None),478+ (integer_re, TOKEN_INTEGER, None),479+ (name_re, TOKEN_NAME, None),480+ (string_re, TOKEN_STRING, None),481+ (operator_re, TOKEN_OPERATOR, None),482+ ]483+484+ # assemble the root lexing rule. because "|" is ungreedy485+ # we have to sort by length so that the lexer continues working486+ # as expected when we have parsing rules like <% for block and487+ # <%= for variables. (if someone wants asp like syntax)488+ # variables are just part of the rules if variable processing489+ # is required.490+ root_tag_rules = compile_rules(environment)491+492+ # block suffix if trimming is enabled493+ block_suffix_re = environment.trim_blocks and "\\n?" or ""494+495+ # If lstrip is enabled, it should not be applied if there is any496+ # non-whitespace between the newline and block.497+ self.lstrip_unless_re = c(r"[^ \t]") if environment.lstrip_blocks else None498+499+ self.newline_sequence = environment.newline_sequence500+ self.keep_trailing_newline = environment.keep_trailing_newline501+502+ # global lexing rules503+ self.rules = {504+ "root": [505+ # directives506+ (507+ c(508+ "(.*?)(?:%s)"509+ % "|".join(510+ [511+ r"(?P<raw_begin>%s(\-|\+|)\s*raw\s*(?:\-%s\s*|%s))"512+ % (513+ e(environment.block_start_string),514+ e(environment.block_end_string),515+ e(environment.block_end_string),516+ )517+ ]518+ + [519+ r"(?P<%s>%s(\-|\+|))" % (n, r)520+ for n, r in root_tag_rules521+ ]522+ )523+ ),524+ OptionalLStrip(TOKEN_DATA, "#bygroup"),525+ "#bygroup",526+ ),527+ # data528+ (c(".+"), TOKEN_DATA, None),529+ ],530+ # comments531+ TOKEN_COMMENT_BEGIN: [532+ (533+ c(534+ r"(.*?)((?:\-%s\s*|%s)%s)"535+ % (536+ e(environment.comment_end_string),537+ e(environment.comment_end_string),538+ block_suffix_re,539+ )540+ ),541+ (TOKEN_COMMENT, TOKEN_COMMENT_END),542+ "#pop",543+ ),544+ (c("(.)"), (Failure("Missing end of comment tag"),), None),545+ ],546+ # blocks547+ TOKEN_BLOCK_BEGIN: [548+ (549+ c(550+ r"(?:\-%s\s*|%s)%s"551+ % (552+ e(environment.block_end_string),553+ e(environment.block_end_string),554+ block_suffix_re,555+ )556+ ),557+ TOKEN_BLOCK_END,558+ "#pop",559+ ),560+ ]561+ + tag_rules,562+ # variables563+ TOKEN_VARIABLE_BEGIN: [564+ (565+ c(566+ r"\-%s\s*|%s"567+ % (568+ e(environment.variable_end_string),569+ e(environment.variable_end_string),570+ )571+ ),572+ TOKEN_VARIABLE_END,573+ "#pop",574+ )575+ ]576+ + tag_rules,577+ # raw block578+ TOKEN_RAW_BEGIN: [579+ (580+ c(581+ r"(.*?)((?:%s(\-|\+|))\s*endraw\s*(?:\-%s\s*|%s%s))"582+ % (583+ e(environment.block_start_string),584+ e(environment.block_end_string),585+ e(environment.block_end_string),586+ block_suffix_re,587+ )588+ ),589+ OptionalLStrip(TOKEN_DATA, TOKEN_RAW_END),590+ "#pop",591+ ),592+ (c("(.)"), (Failure("Missing end of raw directive"),), None),593+ ],594+ # line statements595+ TOKEN_LINESTATEMENT_BEGIN: [596+ (c(r"\s*(\n|$)"), TOKEN_LINESTATEMENT_END, "#pop")597+ ]598+ + tag_rules,599+ # line comments600+ TOKEN_LINECOMMENT_BEGIN: [601+ (602+ c(r"(.*?)()(?=\n|$)"),603+ (TOKEN_LINECOMMENT, TOKEN_LINECOMMENT_END),604+ "#pop",605+ )606+ ],607+ }608+609+ def _normalize_newlines(self, value):610+ """Called for strings and template data to normalize it to unicode."""611+ return newline_re.sub(self.newline_sequence, value)612+613+ def tokenize(self, source, name=None, filename=None, state=None):614+ """Calls tokeniter + tokenize and wraps it in a token stream."""615+ stream = self.tokeniter(source, name, filename, state)616+ return TokenStream(self.wrap(stream, name, filename), name, filename)617+618+ def wrap(self, stream, name=None, filename=None):619+ """This is called with the stream as returned by `tokenize` and wraps620+ every token in a :class:`Token` and converts the value.621+ """622+ for lineno, token, value in stream:623+ if token in ignored_tokens:624+ continue625+ elif token == TOKEN_LINESTATEMENT_BEGIN:626+ token = TOKEN_BLOCK_BEGIN627+ elif token == TOKEN_LINESTATEMENT_END:628+ token = TOKEN_BLOCK_END629+ # we are not interested in those tokens in the parser630+ elif token in (TOKEN_RAW_BEGIN, TOKEN_RAW_END):631+ continue632+ elif token == TOKEN_DATA:633+ value = self._normalize_newlines(value)634+ elif token == "keyword":635+ token = value636+ elif token == TOKEN_NAME:637+ value = str(value)638+ if check_ident and not value.isidentifier():639+ raise TemplateSyntaxError(640+ "Invalid character in identifier", lineno, name, filename641+ )642+ elif token == TOKEN_STRING:643+ # try to unescape string644+ try:645+ value = (646+ self._normalize_newlines(value[1:-1])647+ .encode("ascii", "backslashreplace")648+ .decode("unicode-escape")649+ )650+ except Exception as e:651+ msg = str(e).split(":")[-1].strip()652+ raise TemplateSyntaxError(msg, lineno, name, filename)653+ elif token == TOKEN_INTEGER:654+ value = int(value.replace("_", ""))655+ elif token == TOKEN_FLOAT:656+ # remove all "_" first to support more Python versions657+ value = literal_eval(value.replace("_", ""))658+ elif token == TOKEN_OPERATOR:659+ token = operators[value]660+ yield Token(lineno, token, value)661+662+ def tokeniter(self, source, name, filename=None, state=None):663+ """This method tokenizes the text and returns the tokens in a664+ generator. Use this method if you just want to tokenize a template.665+ """666+ source = text_type(source)667+ lines = source.splitlines()668+ if self.keep_trailing_newline and source:669+ for newline in ("\r\n", "\r", "\n"):670+ if source.endswith(newline):671+ lines.append("")672+ break673+ source = "\n".join(lines)674+ pos = 0675+ lineno = 1676+ stack = ["root"]677+ if state is not None and state != "root":678+ assert state in ("variable", "block"), "invalid state"679+ stack.append(state + "_begin")680+ statetokens = self.rules[stack[-1]]681+ source_length = len(source)682+ balancing_stack = []683+ lstrip_unless_re = self.lstrip_unless_re684+685+ while 1:686+ # tokenizer loop687+ for regex, tokens, new_state in statetokens:688+ m = regex.match(source, pos)689+ # if no match we try again with the next rule690+ if m is None:691+ continue692+693+ # we only match blocks and variables if braces / parentheses694+ # are balanced. continue parsing with the lower rule which695+ # is the operator rule. do this only if the end tags look696+ # like operators697+ if balancing_stack and tokens in (698+ TOKEN_VARIABLE_END,699+ TOKEN_BLOCK_END,700+ TOKEN_LINESTATEMENT_END,701+ ):702+ continue703+704+ # tuples support more options705+ if isinstance(tokens, tuple):706+ groups = m.groups()707+708+ if isinstance(tokens, OptionalLStrip):709+ # Rule supports lstrip. Match will look like710+ # text, block type, whitespace control, type, control, ...711+ text = groups[0]712+713+ # Skipping the text and first type, every other group is the714+ # whitespace control for each type. One of the groups will be715+ # -, +, or empty string instead of None.716+ strip_sign = next(g for g in groups[2::2] if g is not None)717+718+ if strip_sign == "-":719+ # Strip all whitespace between the text and the tag.720+ groups = (text.rstrip(),) + groups[1:]721+ elif (722+ # Not marked for preserving whitespace.723+ strip_sign != "+"724+ # lstrip is enabled.725+ and lstrip_unless_re is not None726+ # Not a variable expression.727+ and not m.groupdict().get(TOKEN_VARIABLE_BEGIN)728+ ):729+ # The start of text between the last newline and the tag.730+ l_pos = text.rfind("\n") + 1731+732+ # If there's only whitespace between the newline and the733+ # tag, strip it.734+ if not lstrip_unless_re.search(text, l_pos):735+ groups = (text[:l_pos],) + groups[1:]736+737+ for idx, token in enumerate(tokens):738+ # failure group739+ if token.__class__ is Failure:740+ raise token(lineno, filename)741+ # bygroup is a bit more complex, in that case we742+ # yield for the current token the first named743+ # group that matched744+ elif token == "#bygroup":745+ for key, value in iteritems(m.groupdict()):746+ if value is not None:747+ yield lineno, key, value748+ lineno += value.count("\n")749+ break750+ else:751+ raise RuntimeError(752+ "%r wanted to resolve "753+ "the token dynamically"754+ " but no group matched" % regex755+ )756+ # normal group757+ else:758+ data = groups[idx]759+ if data or token not in ignore_if_empty:760+ yield lineno, token, data761+ lineno += data.count("\n")762+763+ # strings as token just are yielded as it.764+ else:765+ data = m.group()766+ # update brace/parentheses balance767+ if tokens == TOKEN_OPERATOR:768+ if data == "{":769+ balancing_stack.append("}")770+ elif data == "(":771+ balancing_stack.append(")")772+ elif data == "[":773+ balancing_stack.append("]")774+ elif data in ("}", ")", "]"):775+ if not balancing_stack:776+ raise TemplateSyntaxError(777+ "unexpected '%s'" % data, lineno, name, filename778+ )779+ expected_op = balancing_stack.pop()780+ if expected_op != data:781+ raise TemplateSyntaxError(782+ "unexpected '%s', "783+ "expected '%s'" % (data, expected_op),784+ lineno,785+ name,786+ filename,787+ )788+ # yield items789+ if data or tokens not in ignore_if_empty:790+ yield lineno, tokens, data791+ lineno += data.count("\n")792+793+ # fetch new position into new variable so that we can check794+ # if there is a internal parsing error which would result795+ # in an infinite loop796+ pos2 = m.end()797+798+ # handle state changes799+ if new_state is not None:800+ # remove the uppermost state801+ if new_state == "#pop":802+ stack.pop()803+ # resolve the new state by group checking804+ elif new_state == "#bygroup":805+ for key, value in iteritems(m.groupdict()):806+ if value is not None:807+ stack.append(key)808+ break809+ else:810+ raise RuntimeError(811+ "%r wanted to resolve the "812+ "new state dynamically but"813+ " no group matched" % regex814+ )815+ # direct state name given816+ else:817+ stack.append(new_state)818+ statetokens = self.rules[stack[-1]]819+ # we are still at the same position and no stack change.820+ # this means a loop without break condition, avoid that and821+ # raise error822+ elif pos2 == pos:823+ raise RuntimeError(824+ "%r yielded empty string without stack change" % regex825+ )826+ # publish new function and start again827+ pos = pos2828+ break829+ # if loop terminated without break we haven't found a single match830+ # either we are at the end of the file or we have a problem831+ else:832+ # end of text833+ if pos >= source_length:834+ return835+ # something went wrong836+ raise TemplateSyntaxError(837+ "unexpected char %r at %d" % (source[pos], pos),838+ lineno,839+ name,840+ filename,841+ )added:src/jinja2/loaders.py+572 added
1+# -*- coding: utf-8 -*-2+"""API and implementations for loading templates from different data3+sources.4+"""5+import os6+import pkgutil7+import sys8+import weakref9+from hashlib import sha110+from importlib import import_module11+from os import path12+from types import ModuleType13+14+from ._compat import abc15+from ._compat import fspath16+from ._compat import iteritems17+from ._compat import string_types18+from .exceptions import TemplateNotFound19+from .utils import internalcode20+from .utils import open_if_exists21+22+23+def split_template_path(template):24+ """Split a path into segments and perform a sanity check. If it detects25+ '..' in the path it will raise a `TemplateNotFound` error.26+ """27+ pieces = []28+ for piece in template.split("/"):29+ if (30+ path.sep in piece31+ or (path.altsep and path.altsep in piece)32+ or piece == path.pardir33+ ):34+ raise TemplateNotFound(template)35+ elif piece and piece != ".":36+ pieces.append(piece)37+ return pieces38+39+40+class BaseLoader(object):41+ """Baseclass for all loaders. Subclass this and override `get_source` to42+ implement a custom loading mechanism. The environment provides a43+ `get_template` method that calls the loader's `load` method to get the44+ :class:`Template` object.45+46+ A very basic example for a loader that looks up templates on the file47+ system could look like this::48+49+ from jinja2 import BaseLoader, TemplateNotFound50+ from os.path import join, exists, getmtime51+52+ class MyLoader(BaseLoader):53+54+ def __init__(self, path):55+ self.path = path56+57+ def get_source(self, environment, template):58+ path = join(self.path, template)59+ if not exists(path):60+ raise TemplateNotFound(template)61+ mtime = getmtime(path)62+ with file(path) as f:63+ source = f.read().decode('utf-8')64+ return source, path, lambda: mtime == getmtime(path)65+ """66+67+ #: if set to `False` it indicates that the loader cannot provide access68+ #: to the source of templates.69+ #:70+ #: .. versionadded:: 2.471+ has_source_access = True72+73+ def get_source(self, environment, template):74+ """Get the template source, filename and reload helper for a template.75+ It's passed the environment and template name and has to return a76+ tuple in the form ``(source, filename, uptodate)`` or raise a77+ `TemplateNotFound` error if it can't locate the template.78+79+ The source part of the returned tuple must be the source of the80+ template as unicode string or a ASCII bytestring. The filename should81+ be the name of the file on the filesystem if it was loaded from there,82+ otherwise `None`. The filename is used by python for the tracebacks83+ if no loader extension is used.84+85+ The last item in the tuple is the `uptodate` function. If auto86+ reloading is enabled it's always called to check if the template87+ changed. No arguments are passed so the function must store the88+ old state somewhere (for example in a closure). If it returns `False`89+ the template will be reloaded.90+ """91+ if not self.has_source_access:92+ raise RuntimeError(93+ "%s cannot provide access to the source" % self.__class__.__name__94+ )95+ raise TemplateNotFound(template)96+97+ def list_templates(self):98+ """Iterates over all templates. If the loader does not support that99+ it should raise a :exc:`TypeError` which is the default behavior.100+ """101+ raise TypeError("this loader cannot iterate over all templates")102+103+ @internalcode104+ def load(self, environment, name, globals=None):105+ """Loads a template. This method looks up the template in the cache106+ or loads one by calling :meth:`get_source`. Subclasses should not107+ override this method as loaders working on collections of other108+ loaders (such as :class:`PrefixLoader` or :class:`ChoiceLoader`)109+ will not call this method but `get_source` directly.110+ """111+ code = None112+ if globals is None:113+ globals = {}114+115+ # first we try to get the source for this template together116+ # with the filename and the uptodate function.117+ source, filename, uptodate = self.get_source(environment, name)118+119+ # try to load the code from the bytecode cache if there is a120+ # bytecode cache configured.121+ bcc = environment.bytecode_cache122+ if bcc is not None:123+ bucket = bcc.get_bucket(environment, name, filename, source)124+ code = bucket.code125+126+ # if we don't have code so far (not cached, no longer up to127+ # date) etc. we compile the template128+ if code is None:129+ code = environment.compile(source, name, filename)130+131+ # if the bytecode cache is available and the bucket doesn't132+ # have a code so far, we give the bucket the new code and put133+ # it back to the bytecode cache.134+ if bcc is not None and bucket.code is None:135+ bucket.code = code136+ bcc.set_bucket(bucket)137+138+ return environment.template_class.from_code(139+ environment, code, globals, uptodate140+ )141+142+143+class FileSystemLoader(BaseLoader):144+ """Loads templates from the file system. This loader can find templates145+ in folders on the file system and is the preferred way to load them.146+147+ The loader takes the path to the templates as string, or if multiple148+ locations are wanted a list of them which is then looked up in the149+ given order::150+151+ >>> loader = FileSystemLoader('/path/to/templates')152+ >>> loader = FileSystemLoader(['/path/to/templates', '/other/path'])153+154+ Per default the template encoding is ``'utf-8'`` which can be changed155+ by setting the `encoding` parameter to something else.156+157+ To follow symbolic links, set the *followlinks* parameter to ``True``::158+159+ >>> loader = FileSystemLoader('/path/to/templates', followlinks=True)160+161+ .. versionchanged:: 2.8162+ The ``followlinks`` parameter was added.163+ """164+165+ def __init__(self, searchpath, encoding="utf-8", followlinks=False):166+ if not isinstance(searchpath, abc.Iterable) or isinstance(167+ searchpath, string_types168+ ):169+ searchpath = [searchpath]170+171+ # 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]174+175+ self.encoding = encoding176+ self.followlinks = followlinks177+178+ def get_source(self, environment, template):179+ pieces = split_template_path(template)180+ for searchpath in self.searchpath:181+ filename = path.join(searchpath, *pieces)182+ f = open_if_exists(filename)183+ if f is None:184+ continue185+ try:186+ contents = f.read().decode(self.encoding)187+ finally:188+ f.close()189+190+ mtime = path.getmtime(filename)191+192+ def uptodate():193+ try:194+ return path.getmtime(filename) == mtime195+ except OSError:196+ return False197+198+ return contents, filename, uptodate199+ raise TemplateNotFound(template)200+201+ def list_templates(self):202+ found = set()203+ for searchpath in self.searchpath:204+ walk_dir = os.walk(searchpath, followlinks=self.followlinks)205+ for dirpath, _, filenames in walk_dir:206+ for filename in filenames:207+ template = (208+ os.path.join(dirpath, filename)[len(searchpath) :]209+ .strip(os.path.sep)210+ .replace(os.path.sep, "/")211+ )212+ if template[:2] == "./":213+ template = template[2:]214+ if template not in found:215+ found.add(template)216+ return sorted(found)217+218+219+class PackageLoader(BaseLoader):220+ """Load templates from a directory in a Python package.221+222+ :param package_name: Import name of the package that contains the223+ template directory.224+ :param package_path: Directory within the imported package that225+ contains the templates.226+ :param encoding: Encoding of template files.227+228+ The following example looks up templates in the ``pages`` directory229+ within the ``project.ui`` package.230+231+ .. code-block:: python232+233+ loader = PackageLoader("project.ui", "pages")234+235+ Only packages installed as directories (standard pip behavior) or236+ zip/egg files (less common) are supported. The Python API for237+ introspecting data in packages is too limited to support other238+ installation methods the way this loader requires.239+240+ There is limited support for :pep:`420` namespace packages. The241+ template directory is assumed to only be in one namespace242+ contributor. Zip files contributing to a namespace are not243+ supported.244+245+ .. versionchanged:: 2.11.0246+ No longer uses ``setuptools`` as a dependency.247+248+ .. versionchanged:: 2.11.0249+ Limited PEP 420 namespace package support.250+ """251+252+ def __init__(self, package_name, package_path="templates", encoding="utf-8"):253+ if package_path == os.path.curdir:254+ package_path = ""255+ elif package_path[:2] == os.path.curdir + os.path.sep:256+ package_path = package_path[2:]257+258+ package_path = os.path.normpath(package_path).rstrip(os.path.sep)259+ self.package_path = package_path260+ self.package_name = package_name261+ self.encoding = encoding262+263+ # Make sure the package exists. This also makes namespace264+ # packages work, otherwise get_loader returns None.265+ import_module(package_name)266+ self._loader = loader = pkgutil.get_loader(package_name)267+268+ # Zip loader's archive attribute points at the zip.269+ self._archive = getattr(loader, "archive", None)270+ self._template_root = None271+272+ if hasattr(loader, "get_filename"):273+ # A standard directory package, or a zip package.274+ self._template_root = os.path.join(275+ os.path.dirname(loader.get_filename(package_name)), package_path276+ )277+ elif hasattr(loader, "_path"):278+ # A namespace package, limited support. Find the first279+ # contributor with the template directory.280+ for root in loader._path:281+ root = os.path.join(root, package_path)282+283+ if os.path.isdir(root):284+ self._template_root = root285+ break286+287+ if self._template_root is None:288+ raise ValueError(289+ "The %r package was not installed in a way that"290+ " PackageLoader understands." % package_name291+ )292+293+ def get_source(self, environment, template):294+ p = os.path.join(self._template_root, *split_template_path(template))295+296+ if self._archive is None:297+ # Package is a directory.298+ if not os.path.isfile(p):299+ raise TemplateNotFound(template)300+301+ with open(p, "rb") as f:302+ source = f.read()303+304+ mtime = os.path.getmtime(p)305+306+ def up_to_date():307+ return os.path.isfile(p) and os.path.getmtime(p) == mtime308+309+ else:310+ # Package is a zip file.311+ try:312+ source = self._loader.get_data(p)313+ except OSError:314+ raise TemplateNotFound(template)315+316+ # Could use the zip's mtime for all template mtimes, but317+ # would need to safely reload the module if it's out of318+ # date, so just report it as always current.319+ up_to_date = None320+321+ return source.decode(self.encoding), p, up_to_date322+323+ def list_templates(self):324+ results = []325+326+ if self._archive is None:327+ # Package is a directory.328+ offset = len(self._template_root)329+330+ for dirpath, _, filenames in os.walk(self._template_root):331+ dirpath = dirpath[offset:].lstrip(os.path.sep)332+ results.extend(333+ os.path.join(dirpath, name).replace(os.path.sep, "/")334+ for name in filenames335+ )336+ else:337+ if not hasattr(self._loader, "_files"):338+ raise TypeError(339+ "This zip import does not have the required"340+ " metadata to list templates."341+ )342+343+ # Package is a zip file.344+ prefix = (345+ self._template_root[len(self._archive) :].lstrip(os.path.sep)346+ + os.path.sep347+ )348+ offset = len(prefix)349+350+ for name in self._loader._files.keys():351+ # Find names under the templates directory that aren't directories.352+ if name.startswith(prefix) and name[-1] != os.path.sep:353+ results.append(name[offset:].replace(os.path.sep, "/"))354+355+ results.sort()356+ return results357+358+359+class 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:362+363+ >>> loader = DictLoader({'index.html': 'source here'})364+365+ Because auto reloading is rarely useful this is disabled per default.366+ """367+368+ def __init__(self, mapping):369+ self.mapping = mapping370+371+ def get_source(self, environment, template):372+ if template in self.mapping:373+ source = self.mapping[template]374+ return source, None, lambda: source == self.mapping.get(template)375+ raise TemplateNotFound(template)376+377+ def list_templates(self):378+ return sorted(self.mapping)379+380+381+class FunctionLoader(BaseLoader):382+ """A loader that is passed a function which does the loading. The383+ function receives the name of the template and has to return either384+ an unicode string with the template source, a tuple in the form ``(source,385+ filename, uptodatefunc)`` or `None` if the template does not exist.386+387+ >>> def load_template(name):388+ ... if name == 'index.html':389+ ... return '...'390+ ...391+ >>> loader = FunctionLoader(load_template)392+393+ The `uptodatefunc` is a function that is called if autoreload is enabled394+ and has to return `True` if the template is still up to date. For more395+ details have a look at :meth:`BaseLoader.get_source` which has the same396+ return value.397+ """398+399+ def __init__(self, load_func):400+ self.load_func = load_func401+402+ def get_source(self, environment, template):403+ rv = self.load_func(template)404+ if rv is None:405+ raise TemplateNotFound(template)406+ elif isinstance(rv, string_types):407+ return rv, None, None408+ return rv409+410+411+class PrefixLoader(BaseLoader):412+ """A loader that is passed a dict of loaders where each loader is bound413+ to a prefix. The prefix is delimited from the template by a slash per414+ default, which can be changed by setting the `delimiter` argument to415+ something else::416+417+ loader = PrefixLoader({418+ 'app1': PackageLoader('mypackage.app1'),419+ 'app2': PackageLoader('mypackage.app2')420+ })421+422+ By loading ``'app1/index.html'`` the file from the app1 package is loaded,423+ by loading ``'app2/index.html'`` the file from the second.424+ """425+426+ def __init__(self, mapping, delimiter="/"):427+ self.mapping = mapping428+ self.delimiter = delimiter429+430+ def get_loader(self, template):431+ try:432+ prefix, name = template.split(self.delimiter, 1)433+ loader = self.mapping[prefix]434+ except (ValueError, KeyError):435+ raise TemplateNotFound(template)436+ return loader, name437+438+ def get_source(self, environment, template):439+ loader, name = self.get_loader(template)440+ try:441+ return loader.get_source(environment, name)442+ except TemplateNotFound:443+ # re-raise the exception with the correct filename here.444+ # (the one that includes the prefix)445+ raise TemplateNotFound(template)446+447+ @internalcode448+ def load(self, environment, name, globals=None):449+ loader, local_name = self.get_loader(name)450+ try:451+ return loader.load(environment, local_name, globals)452+ except TemplateNotFound:453+ # re-raise the exception with the correct filename here.454+ # (the one that includes the prefix)455+ raise TemplateNotFound(name)456+457+ def list_templates(self):458+ result = []459+ for prefix, loader in iteritems(self.mapping):460+ for template in loader.list_templates():461+ result.append(prefix + self.delimiter + template)462+ return result463+464+465+class ChoiceLoader(BaseLoader):466+ """This loader works like the `PrefixLoader` just that no prefix is467+ specified. If a template could not be found by one loader the next one468+ is tried.469+470+ >>> loader = ChoiceLoader([471+ ... FileSystemLoader('/path/to/user/templates'),472+ ... FileSystemLoader('/path/to/system/templates')473+ ... ])474+475+ This is useful if you want to allow users to override builtin templates476+ from a different location.477+ """478+479+ def __init__(self, loaders):480+ self.loaders = loaders481+482+ def get_source(self, environment, template):483+ for loader in self.loaders:484+ try:485+ return loader.get_source(environment, template)486+ except TemplateNotFound:487+ pass488+ raise TemplateNotFound(template)489+490+ @internalcode491+ def load(self, environment, name, globals=None):492+ for loader in self.loaders:493+ try:494+ return loader.load(environment, name, globals)495+ except TemplateNotFound:496+ pass497+ raise TemplateNotFound(name)498+499+ def list_templates(self):500+ found = set()501+ for loader in self.loaders:502+ found.update(loader.list_templates())503+ return sorted(found)504+505+506+class _TemplateModule(ModuleType):507+ """Like a normal module but with support for weak references"""508+509+510+class ModuleLoader(BaseLoader):511+ """This loader loads templates from precompiled templates.512+513+ Example usage:514+515+ >>> loader = ChoiceLoader([516+ ... ModuleLoader('/path/to/compiled/templates'),517+ ... FileSystemLoader('/path/to/templates')518+ ... ])519+520+ Templates can be precompiled with :meth:`Environment.compile_templates`.521+ """522+523+ has_source_access = False524+525+ def __init__(self, path):526+ package_name = "_jinja2_module_templates_%x" % id(self)527+528+ # create a fake module that looks for the templates in the529+ # path given.530+ mod = _TemplateModule(package_name)531+532+ if not isinstance(path, abc.Iterable) or isinstance(path, string_types):533+ path = [path]534+535+ mod.__path__ = [fspath(p) for p in path]536+537+ sys.modules[package_name] = weakref.proxy(538+ mod, lambda x: sys.modules.pop(package_name, None)539+ )540+541+ # the only strong reference, the sys.modules entry is weak542+ # so that the garbage collector can remove it once the543+ # loader that created it goes out of business.544+ self.module = mod545+ self.package_name = package_name546+547+ @staticmethod548+ def get_template_key(name):549+ return "tmpl_" + sha1(name.encode("utf-8")).hexdigest()550+551+ @staticmethod552+ def get_module_filename(name):553+ return ModuleLoader.get_template_key(name) + ".py"554+555+ @internalcode556+ def load(self, environment, name, globals=None):557+ key = self.get_template_key(name)558+ module = "%s.%s" % (self.package_name, key)559+ mod = getattr(self.module, module, None)560+ if mod is None:561+ try:562+ mod = __import__(module, None, None, ["root"])563+ except ImportError:564+ raise TemplateNotFound(name)565+566+ # remove the entry from sys.modules, we only want the attribute567+ # on the module object we have stored on the loader.568+ sys.modules.pop(module, None)569+570+ return environment.template_class.from_module_dict(571+ environment, mod.__dict__, globals572+ )added:src/jinja2/meta.py+101 added
1+# -*- coding: utf-8 -*-2+"""Functions that expose information about templates that might be3+interesting for introspection.4+"""5+from . import nodes6+from ._compat import iteritems7+from ._compat import string_types8+from .compiler import CodeGenerator9+10+11+class TrackingCodeGenerator(CodeGenerator):12+ """We abuse the code generator for introspection."""13+14+ def __init__(self, environment):15+ CodeGenerator.__init__(self, environment, "<introspection>", "<introspection>")16+ self.undeclared_identifiers = set()17+18+ def write(self, x):19+ """Don't write."""20+21+ def enter_frame(self, frame):22+ """Remember all undeclared identifiers."""23+ CodeGenerator.enter_frame(self, frame)24+ for _, (action, param) in iteritems(frame.symbols.loads):25+ if action == "resolve" and param not in self.environment.globals:26+ self.undeclared_identifiers.add(param)27+28+29+def find_undeclared_variables(ast):30+ """Returns a set of all variables in the AST that will be looked up from31+ the context at runtime. Because at compile time it's not known which32+ variables will be used depending on the path the execution takes at33+ runtime, all variables are returned.34+35+ >>> from jinja2 import Environment, meta36+ >>> env = Environment()37+ >>> ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')38+ >>> meta.find_undeclared_variables(ast) == set(['bar'])39+ True40+41+ .. admonition:: Implementation42+43+ Internally the code generator is used for finding undeclared variables.44+ This is good to know because the code generator might raise a45+ :exc:`TemplateAssertionError` during compilation and as a matter of46+ fact this function can currently raise that exception as well.47+ """48+ codegen = TrackingCodeGenerator(ast.environment)49+ codegen.visit(ast)50+ return codegen.undeclared_identifiers51+52+53+def find_referenced_templates(ast):54+ """Finds all the referenced templates from the AST. This will return an55+ iterator over all the hardcoded template extensions, inclusions and56+ imports. If dynamic inheritance or inclusion is used, `None` will be57+ yielded.58+59+ >>> from jinja2 import Environment, meta60+ >>> env = Environment()61+ >>> ast = env.parse('{% extends "layout.html" %}{% include helper %}')62+ >>> list(meta.find_referenced_templates(ast))63+ ['layout.html', None]64+65+ This function is useful for dependency tracking. For example if you want66+ to rebuild parts of the website after a layout template has changed.67+ """68+ for node in ast.find_all(69+ (nodes.Extends, nodes.FromImport, nodes.Import, nodes.Include)70+ ):71+ if not isinstance(node.template, nodes.Const):72+ # a tuple with some non consts in there73+ if isinstance(node.template, (nodes.Tuple, nodes.List)):74+ for template_name in node.template.items:75+ # something const, only yield the strings and ignore76+ # non-string consts that really just make no sense77+ if isinstance(template_name, nodes.Const):78+ if isinstance(template_name.value, string_types):79+ yield template_name.value80+ # something dynamic in there81+ else:82+ yield None83+ # something dynamic we don't know about here84+ else:85+ yield None86+ continue87+ # constant is a basestring, direct template name88+ if isinstance(node.template.value, string_types):89+ yield node.template.value90+ # a tuple or list (latter *should* not happen) made of consts,91+ # yield the consts that are strings. We could warn here for92+ # non string values93+ elif isinstance(node, nodes.Include) and isinstance(94+ node.template.value, (tuple, list)95+ ):96+ for template_name in node.template.value:97+ if isinstance(template_name, string_types):98+ yield template_name99+ # something else we don't care about, we could warn here100+ else:101+ yield Noneadded:src/jinja2/nativetypes.py+111 added
1+import types2+from ast import literal_eval3+from itertools import chain4+from itertools import islice5+6+from . import nodes7+from ._compat import text_type8+from .compiler import CodeGenerator9+from .compiler import has_safe_repr10+from .environment import Environment11+from .environment import Template12+13+14+def native_concat(nodes, preserve_quotes=True):15+ """Return a native Python type from the list of compiled nodes. If16+ the result is a single node, its value is returned. Otherwise, the17+ nodes are concatenated as strings. If the result can be parsed with18+ :func:`ast.literal_eval`, the parsed value is returned. Otherwise,19+ the string is returned.20+21+ :param nodes: Iterable of nodes to concatenate.22+ :param preserve_quotes: Whether to re-wrap literal strings with23+ quotes, to preserve quotes around expressions for later parsing.24+ Should be ``False`` in :meth:`NativeEnvironment.render`.25+ """26+ head = list(islice(nodes, 2))27+28+ if not head:29+ return None30+31+ if len(head) == 1:32+ raw = head[0]33+ else:34+ if isinstance(nodes, types.GeneratorType):35+ nodes = chain(head, nodes)36+ raw = u"".join([text_type(v) for v in nodes])37+38+ try:39+ literal = literal_eval(raw)40+ except (ValueError, SyntaxError, MemoryError):41+ return raw42+43+ # If literal_eval returned a string, re-wrap with the original44+ # quote character to avoid dropping quotes between expression nodes.45+ # Without this, "'{{ a }}', '{{ b }}'" results in "a, b", but should46+ # be ('a', 'b').47+ if preserve_quotes and isinstance(literal, str):48+ return "{quote}{}{quote}".format(literal, quote=raw[0])49+50+ return literal51+52+53+class NativeCodeGenerator(CodeGenerator):54+ """A code generator which renders Python types by not adding55+ ``to_string()`` around output nodes, and using :func:`native_concat`56+ to convert complex strings back to Python types if possible.57+ """58+59+ @staticmethod60+ def _default_finalize(value):61+ return value62+63+ def _output_const_repr(self, group):64+ return repr(native_concat(group))65+66+ def _output_child_to_const(self, node, frame, finalize):67+ const = node.as_const(frame.eval_ctx)68+69+ if not has_safe_repr(const):70+ raise nodes.Impossible()71+72+ if isinstance(node, nodes.TemplateData):73+ return const74+75+ return finalize.const(const)76+77+ def _output_child_pre(self, node, frame, finalize):78+ if finalize.src is not None:79+ self.write(finalize.src)80+81+ def _output_child_post(self, node, frame, finalize):82+ if finalize.src is not None:83+ self.write(")")84+85+86+class NativeEnvironment(Environment):87+ """An environment that renders templates to native Python types."""88+89+ code_generator_class = NativeCodeGenerator90+91+92+class NativeTemplate(Template):93+ environment_class = NativeEnvironment94+95+ def render(self, *args, **kwargs):96+ """Render the template to produce a native Python type. If the97+ result is a single node, its value is returned. Otherwise, the98+ nodes are concatenated as strings. If the result can be parsed99+ with :func:`ast.literal_eval`, the parsed value is returned.100+ Otherwise, the string is returned.101+ """102+ vars = dict(*args, **kwargs)103+ try:104+ return native_concat(105+ self.root_render_func(self.new_context(vars)), preserve_quotes=False106+ )107+ except Exception:108+ return self.environment.handle_exception()109+110+111+NativeEnvironment.template_class = NativeTemplateadded:src/jinja2/nodes.py+1087 added
1+# -*- coding: utf-8 -*-2+"""AST nodes generated by the parser for the compiler. Also provides3+some node tree helper functions used by the parser and compiler in order4+to normalize nodes.5+"""6+import operator7+from collections import deque8+9+from ._compat import izip10+from ._compat import PY211+from ._compat import text_type12+from ._compat import with_metaclass13+from .utils import Markup14+15+_binop_to_func = {16+ "*": operator.mul,17+ "/": operator.truediv,18+ "//": operator.floordiv,19+ "**": operator.pow,20+ "%": operator.mod,21+ "+": operator.add,22+ "-": operator.sub,23+}24+25+_uaop_to_func = {"not": operator.not_, "+": operator.pos, "-": operator.neg}26+27+_cmpop_to_func = {28+ "eq": operator.eq,29+ "ne": operator.ne,30+ "gt": operator.gt,31+ "gteq": operator.ge,32+ "lt": operator.lt,33+ "lteq": operator.le,34+ "in": lambda a, b: a in b,35+ "notin": lambda a, b: a not in b,36+}37+38+39+class Impossible(Exception):40+ """Raised if the node could not perform a requested action."""41+42+43+class NodeType(type):44+ """A metaclass for nodes that handles the field and attribute45+ inheritance. fields and attributes from the parent class are46+ automatically forwarded to the child."""47+48+ def __new__(mcs, name, bases, d):49+ for attr in "fields", "attributes":50+ storage = []51+ storage.extend(getattr(bases[0], attr, ()))52+ storage.extend(d.get(attr, ()))53+ assert len(bases) == 1, "multiple inheritance not allowed"54+ assert len(storage) == len(set(storage)), "layout conflict"55+ d[attr] = tuple(storage)56+ d.setdefault("abstract", False)57+ return type.__new__(mcs, name, bases, d)58+59+60+class EvalContext(object):61+ """Holds evaluation time information. Custom attributes can be attached62+ to it in extensions.63+ """64+65+ def __init__(self, environment, template_name=None):66+ self.environment = environment67+ if callable(environment.autoescape):68+ self.autoescape = environment.autoescape(template_name)69+ else:70+ self.autoescape = environment.autoescape71+ self.volatile = False72+73+ def save(self):74+ return self.__dict__.copy()75+76+ def revert(self, old):77+ self.__dict__.clear()78+ self.__dict__.update(old)79+80+81+def get_eval_context(node, ctx):82+ if ctx is None:83+ if node.environment is None:84+ raise RuntimeError(85+ "if no eval context is passed, the "86+ "node must have an attached "87+ "environment."88+ )89+ return EvalContext(node.environment)90+ return ctx91+92+93+class Node(with_metaclass(NodeType, object)):94+ """Baseclass for all Jinja nodes. There are a number of nodes available95+ of different types. There are four major types:96+97+ - :class:`Stmt`: statements98+ - :class:`Expr`: expressions99+ - :class:`Helper`: helper nodes100+ - :class:`Template`: the outermost wrapper node101+102+ All nodes have fields and attributes. Fields may be other nodes, lists,103+ or arbitrary values. Fields are passed to the constructor as regular104+ positional arguments, attributes as keyword arguments. Each node has105+ two attributes: `lineno` (the line number of the node) and `environment`.106+ The `environment` attribute is set at the end of the parsing process for107+ all nodes automatically.108+ """109+110+ fields = ()111+ attributes = ("lineno", "environment")112+ abstract = True113+114+ def __init__(self, *fields, **attributes):115+ if self.abstract:116+ raise TypeError("abstract nodes are not instantiable")117+ if fields:118+ if len(fields) != len(self.fields):119+ if not self.fields:120+ raise TypeError("%r takes 0 arguments" % self.__class__.__name__)121+ raise TypeError(122+ "%r takes 0 or %d argument%s"123+ % (124+ self.__class__.__name__,125+ len(self.fields),126+ len(self.fields) != 1 and "s" or "",127+ )128+ )129+ for name, arg in izip(self.fields, fields):130+ setattr(self, name, arg)131+ for attr in self.attributes:132+ setattr(self, attr, attributes.pop(attr, None))133+ if attributes:134+ raise TypeError("unknown attribute %r" % next(iter(attributes)))135+136+ def iter_fields(self, exclude=None, only=None):137+ """This method iterates over all fields that are defined and yields138+ ``(key, value)`` tuples. Per default all fields are returned, but139+ it's possible to limit that to some fields by providing the `only`140+ parameter or to exclude some using the `exclude` parameter. Both141+ should be sets or tuples of field names.142+ """143+ for name in self.fields:144+ if (145+ (exclude is only is None)146+ or (exclude is not None and name not in exclude)147+ or (only is not None and name in only)148+ ):149+ try:150+ yield name, getattr(self, name)151+ except AttributeError:152+ pass153+154+ def iter_child_nodes(self, exclude=None, only=None):155+ """Iterates over all direct child nodes of the node. This iterates156+ over all fields and yields the values of they are nodes. If the value157+ of a field is a list all the nodes in that list are returned.158+ """159+ for _, item in self.iter_fields(exclude, only):160+ if isinstance(item, list):161+ for n in item:162+ if isinstance(n, Node):163+ yield n164+ elif isinstance(item, Node):165+ yield item166+167+ def find(self, node_type):168+ """Find the first node of a given type. If no such node exists the169+ return value is `None`.170+ """171+ for result in self.find_all(node_type):172+ return result173+174+ def find_all(self, node_type):175+ """Find all the nodes of a given type. If the type is a tuple,176+ the check is performed for any of the tuple items.177+ """178+ for child in self.iter_child_nodes():179+ if isinstance(child, node_type):180+ yield child181+ for result in child.find_all(node_type):182+ yield result183+184+ def set_ctx(self, ctx):185+ """Reset the context of a node and all child nodes. Per default the186+ parser will all generate nodes that have a 'load' context as it's the187+ most common one. This method is used in the parser to set assignment188+ targets and other nodes to a store context.189+ """190+ todo = deque([self])191+ while todo:192+ node = todo.popleft()193+ if "ctx" in node.fields:194+ node.ctx = ctx195+ todo.extend(node.iter_child_nodes())196+ return self197+198+ def set_lineno(self, lineno, override=False):199+ """Set the line numbers of the node and children."""200+ todo = deque([self])201+ while todo:202+ node = todo.popleft()203+ if "lineno" in node.attributes:204+ if node.lineno is None or override:205+ node.lineno = lineno206+ todo.extend(node.iter_child_nodes())207+ return self208+209+ def set_environment(self, environment):210+ """Set the environment for all nodes."""211+ todo = deque([self])212+ while todo:213+ node = todo.popleft()214+ node.environment = environment215+ todo.extend(node.iter_child_nodes())216+ return self217+218+ def __eq__(self, other):219+ return type(self) is type(other) and tuple(self.iter_fields()) == tuple(220+ other.iter_fields()221+ )222+223+ def __ne__(self, other):224+ return not self.__eq__(other)225+226+ # Restore Python 2 hashing behavior on Python 3227+ __hash__ = object.__hash__228+229+ def __repr__(self):230+ return "%s(%s)" % (231+ self.__class__.__name__,232+ ", ".join("%s=%r" % (arg, getattr(self, arg, None)) for arg in self.fields),233+ )234+235+ def dump(self):236+ def _dump(node):237+ if not isinstance(node, Node):238+ buf.append(repr(node))239+ return240+241+ buf.append("nodes.%s(" % node.__class__.__name__)242+ if not node.fields:243+ buf.append(")")244+ return245+ for idx, field in enumerate(node.fields):246+ if idx:247+ buf.append(", ")248+ value = getattr(node, field)249+ if isinstance(value, list):250+ buf.append("[")251+ for idx, item in enumerate(value):252+ if idx:253+ buf.append(", ")254+ _dump(item)255+ buf.append("]")256+ else:257+ _dump(value)258+ buf.append(")")259+260+ buf = []261+ _dump(self)262+ return "".join(buf)263+264+265+class Stmt(Node):266+ """Base node for all statements."""267+268+ abstract = True269+270+271+class Helper(Node):272+ """Nodes that exist in a specific context only."""273+274+ abstract = True275+276+277+class Template(Node):278+ """Node that represents a template. This must be the outermost node that279+ is passed to the compiler.280+ """281+282+ fields = ("body",)283+284+285+class Output(Stmt):286+ """A node that holds multiple expressions which are then printed out.287+ This is used both for the `print` statement and the regular template data.288+ """289+290+ fields = ("nodes",)291+292+293+class Extends(Stmt):294+ """Represents an extends statement."""295+296+ fields = ("template",)297+298+299+class For(Stmt):300+ """The for loop. `target` is the target for the iteration (usually a301+ :class:`Name` or :class:`Tuple`), `iter` the iterable. `body` is a list302+ of nodes that are used as loop-body, and `else_` a list of nodes for the303+ `else` block. If no else node exists it has to be an empty list.304+305+ For filtered nodes an expression can be stored as `test`, otherwise `None`.306+ """307+308+ fields = ("target", "iter", "body", "else_", "test", "recursive")309+310+311+class If(Stmt):312+ """If `test` is true, `body` is rendered, else `else_`."""313+314+ fields = ("test", "body", "elif_", "else_")315+316+317+class Macro(Stmt):318+ """A macro definition. `name` is the name of the macro, `args` a list of319+ arguments and `defaults` a list of defaults if there are any. `body` is320+ a list of nodes for the macro body.321+ """322+323+ fields = ("name", "args", "defaults", "body")324+325+326+class CallBlock(Stmt):327+ """Like a macro without a name but a call instead. `call` is called with328+ the unnamed macro as `caller` argument this node holds.329+ """330+331+ fields = ("call", "args", "defaults", "body")332+333+334+class FilterBlock(Stmt):335+ """Node for filter sections."""336+337+ fields = ("body", "filter")338+339+340+class With(Stmt):341+ """Specific node for with statements. In older versions of Jinja the342+ with statement was implemented on the base of the `Scope` node instead.343+344+ .. versionadded:: 2.9.3345+ """346+347+ fields = ("targets", "values", "body")348+349+350+class Block(Stmt):351+ """A node that represents a block."""352+353+ fields = ("name", "body", "scoped")354+355+356+class Include(Stmt):357+ """A node that represents the include tag."""358+359+ fields = ("template", "with_context", "ignore_missing")360+361+362+class Import(Stmt):363+ """A node that represents the import tag."""364+365+ fields = ("template", "target", "with_context")366+367+368+class FromImport(Stmt):369+ """A node that represents the from import tag. It's important to not370+ pass unsafe names to the name attribute. The compiler translates the371+ attribute lookups directly into getattr calls and does *not* use the372+ subscript callback of the interface. As exported variables may not373+ start with double underscores (which the parser asserts) this is not a374+ problem for regular Jinja code, but if this node is used in an extension375+ extra care must be taken.376+377+ The list of names may contain tuples if aliases are wanted.378+ """379+380+ fields = ("template", "names", "with_context")381+382+383+class ExprStmt(Stmt):384+ """A statement that evaluates an expression and discards the result."""385+386+ fields = ("node",)387+388+389+class Assign(Stmt):390+ """Assigns an expression to a target."""391+392+ fields = ("target", "node")393+394+395+class AssignBlock(Stmt):396+ """Assigns a block to a target."""397+398+ fields = ("target", "filter", "body")399+400+401+class Expr(Node):402+ """Baseclass for all expressions."""403+404+ abstract = True405+406+ def as_const(self, eval_ctx=None):407+ """Return the value of the expression as constant or raise408+ :exc:`Impossible` if this was not possible.409+410+ An :class:`EvalContext` can be provided, if none is given411+ a default context is created which requires the nodes to have412+ an attached environment.413+414+ .. versionchanged:: 2.4415+ the `eval_ctx` parameter was added.416+ """417+ raise Impossible()418+419+ def can_assign(self):420+ """Check if it's possible to assign something to this node."""421+ return False422+423+424+class BinExpr(Expr):425+ """Baseclass for all binary expressions."""426+427+ fields = ("left", "right")428+ operator = None429+ abstract = True430+431+ def as_const(self, eval_ctx=None):432+ eval_ctx = get_eval_context(self, eval_ctx)433+ # intercepted operators cannot be folded at compile time434+ if (435+ self.environment.sandboxed436+ and self.operator in self.environment.intercepted_binops437+ ):438+ raise Impossible()439+ f = _binop_to_func[self.operator]440+ try:441+ return f(self.left.as_const(eval_ctx), self.right.as_const(eval_ctx))442+ except Exception:443+ raise Impossible()444+445+446+class UnaryExpr(Expr):447+ """Baseclass for all unary expressions."""448+449+ fields = ("node",)450+ operator = None451+ abstract = True452+453+ def as_const(self, eval_ctx=None):454+ eval_ctx = get_eval_context(self, eval_ctx)455+ # intercepted operators cannot be folded at compile time456+ if (457+ self.environment.sandboxed458+ and self.operator in self.environment.intercepted_unops459+ ):460+ raise Impossible()461+ f = _uaop_to_func[self.operator]462+ try:463+ return f(self.node.as_const(eval_ctx))464+ except Exception:465+ raise Impossible()466+467+468+class Name(Expr):469+ """Looks up a name or stores a value in a name.470+ The `ctx` of the node can be one of the following values:471+472+ - `store`: store a value in the name473+ - `load`: load that name474+ - `param`: like `store` but if the name was defined as function parameter.475+ """476+477+ fields = ("name", "ctx")478+479+ def can_assign(self):480+ return self.name not in ("true", "false", "none", "True", "False", "None")481+482+483+class NSRef(Expr):484+ """Reference to a namespace value assignment"""485+486+ fields = ("name", "attr")487+488+ def can_assign(self):489+ # We don't need any special checks here; NSRef assignments have a490+ # runtime check to ensure the target is a namespace object which will491+ # have been checked already as it is created using a normal assignment492+ # which goes through a `Name` node.493+ return True494+495+496+class Literal(Expr):497+ """Baseclass for literals."""498+499+ abstract = True500+501+502+class Const(Literal):503+ """All constant values. The parser will return this node for simple504+ constants such as ``42`` or ``"foo"`` but it can be used to store more505+ complex values such as lists too. Only constants with a safe506+ representation (objects where ``eval(repr(x)) == x`` is true).507+ """508+509+ fields = ("value",)510+511+ def as_const(self, eval_ctx=None):512+ rv = self.value513+ if (514+ PY2515+ and type(rv) is text_type516+ and self.environment.policies["compiler.ascii_str"]517+ ):518+ try:519+ rv = rv.encode("ascii")520+ except UnicodeError:521+ pass522+ return rv523+524+ @classmethod525+ def from_untrusted(cls, value, lineno=None, environment=None):526+ """Return a const object if the value is representable as527+ constant value in the generated code, otherwise it will raise528+ an `Impossible` exception.529+ """530+ from .compiler import has_safe_repr531+532+ if not has_safe_repr(value):533+ raise Impossible()534+ return cls(value, lineno=lineno, environment=environment)535+536+537+class TemplateData(Literal):538+ """A constant template string."""539+540+ fields = ("data",)541+542+ def as_const(self, eval_ctx=None):543+ eval_ctx = get_eval_context(self, eval_ctx)544+ if eval_ctx.volatile:545+ raise Impossible()546+ if eval_ctx.autoescape:547+ return Markup(self.data)548+ return self.data549+550+551+class Tuple(Literal):552+ """For loop unpacking and some other things like multiple arguments553+ for subscripts. Like for :class:`Name` `ctx` specifies if the tuple554+ is used for loading the names or storing.555+ """556+557+ fields = ("items", "ctx")558+559+ def as_const(self, eval_ctx=None):560+ eval_ctx = get_eval_context(self, eval_ctx)561+ return tuple(x.as_const(eval_ctx) for x in self.items)562+563+ def can_assign(self):564+ for item in self.items:565+ if not item.can_assign():566+ return False567+ return True568+569+570+class List(Literal):571+ """Any list literal such as ``[1, 2, 3]``"""572+573+ fields = ("items",)574+575+ def as_const(self, eval_ctx=None):576+ eval_ctx = get_eval_context(self, eval_ctx)577+ return [x.as_const(eval_ctx) for x in self.items]578+579+580+class Dict(Literal):581+ """Any dict literal such as ``{1: 2, 3: 4}``. The items must be a list of582+ :class:`Pair` nodes.583+ """584+585+ fields = ("items",)586+587+ def as_const(self, eval_ctx=None):588+ eval_ctx = get_eval_context(self, eval_ctx)589+ return dict(x.as_const(eval_ctx) for x in self.items)590+591+592+class Pair(Helper):593+ """A key, value pair for dicts."""594+595+ fields = ("key", "value")596+597+ def as_const(self, eval_ctx=None):598+ eval_ctx = get_eval_context(self, eval_ctx)599+ return self.key.as_const(eval_ctx), self.value.as_const(eval_ctx)600+601+602+class Keyword(Helper):603+ """A key, value pair for keyword arguments where key is a string."""604+605+ fields = ("key", "value")606+607+ def as_const(self, eval_ctx=None):608+ eval_ctx = get_eval_context(self, eval_ctx)609+ return self.key, self.value.as_const(eval_ctx)610+611+612+class CondExpr(Expr):613+ """A conditional expression (inline if expression). (``{{614+ foo if bar else baz }}``)615+ """616+617+ fields = ("test", "expr1", "expr2")618+619+ def as_const(self, eval_ctx=None):620+ eval_ctx = get_eval_context(self, eval_ctx)621+ if self.test.as_const(eval_ctx):622+ return self.expr1.as_const(eval_ctx)623+624+ # if we evaluate to an undefined object, we better do that at runtime625+ if self.expr2 is None:626+ raise Impossible()627+628+ return self.expr2.as_const(eval_ctx)629+630+631+def args_as_const(node, eval_ctx):632+ args = [x.as_const(eval_ctx) for x in node.args]633+ kwargs = dict(x.as_const(eval_ctx) for x in node.kwargs)634+635+ if node.dyn_args is not None:636+ try:637+ args.extend(node.dyn_args.as_const(eval_ctx))638+ except Exception:639+ raise Impossible()640+641+ if node.dyn_kwargs is not None:642+ try:643+ kwargs.update(node.dyn_kwargs.as_const(eval_ctx))644+ except Exception:645+ raise Impossible()646+647+ return args, kwargs648+649+650+class Filter(Expr):651+ """This node applies a filter on an expression. `name` is the name of652+ the filter, the rest of the fields are the same as for :class:`Call`.653+654+ If the `node` of a filter is `None` the contents of the last buffer are655+ filtered. Buffers are created by macros and filter blocks.656+ """657+658+ fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")659+660+ def as_const(self, eval_ctx=None):661+ eval_ctx = get_eval_context(self, eval_ctx)662+663+ if eval_ctx.volatile or self.node is None:664+ raise Impossible()665+666+ # we have to be careful here because we call filter_ below.667+ # if this variable would be called filter, 2to3 would wrap the668+ # call in a list because it is assuming we are talking about the669+ # builtin filter function here which no longer returns a list in670+ # python 3. because of that, do not rename filter_ to filter!671+ filter_ = self.environment.filters.get(self.name)672+673+ if filter_ is None or getattr(filter_, "contextfilter", False):674+ raise Impossible()675+676+ # We cannot constant handle async filters, so we need to make sure677+ # to not go down this path.678+ if eval_ctx.environment.is_async and getattr(679+ filter_, "asyncfiltervariant", False680+ ):681+ raise Impossible()682+683+ args, kwargs = args_as_const(self, eval_ctx)684+ args.insert(0, self.node.as_const(eval_ctx))685+686+ if getattr(filter_, "evalcontextfilter", False):687+ args.insert(0, eval_ctx)688+ elif getattr(filter_, "environmentfilter", False):689+ args.insert(0, self.environment)690+691+ try:692+ return filter_(*args, **kwargs)693+ except Exception:694+ raise Impossible()695+696+697+class Test(Expr):698+ """Applies a test on an expression. `name` is the name of the test, the699+ rest of the fields are the same as for :class:`Call`.700+ """701+702+ fields = ("node", "name", "args", "kwargs", "dyn_args", "dyn_kwargs")703+704+ def as_const(self, eval_ctx=None):705+ test = self.environment.tests.get(self.name)706+707+ if test is None:708+ raise Impossible()709+710+ eval_ctx = get_eval_context(self, eval_ctx)711+ args, kwargs = args_as_const(self, eval_ctx)712+ args.insert(0, self.node.as_const(eval_ctx))713+714+ try:715+ return test(*args, **kwargs)716+ except Exception:717+ raise Impossible()718+719+720+class Call(Expr):721+ """Calls an expression. `args` is a list of arguments, `kwargs` a list722+ of keyword arguments (list of :class:`Keyword` nodes), and `dyn_args`723+ and `dyn_kwargs` has to be either `None` or a node that is used as724+ node for dynamic positional (``*args``) or keyword (``**kwargs``)725+ arguments.726+ """727+728+ fields = ("node", "args", "kwargs", "dyn_args", "dyn_kwargs")729+730+731+class Getitem(Expr):732+ """Get an attribute or item from an expression and prefer the item."""733+734+ fields = ("node", "arg", "ctx")735+736+ def as_const(self, eval_ctx=None):737+ eval_ctx = get_eval_context(self, eval_ctx)738+ if self.ctx != "load":739+ raise Impossible()740+ try:741+ return self.environment.getitem(742+ self.node.as_const(eval_ctx), self.arg.as_const(eval_ctx)743+ )744+ except Exception:745+ raise Impossible()746+747+ def can_assign(self):748+ return False749+750+751+class Getattr(Expr):752+ """Get an attribute or item from an expression that is a ascii-only753+ bytestring and prefer the attribute.754+ """755+756+ fields = ("node", "attr", "ctx")757+758+ def as_const(self, eval_ctx=None):759+ if self.ctx != "load":760+ raise Impossible()761+ try:762+ eval_ctx = get_eval_context(self, eval_ctx)763+ return self.environment.getattr(self.node.as_const(eval_ctx), self.attr)764+ except Exception:765+ raise Impossible()766+767+ def can_assign(self):768+ return False769+770+771+class Slice(Expr):772+ """Represents a slice object. This must only be used as argument for773+ :class:`Subscript`.774+ """775+776+ fields = ("start", "stop", "step")777+778+ def as_const(self, eval_ctx=None):779+ eval_ctx = get_eval_context(self, eval_ctx)780+781+ def const(obj):782+ if obj is None:783+ return None784+ return obj.as_const(eval_ctx)785+786+ return slice(const(self.start), const(self.stop), const(self.step))787+788+789+class Concat(Expr):790+ """Concatenates the list of expressions provided after converting them to791+ unicode.792+ """793+794+ fields = ("nodes",)795+796+ def as_const(self, eval_ctx=None):797+ eval_ctx = get_eval_context(self, eval_ctx)798+ return "".join(text_type(x.as_const(eval_ctx)) for x in self.nodes)799+800+801+class Compare(Expr):802+ """Compares an expression with some other expressions. `ops` must be a803+ list of :class:`Operand`\\s.804+ """805+806+ fields = ("expr", "ops")807+808+ def as_const(self, eval_ctx=None):809+ eval_ctx = get_eval_context(self, eval_ctx)810+ result = value = self.expr.as_const(eval_ctx)811+812+ try:813+ for op in self.ops:814+ new_value = op.expr.as_const(eval_ctx)815+ result = _cmpop_to_func[op.op](value, new_value)816+817+ if not result:818+ return False819+820+ value = new_value821+ except Exception:822+ raise Impossible()823+824+ return result825+826+827+class Operand(Helper):828+ """Holds an operator and an expression."""829+830+ fields = ("op", "expr")831+832+833+if __debug__:834+ Operand.__doc__ += "\nThe following operators are available: " + ", ".join(835+ sorted(836+ "``%s``" % x837+ for x in set(_binop_to_func) | set(_uaop_to_func) | set(_cmpop_to_func)838+ )839+ )840+841+842+class Mul(BinExpr):843+ """Multiplies the left with the right node."""844+845+ operator = "*"846+847+848+class Div(BinExpr):849+ """Divides the left by the right node."""850+851+ operator = "/"852+853+854+class FloorDiv(BinExpr):855+ """Divides the left by the right node and truncates conver the856+ result into an integer by truncating.857+ """858+859+ operator = "//"860+861+862+class Add(BinExpr):863+ """Add the left to the right node."""864+865+ operator = "+"866+867+868+class Sub(BinExpr):869+ """Subtract the right from the left node."""870+871+ operator = "-"872+873+874+class Mod(BinExpr):875+ """Left modulo right."""876+877+ operator = "%"878+879+880+class Pow(BinExpr):881+ """Left to the power of right."""882+883+ operator = "**"884+885+886+class And(BinExpr):887+ """Short circuited AND."""888+889+ operator = "and"890+891+ def as_const(self, eval_ctx=None):892+ eval_ctx = get_eval_context(self, eval_ctx)893+ return self.left.as_const(eval_ctx) and self.right.as_const(eval_ctx)894+895+896+class Or(BinExpr):897+ """Short circuited OR."""898+899+ operator = "or"900+901+ def as_const(self, eval_ctx=None):902+ eval_ctx = get_eval_context(self, eval_ctx)903+ return self.left.as_const(eval_ctx) or self.right.as_const(eval_ctx)904+905+906+class Not(UnaryExpr):907+ """Negate the expression."""908+909+ operator = "not"910+911+912+class Neg(UnaryExpr):913+ """Make the expression negative."""914+915+ operator = "-"916+917+918+class Pos(UnaryExpr):919+ """Make the expression positive (noop for most expressions)"""920+921+ operator = "+"922+923+924+# Helpers for extensions925+926+927+class EnvironmentAttribute(Expr):928+ """Loads an attribute from the environment object. This is useful for929+ extensions that want to call a callback stored on the environment.930+ """931+932+ fields = ("name",)933+934+935+class ExtensionAttribute(Expr):936+ """Returns the attribute of an extension bound to the environment.937+ The identifier is the identifier of the :class:`Extension`.938+939+ This node is usually constructed by calling the940+ :meth:`~jinja2.ext.Extension.attr` method on an extension.941+ """942+943+ fields = ("identifier", "name")944+945+946+class ImportedName(Expr):947+ """If created with an import name the import name is returned on node948+ access. For example ``ImportedName('cgi.escape')`` returns the `escape`949+ function from the cgi module on evaluation. Imports are optimized by the950+ compiler so there is no need to assign them to local variables.951+ """952+953+ fields = ("importname",)954+955+956+class InternalName(Expr):957+ """An internal name in the compiler. You cannot create these nodes958+ yourself but the parser provides a959+ :meth:`~jinja2.parser.Parser.free_identifier` method that creates960+ a new identifier for you. This identifier is not available from the961+ template and is not threated specially by the compiler.962+ """963+964+ fields = ("name",)965+966+ def __init__(self):967+ raise TypeError(968+ "Can't create internal names. Use the "969+ "`free_identifier` method on a parser."970+ )971+972+973+class MarkSafe(Expr):974+ """Mark the wrapped expression as safe (wrap it as `Markup`)."""975+976+ fields = ("expr",)977+978+ def as_const(self, eval_ctx=None):979+ eval_ctx = get_eval_context(self, eval_ctx)980+ return Markup(self.expr.as_const(eval_ctx))981+982+983+class MarkSafeIfAutoescape(Expr):984+ """Mark the wrapped expression as safe (wrap it as `Markup`) but985+ only if autoescaping is active.986+987+ .. versionadded:: 2.5988+ """989+990+ fields = ("expr",)991+992+ def as_const(self, eval_ctx=None):993+ eval_ctx = get_eval_context(self, eval_ctx)994+ if eval_ctx.volatile:995+ raise Impossible()996+ expr = self.expr.as_const(eval_ctx)997+ if eval_ctx.autoescape:998+ return Markup(expr)999+ return expr1000+1001+1002+class ContextReference(Expr):1003+ """Returns the current template context. It can be used like a1004+ :class:`Name` node, with a ``'load'`` ctx and will return the1005+ current :class:`~jinja2.runtime.Context` object.1006+1007+ Here an example that assigns the current template name to a1008+ variable named `foo`::1009+1010+ Assign(Name('foo', ctx='store'),1011+ Getattr(ContextReference(), 'name'))1012+1013+ This is basically equivalent to using the1014+ :func:`~jinja2.contextfunction` decorator when using the1015+ high-level API, which causes a reference to the context to be passed1016+ as the first argument to a function.1017+ """1018+1019+1020+class DerivedContextReference(Expr):1021+ """Return the current template context including locals. Behaves1022+ exactly like :class:`ContextReference`, but includes local1023+ variables, such as from a ``for`` loop.1024+1025+ .. versionadded:: 2.111026+ """1027+1028+1029+class Continue(Stmt):1030+ """Continue a loop."""1031+1032+1033+class Break(Stmt):1034+ """Break a loop."""1035+1036+1037+class Scope(Stmt):1038+ """An artificial scope."""1039+1040+ fields = ("body",)1041+1042+1043+class OverlayScope(Stmt):1044+ """An overlay scope for extensions. This is a largely unoptimized scope1045+ that however can be used to introduce completely arbitrary variables into1046+ a sub scope from a dictionary or dictionary like object. The `context`1047+ field has to evaluate to a dictionary object.1048+1049+ Example usage::1050+1051+ OverlayScope(context=self.call_method('get_context'),1052+ body=[...])1053+1054+ .. versionadded:: 2.101055+ """1056+1057+ fields = ("context", "body")1058+1059+1060+class EvalContextModifier(Stmt):1061+ """Modifies the eval context. For each option that should be modified,1062+ a :class:`Keyword` has to be added to the :attr:`options` list.1063+1064+ Example to change the `autoescape` setting::1065+1066+ EvalContextModifier(options=[Keyword('autoescape', Const(True))])1067+ """1068+1069+ fields = ("options",)1070+1071+1072+class ScopedEvalContextModifier(EvalContextModifier):1073+ """Modifies the eval context and reverts it later. Works exactly like1074+ :class:`EvalContextModifier` but will only modify the1075+ :class:`~jinja2.nodes.EvalContext` for nodes in the :attr:`body`.1076+ """1077+1078+ fields = ("body",)1079+1080+1081+# make sure nobody creates custom nodes1082+def _failing_new(*args, **kwargs):1083+ raise TypeError("can't create custom node types")1084+1085+1086+NodeType.__new__ = staticmethod(_failing_new)1087+del _failing_newadded:src/jinja2/optimizer.py+41 added
1+# -*- coding: utf-8 -*-2+"""The optimizer tries to constant fold expressions and modify the AST3+in place so that it should be faster to evaluate.4+5+Because the AST does not contain all the scoping information and the6+compiler has to find that out, we cannot do all the optimizations we7+want. For example, loop unrolling doesn't work because unrolled loops8+would have a different scope. The solution would be a second syntax tree9+that stored the scoping rules.10+"""11+from . import nodes12+from .visitor import NodeTransformer13+14+15+def optimize(node, environment):16+ """The context hint can be used to perform an static optimization17+ based on the context given."""18+ optimizer = Optimizer(environment)19+ return optimizer.visit(node)20+21+22+class Optimizer(NodeTransformer):23+ def __init__(self, environment):24+ self.environment = environment25+26+ def generic_visit(self, node, *args, **kwargs):27+ node = super(Optimizer, self).generic_visit(node, *args, **kwargs)28+29+ # Do constant folding. Some other nodes besides Expr have30+ # as_const, but folding them causes errors later on.31+ if isinstance(node, nodes.Expr):32+ try:33+ return nodes.Const.from_untrusted(34+ node.as_const(args[0] if args else None),35+ lineno=node.lineno,36+ environment=self.environment,37+ )38+ except nodes.Impossible:39+ pass40+41+ return nodeadded:src/jinja2/parser.py+939 added
1+# -*- coding: utf-8 -*-2+"""Parse tokens from the lexer into nodes for the compiler."""3+from . import nodes4+from ._compat import imap5+from .exceptions import TemplateAssertionError6+from .exceptions import TemplateSyntaxError7+from .lexer import describe_token8+from .lexer import describe_token_expr9+10+_statement_keywords = frozenset(11+ [12+ "for",13+ "if",14+ "block",15+ "extends",16+ "print",17+ "macro",18+ "include",19+ "from",20+ "import",21+ "set",22+ "with",23+ "autoescape",24+ ]25+)26+_compare_operators = frozenset(["eq", "ne", "lt", "lteq", "gt", "gteq"])27+28+_math_nodes = {29+ "add": nodes.Add,30+ "sub": nodes.Sub,31+ "mul": nodes.Mul,32+ "div": nodes.Div,33+ "floordiv": nodes.FloorDiv,34+ "mod": nodes.Mod,35+}36+37+38+class Parser(object):39+ """This is the central parsing class Jinja uses. It's passed to40+ extensions and can be used to parse expressions or statements.41+ """42+43+ def __init__(self, environment, source, name=None, filename=None, state=None):44+ self.environment = environment45+ self.stream = environment._tokenize(source, name, filename, state)46+ self.name = name47+ self.filename = filename48+ self.closed = False49+ self.extensions = {}50+ for extension in environment.iter_extensions():51+ for tag in extension.tags:52+ self.extensions[tag] = extension.parse53+ self._last_identifier = 054+ self._tag_stack = []55+ self._end_token_stack = []56+57+ def fail(self, msg, lineno=None, exc=TemplateSyntaxError):58+ """Convenience method that raises `exc` with the message, passed59+ line number or last line number as well as the current name and60+ filename.61+ """62+ if lineno is None:63+ lineno = self.stream.current.lineno64+ raise exc(msg, lineno, self.name, self.filename)65+66+ def _fail_ut_eof(self, name, end_token_stack, lineno):67+ expected = []68+ for exprs in end_token_stack:69+ expected.extend(imap(describe_token_expr, exprs))70+ if end_token_stack:71+ currently_looking = " or ".join(72+ "'%s'" % describe_token_expr(expr) for expr in end_token_stack[-1]73+ )74+ else:75+ currently_looking = None76+77+ if name is None:78+ message = ["Unexpected end of template."]79+ else:80+ message = ["Encountered unknown tag '%s'." % name]81+82+ if currently_looking:83+ if name is not None and name in expected:84+ message.append(85+ "You probably made a nesting mistake. Jinja "86+ "is expecting this tag, but currently looking "87+ "for %s." % currently_looking88+ )89+ else:90+ message.append(91+ "Jinja was looking for the following tags: "92+ "%s." % currently_looking93+ )94+95+ if self._tag_stack:96+ message.append(97+ "The innermost block that needs to be "98+ "closed is '%s'." % self._tag_stack[-1]99+ )100+101+ self.fail(" ".join(message), lineno)102+103+ def fail_unknown_tag(self, name, lineno=None):104+ """Called if the parser encounters an unknown tag. Tries to fail105+ with a human readable error message that could help to identify106+ the problem.107+ """108+ return self._fail_ut_eof(name, self._end_token_stack, lineno)109+110+ def fail_eof(self, end_tokens=None, lineno=None):111+ """Like fail_unknown_tag but for end of template situations."""112+ stack = list(self._end_token_stack)113+ if end_tokens is not None:114+ stack.append(end_tokens)115+ return self._fail_ut_eof(None, stack, lineno)116+117+ def is_tuple_end(self, extra_end_rules=None):118+ """Are we at the end of a tuple?"""119+ if self.stream.current.type in ("variable_end", "block_end", "rparen"):120+ return True121+ elif extra_end_rules is not None:122+ return self.stream.current.test_any(extra_end_rules)123+ return False124+125+ def free_identifier(self, lineno=None):126+ """Return a new free identifier as :class:`~jinja2.nodes.InternalName`."""127+ self._last_identifier += 1128+ rv = object.__new__(nodes.InternalName)129+ nodes.Node.__init__(rv, "fi%d" % self._last_identifier, lineno=lineno)130+ return rv131+132+ def parse_statement(self):133+ """Parse a single statement."""134+ token = self.stream.current135+ if token.type != "name":136+ self.fail("tag name expected", token.lineno)137+ self._tag_stack.append(token.value)138+ pop_tag = True139+ try:140+ if token.value in _statement_keywords:141+ return getattr(self, "parse_" + self.stream.current.value)()142+ if token.value == "call":143+ return self.parse_call_block()144+ if token.value == "filter":145+ return self.parse_filter_block()146+ ext = self.extensions.get(token.value)147+ if ext is not None:148+ return ext(self)149+150+ # did not work out, remove the token we pushed by accident151+ # from the stack so that the unknown tag fail function can152+ # produce a proper error message.153+ self._tag_stack.pop()154+ pop_tag = False155+ self.fail_unknown_tag(token.value, token.lineno)156+ finally:157+ if pop_tag:158+ self._tag_stack.pop()159+160+ def parse_statements(self, end_tokens, drop_needle=False):161+ """Parse multiple statements into a list until one of the end tokens162+ is reached. This is used to parse the body of statements as it also163+ parses template data if appropriate. The parser checks first if the164+ current token is a colon and skips it if there is one. Then it checks165+ for the block end and parses until if one of the `end_tokens` is166+ reached. Per default the active token in the stream at the end of167+ the call is the matched end token. If this is not wanted `drop_needle`168+ can be set to `True` and the end token is removed.169+ """170+ # the first token may be a colon for python compatibility171+ self.stream.skip_if("colon")172+173+ # in the future it would be possible to add whole code sections174+ # by adding some sort of end of statement token and parsing those here.175+ self.stream.expect("block_end")176+ result = self.subparse(end_tokens)177+178+ # we reached the end of the template too early, the subparser179+ # does not check for this, so we do that now180+ if self.stream.current.type == "eof":181+ self.fail_eof(end_tokens)182+183+ if drop_needle:184+ next(self.stream)185+ return result186+187+ def parse_set(self):188+ """Parse an assign statement."""189+ lineno = next(self.stream).lineno190+ target = self.parse_assign_target(with_namespace=True)191+ if self.stream.skip_if("assign"):192+ expr = self.parse_tuple()193+ return nodes.Assign(target, expr, lineno=lineno)194+ filter_node = self.parse_filter(None)195+ body = self.parse_statements(("name:endset",), drop_needle=True)196+ return nodes.AssignBlock(target, filter_node, body, lineno=lineno)197+198+ def parse_for(self):199+ """Parse a for loop."""200+ lineno = self.stream.expect("name:for").lineno201+ target = self.parse_assign_target(extra_end_rules=("name:in",))202+ self.stream.expect("name:in")203+ iter = self.parse_tuple(204+ with_condexpr=False, extra_end_rules=("name:recursive",)205+ )206+ test = None207+ if self.stream.skip_if("name:if"):208+ test = self.parse_expression()209+ recursive = self.stream.skip_if("name:recursive")210+ body = self.parse_statements(("name:endfor", "name:else"))211+ if next(self.stream).value == "endfor":212+ else_ = []213+ else:214+ else_ = self.parse_statements(("name:endfor",), drop_needle=True)215+ return nodes.For(target, iter, body, else_, test, recursive, lineno=lineno)216+217+ def parse_if(self):218+ """Parse an if construct."""219+ node = result = nodes.If(lineno=self.stream.expect("name:if").lineno)220+ while 1:221+ node.test = self.parse_tuple(with_condexpr=False)222+ node.body = self.parse_statements(("name:elif", "name:else", "name:endif"))223+ node.elif_ = []224+ node.else_ = []225+ token = next(self.stream)226+ if token.test("name:elif"):227+ node = nodes.If(lineno=self.stream.current.lineno)228+ result.elif_.append(node)229+ continue230+ elif token.test("name:else"):231+ result.else_ = self.parse_statements(("name:endif",), drop_needle=True)232+ break233+ return result234+235+ def parse_with(self):236+ node = nodes.With(lineno=next(self.stream).lineno)237+ targets = []238+ values = []239+ while self.stream.current.type != "block_end":240+ if targets:241+ self.stream.expect("comma")242+ target = self.parse_assign_target()243+ target.set_ctx("param")244+ targets.append(target)245+ self.stream.expect("assign")246+ values.append(self.parse_expression())247+ node.targets = targets248+ node.values = values249+ node.body = self.parse_statements(("name:endwith",), drop_needle=True)250+ return node251+252+ def parse_autoescape(self):253+ node = nodes.ScopedEvalContextModifier(lineno=next(self.stream).lineno)254+ node.options = [nodes.Keyword("autoescape", self.parse_expression())]255+ node.body = self.parse_statements(("name:endautoescape",), drop_needle=True)256+ return nodes.Scope([node])257+258+ def parse_block(self):259+ node = nodes.Block(lineno=next(self.stream).lineno)260+ node.name = self.stream.expect("name").value261+ node.scoped = self.stream.skip_if("name:scoped")262+263+ # common problem people encounter when switching from django264+ # to jinja. we do not support hyphens in block names, so let's265+ # raise a nicer error message in that case.266+ if self.stream.current.type == "sub":267+ self.fail(268+ "Block names in Jinja have to be valid Python "269+ "identifiers and may not contain hyphens, use an "270+ "underscore instead."271+ )272+273+ node.body = self.parse_statements(("name:endblock",), drop_needle=True)274+ self.stream.skip_if("name:" + node.name)275+ return node276+277+ def parse_extends(self):278+ node = nodes.Extends(lineno=next(self.stream).lineno)279+ node.template = self.parse_expression()280+ return node281+282+ def parse_import_context(self, node, default):283+ if self.stream.current.test_any(284+ "name:with", "name:without"285+ ) and self.stream.look().test("name:context"):286+ node.with_context = next(self.stream).value == "with"287+ self.stream.skip()288+ else:289+ node.with_context = default290+ return node291+292+ def parse_include(self):293+ node = nodes.Include(lineno=next(self.stream).lineno)294+ node.template = self.parse_expression()295+ if self.stream.current.test("name:ignore") and self.stream.look().test(296+ "name:missing"297+ ):298+ node.ignore_missing = True299+ self.stream.skip(2)300+ else:301+ node.ignore_missing = False302+ return self.parse_import_context(node, True)303+304+ def parse_import(self):305+ node = nodes.Import(lineno=next(self.stream).lineno)306+ node.template = self.parse_expression()307+ self.stream.expect("name:as")308+ node.target = self.parse_assign_target(name_only=True).name309+ return self.parse_import_context(node, False)310+311+ def parse_from(self):312+ node = nodes.FromImport(lineno=next(self.stream).lineno)313+ node.template = self.parse_expression()314+ self.stream.expect("name:import")315+ node.names = []316+317+ def parse_context():318+ if self.stream.current.value in (319+ "with",320+ "without",321+ ) and self.stream.look().test("name:context"):322+ node.with_context = next(self.stream).value == "with"323+ self.stream.skip()324+ return True325+ return False326+327+ while 1:328+ if node.names:329+ self.stream.expect("comma")330+ if self.stream.current.type == "name":331+ if parse_context():332+ break333+ target = self.parse_assign_target(name_only=True)334+ if target.name.startswith("_"):335+ self.fail(336+ "names starting with an underline can not be imported",337+ target.lineno,338+ exc=TemplateAssertionError,339+ )340+ if self.stream.skip_if("name:as"):341+ alias = self.parse_assign_target(name_only=True)342+ node.names.append((target.name, alias.name))343+ else:344+ node.names.append(target.name)345+ if parse_context() or self.stream.current.type != "comma":346+ break347+ else:348+ self.stream.expect("name")349+ if not hasattr(node, "with_context"):350+ node.with_context = False351+ return node352+353+ def parse_signature(self, node):354+ node.args = args = []355+ node.defaults = defaults = []356+ self.stream.expect("lparen")357+ while self.stream.current.type != "rparen":358+ if args:359+ self.stream.expect("comma")360+ arg = self.parse_assign_target(name_only=True)361+ arg.set_ctx("param")362+ if self.stream.skip_if("assign"):363+ defaults.append(self.parse_expression())364+ elif defaults:365+ self.fail("non-default argument follows default argument")366+ args.append(arg)367+ self.stream.expect("rparen")368+369+ def parse_call_block(self):370+ node = nodes.CallBlock(lineno=next(self.stream).lineno)371+ if self.stream.current.type == "lparen":372+ self.parse_signature(node)373+ else:374+ node.args = []375+ node.defaults = []376+377+ node.call = self.parse_expression()378+ if not isinstance(node.call, nodes.Call):379+ self.fail("expected call", node.lineno)380+ node.body = self.parse_statements(("name:endcall",), drop_needle=True)381+ return node382+383+ def parse_filter_block(self):384+ node = nodes.FilterBlock(lineno=next(self.stream).lineno)385+ node.filter = self.parse_filter(None, start_inline=True)386+ node.body = self.parse_statements(("name:endfilter",), drop_needle=True)387+ return node388+389+ def parse_macro(self):390+ node = nodes.Macro(lineno=next(self.stream).lineno)391+ node.name = self.parse_assign_target(name_only=True).name392+ self.parse_signature(node)393+ node.body = self.parse_statements(("name:endmacro",), drop_needle=True)394+ return node395+396+ def parse_print(self):397+ node = nodes.Output(lineno=next(self.stream).lineno)398+ node.nodes = []399+ while self.stream.current.type != "block_end":400+ if node.nodes:401+ self.stream.expect("comma")402+ node.nodes.append(self.parse_expression())403+ return node404+405+ def parse_assign_target(406+ self,407+ with_tuple=True,408+ name_only=False,409+ extra_end_rules=None,410+ with_namespace=False,411+ ):412+ """Parse an assignment target. As Jinja allows assignments to413+ tuples, this function can parse all allowed assignment targets. Per414+ default assignments to tuples are parsed, that can be disable however415+ by setting `with_tuple` to `False`. If only assignments to names are416+ wanted `name_only` can be set to `True`. The `extra_end_rules`417+ parameter is forwarded to the tuple parsing function. If418+ `with_namespace` is enabled, a namespace assignment may be parsed.419+ """420+ if with_namespace and self.stream.look().type == "dot":421+ token = self.stream.expect("name")422+ next(self.stream) # dot423+ attr = self.stream.expect("name")424+ target = nodes.NSRef(token.value, attr.value, lineno=token.lineno)425+ elif name_only:426+ token = self.stream.expect("name")427+ target = nodes.Name(token.value, "store", lineno=token.lineno)428+ else:429+ if with_tuple:430+ target = self.parse_tuple(431+ simplified=True, extra_end_rules=extra_end_rules432+ )433+ else:434+ target = self.parse_primary()435+ target.set_ctx("store")436+ if not target.can_assign():437+ self.fail(438+ "can't assign to %r" % target.__class__.__name__.lower(), target.lineno439+ )440+ return target441+442+ def parse_expression(self, with_condexpr=True):443+ """Parse an expression. Per default all expressions are parsed, if444+ the optional `with_condexpr` parameter is set to `False` conditional445+ expressions are not parsed.446+ """447+ if with_condexpr:448+ return self.parse_condexpr()449+ return self.parse_or()450+451+ def parse_condexpr(self):452+ lineno = self.stream.current.lineno453+ expr1 = self.parse_or()454+ while self.stream.skip_if("name:if"):455+ expr2 = self.parse_or()456+ if self.stream.skip_if("name:else"):457+ expr3 = self.parse_condexpr()458+ else:459+ expr3 = None460+ expr1 = nodes.CondExpr(expr2, expr1, expr3, lineno=lineno)461+ lineno = self.stream.current.lineno462+ return expr1463+464+ def parse_or(self):465+ lineno = self.stream.current.lineno466+ left = self.parse_and()467+ while self.stream.skip_if("name:or"):468+ right = self.parse_and()469+ left = nodes.Or(left, right, lineno=lineno)470+ lineno = self.stream.current.lineno471+ return left472+473+ def parse_and(self):474+ lineno = self.stream.current.lineno475+ left = self.parse_not()476+ while self.stream.skip_if("name:and"):477+ right = self.parse_not()478+ left = nodes.And(left, right, lineno=lineno)479+ lineno = self.stream.current.lineno480+ return left481+482+ def parse_not(self):483+ if self.stream.current.test("name:not"):484+ lineno = next(self.stream).lineno485+ return nodes.Not(self.parse_not(), lineno=lineno)486+ return self.parse_compare()487+488+ def parse_compare(self):489+ lineno = self.stream.current.lineno490+ expr = self.parse_math1()491+ ops = []492+ while 1:493+ token_type = self.stream.current.type494+ if token_type in _compare_operators:495+ next(self.stream)496+ ops.append(nodes.Operand(token_type, self.parse_math1()))497+ elif self.stream.skip_if("name:in"):498+ ops.append(nodes.Operand("in", self.parse_math1()))499+ elif self.stream.current.test("name:not") and self.stream.look().test(500+ "name:in"501+ ):502+ self.stream.skip(2)503+ ops.append(nodes.Operand("notin", self.parse_math1()))504+ else:505+ break506+ lineno = self.stream.current.lineno507+ if not ops:508+ return expr509+ return nodes.Compare(expr, ops, lineno=lineno)510+511+ def parse_math1(self):512+ lineno = self.stream.current.lineno513+ left = self.parse_concat()514+ while self.stream.current.type in ("add", "sub"):515+ cls = _math_nodes[self.stream.current.type]516+ next(self.stream)517+ right = self.parse_concat()518+ left = cls(left, right, lineno=lineno)519+ lineno = self.stream.current.lineno520+ return left521+522+ def parse_concat(self):523+ lineno = self.stream.current.lineno524+ args = [self.parse_math2()]525+ while self.stream.current.type == "tilde":526+ next(self.stream)527+ args.append(self.parse_math2())528+ if len(args) == 1:529+ return args[0]530+ return nodes.Concat(args, lineno=lineno)531+532+ def parse_math2(self):533+ lineno = self.stream.current.lineno534+ left = self.parse_pow()535+ while self.stream.current.type in ("mul", "div", "floordiv", "mod"):536+ cls = _math_nodes[self.stream.current.type]537+ next(self.stream)538+ right = self.parse_pow()539+ left = cls(left, right, lineno=lineno)540+ lineno = self.stream.current.lineno541+ return left542+543+ def parse_pow(self):544+ lineno = self.stream.current.lineno545+ left = self.parse_unary()546+ while self.stream.current.type == "pow":547+ next(self.stream)548+ right = self.parse_unary()549+ left = nodes.Pow(left, right, lineno=lineno)550+ lineno = self.stream.current.lineno551+ return left552+553+ def parse_unary(self, with_filter=True):554+ token_type = self.stream.current.type555+ lineno = self.stream.current.lineno556+ if token_type == "sub":557+ next(self.stream)558+ node = nodes.Neg(self.parse_unary(False), lineno=lineno)559+ elif token_type == "add":560+ next(self.stream)561+ node = nodes.Pos(self.parse_unary(False), lineno=lineno)562+ else:563+ node = self.parse_primary()564+ node = self.parse_postfix(node)565+ if with_filter:566+ node = self.parse_filter_expr(node)567+ return node568+569+ def parse_primary(self):570+ token = self.stream.current571+ if token.type == "name":572+ if token.value in ("true", "false", "True", "False"):573+ node = nodes.Const(token.value in ("true", "True"), lineno=token.lineno)574+ elif token.value in ("none", "None"):575+ node = nodes.Const(None, lineno=token.lineno)576+ else:577+ node = nodes.Name(token.value, "load", lineno=token.lineno)578+ next(self.stream)579+ elif token.type == "string":580+ next(self.stream)581+ buf = [token.value]582+ lineno = token.lineno583+ while self.stream.current.type == "string":584+ buf.append(self.stream.current.value)585+ next(self.stream)586+ node = nodes.Const("".join(buf), lineno=lineno)587+ elif token.type in ("integer", "float"):588+ next(self.stream)589+ node = nodes.Const(token.value, lineno=token.lineno)590+ elif token.type == "lparen":591+ next(self.stream)592+ node = self.parse_tuple(explicit_parentheses=True)593+ self.stream.expect("rparen")594+ elif token.type == "lbracket":595+ node = self.parse_list()596+ elif token.type == "lbrace":597+ node = self.parse_dict()598+ else:599+ self.fail("unexpected '%s'" % describe_token(token), token.lineno)600+ return node601+602+ def parse_tuple(603+ self,604+ simplified=False,605+ with_condexpr=True,606+ extra_end_rules=None,607+ explicit_parentheses=False,608+ ):609+ """Works like `parse_expression` but if multiple expressions are610+ delimited by a comma a :class:`~jinja2.nodes.Tuple` node is created.611+ This method could also return a regular expression instead of a tuple612+ if no commas where found.613+614+ The default parsing mode is a full tuple. If `simplified` is `True`615+ only names and literals are parsed. The `no_condexpr` parameter is616+ forwarded to :meth:`parse_expression`.617+618+ Because tuples do not require delimiters and may end in a bogus comma619+ an extra hint is needed that marks the end of a tuple. For example620+ for loops support tuples between `for` and `in`. In that case the621+ `extra_end_rules` is set to ``['name:in']``.622+623+ `explicit_parentheses` is true if the parsing was triggered by an624+ expression in parentheses. This is used to figure out if an empty625+ tuple is a valid expression or not.626+ """627+ lineno = self.stream.current.lineno628+ if simplified:629+ parse = self.parse_primary630+ elif with_condexpr:631+ parse = self.parse_expression632+ else:633+634+ def parse():635+ return self.parse_expression(with_condexpr=False)636+637+ args = []638+ is_tuple = False639+ while 1:640+ if args:641+ self.stream.expect("comma")642+ if self.is_tuple_end(extra_end_rules):643+ break644+ args.append(parse())645+ if self.stream.current.type == "comma":646+ is_tuple = True647+ else:648+ break649+ lineno = self.stream.current.lineno650+651+ if not is_tuple:652+ if args:653+ return args[0]654+655+ # if we don't have explicit parentheses, an empty tuple is656+ # not a valid expression. This would mean nothing (literally657+ # nothing) in the spot of an expression would be an empty658+ # tuple.659+ if not explicit_parentheses:660+ self.fail(661+ "Expected an expression, got '%s'"662+ % describe_token(self.stream.current)663+ )664+665+ return nodes.Tuple(args, "load", lineno=lineno)666+667+ def parse_list(self):668+ token = self.stream.expect("lbracket")669+ items = []670+ while self.stream.current.type != "rbracket":671+ if items:672+ self.stream.expect("comma")673+ if self.stream.current.type == "rbracket":674+ break675+ items.append(self.parse_expression())676+ self.stream.expect("rbracket")677+ return nodes.List(items, lineno=token.lineno)678+679+ def parse_dict(self):680+ token = self.stream.expect("lbrace")681+ items = []682+ while self.stream.current.type != "rbrace":683+ if items:684+ self.stream.expect("comma")685+ if self.stream.current.type == "rbrace":686+ break687+ key = self.parse_expression()688+ self.stream.expect("colon")689+ value = self.parse_expression()690+ items.append(nodes.Pair(key, value, lineno=key.lineno))691+ self.stream.expect("rbrace")692+ return nodes.Dict(items, lineno=token.lineno)693+694+ def parse_postfix(self, node):695+ while 1:696+ token_type = self.stream.current.type697+ if token_type == "dot" or token_type == "lbracket":698+ node = self.parse_subscript(node)699+ # calls are valid both after postfix expressions (getattr700+ # and getitem) as well as filters and tests701+ elif token_type == "lparen":702+ node = self.parse_call(node)703+ else:704+ break705+ return node706+707+ def parse_filter_expr(self, node):708+ while 1:709+ token_type = self.stream.current.type710+ if token_type == "pipe":711+ node = self.parse_filter(node)712+ elif token_type == "name" and self.stream.current.value == "is":713+ node = self.parse_test(node)714+ # calls are valid both after postfix expressions (getattr715+ # and getitem) as well as filters and tests716+ elif token_type == "lparen":717+ node = self.parse_call(node)718+ else:719+ break720+ return node721+722+ def parse_subscript(self, node):723+ token = next(self.stream)724+ if token.type == "dot":725+ attr_token = self.stream.current726+ next(self.stream)727+ if attr_token.type == "name":728+ return nodes.Getattr(729+ node, attr_token.value, "load", lineno=token.lineno730+ )731+ elif attr_token.type != "integer":732+ self.fail("expected name or number", attr_token.lineno)733+ arg = nodes.Const(attr_token.value, lineno=attr_token.lineno)734+ return nodes.Getitem(node, arg, "load", lineno=token.lineno)735+ if token.type == "lbracket":736+ args = []737+ while self.stream.current.type != "rbracket":738+ if args:739+ self.stream.expect("comma")740+ args.append(self.parse_subscribed())741+ self.stream.expect("rbracket")742+ if len(args) == 1:743+ arg = args[0]744+ else:745+ arg = nodes.Tuple(args, "load", lineno=token.lineno)746+ return nodes.Getitem(node, arg, "load", lineno=token.lineno)747+ self.fail("expected subscript expression", token.lineno)748+749+ def parse_subscribed(self):750+ lineno = self.stream.current.lineno751+752+ if self.stream.current.type == "colon":753+ next(self.stream)754+ args = [None]755+ else:756+ node = self.parse_expression()757+ if self.stream.current.type != "colon":758+ return node759+ next(self.stream)760+ args = [node]761+762+ if self.stream.current.type == "colon":763+ args.append(None)764+ elif self.stream.current.type not in ("rbracket", "comma"):765+ args.append(self.parse_expression())766+ else:767+ args.append(None)768+769+ if self.stream.current.type == "colon":770+ next(self.stream)771+ if self.stream.current.type not in ("rbracket", "comma"):772+ args.append(self.parse_expression())773+ else:774+ args.append(None)775+ else:776+ args.append(None)777+778+ return nodes.Slice(lineno=lineno, *args)779+780+ def parse_call(self, node):781+ token = self.stream.expect("lparen")782+ args = []783+ kwargs = []784+ dyn_args = dyn_kwargs = None785+ require_comma = False786+787+ def ensure(expr):788+ if not expr:789+ self.fail("invalid syntax for function call expression", token.lineno)790+791+ while self.stream.current.type != "rparen":792+ if require_comma:793+ self.stream.expect("comma")794+ # support for trailing comma795+ if self.stream.current.type == "rparen":796+ break797+ if self.stream.current.type == "mul":798+ ensure(dyn_args is None and dyn_kwargs is None)799+ next(self.stream)800+ dyn_args = self.parse_expression()801+ elif self.stream.current.type == "pow":802+ ensure(dyn_kwargs is None)803+ next(self.stream)804+ dyn_kwargs = self.parse_expression()805+ else:806+ if (807+ self.stream.current.type == "name"808+ and self.stream.look().type == "assign"809+ ):810+ # Parsing a kwarg811+ ensure(dyn_kwargs is None)812+ key = self.stream.current.value813+ self.stream.skip(2)814+ value = self.parse_expression()815+ kwargs.append(nodes.Keyword(key, value, lineno=value.lineno))816+ else:817+ # Parsing an arg818+ ensure(dyn_args is None and dyn_kwargs is None and not kwargs)819+ args.append(self.parse_expression())820+821+ require_comma = True822+ self.stream.expect("rparen")823+824+ if node is None:825+ return args, kwargs, dyn_args, dyn_kwargs826+ return nodes.Call(node, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno)827+828+ def parse_filter(self, node, start_inline=False):829+ while self.stream.current.type == "pipe" or start_inline:830+ if not start_inline:831+ next(self.stream)832+ token = self.stream.expect("name")833+ name = token.value834+ while self.stream.current.type == "dot":835+ next(self.stream)836+ name += "." + self.stream.expect("name").value837+ if self.stream.current.type == "lparen":838+ args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)839+ else:840+ args = []841+ kwargs = []842+ dyn_args = dyn_kwargs = None843+ node = nodes.Filter(844+ node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno845+ )846+ start_inline = False847+ return node848+849+ def parse_test(self, node):850+ token = next(self.stream)851+ if self.stream.current.test("name:not"):852+ next(self.stream)853+ negated = True854+ else:855+ negated = False856+ name = self.stream.expect("name").value857+ while self.stream.current.type == "dot":858+ next(self.stream)859+ name += "." + self.stream.expect("name").value860+ dyn_args = dyn_kwargs = None861+ kwargs = []862+ if self.stream.current.type == "lparen":863+ args, kwargs, dyn_args, dyn_kwargs = self.parse_call(None)864+ elif self.stream.current.type in (865+ "name",866+ "string",867+ "integer",868+ "float",869+ "lparen",870+ "lbracket",871+ "lbrace",872+ ) and not self.stream.current.test_any("name:else", "name:or", "name:and"):873+ if self.stream.current.test("name:is"):874+ self.fail("You cannot chain multiple tests with is")875+ arg_node = self.parse_primary()876+ arg_node = self.parse_postfix(arg_node)877+ args = [arg_node]878+ else:879+ args = []880+ node = nodes.Test(881+ node, name, args, kwargs, dyn_args, dyn_kwargs, lineno=token.lineno882+ )883+ if negated:884+ node = nodes.Not(node, lineno=token.lineno)885+ return node886+887+ def subparse(self, end_tokens=None):888+ body = []889+ data_buffer = []890+ add_data = data_buffer.append891+892+ if end_tokens is not None:893+ self._end_token_stack.append(end_tokens)894+895+ def flush_data():896+ if data_buffer:897+ lineno = data_buffer[0].lineno898+ body.append(nodes.Output(data_buffer[:], lineno=lineno))899+ del data_buffer[:]900+901+ try:902+ while self.stream:903+ token = self.stream.current904+ if token.type == "data":905+ if token.value:906+ add_data(nodes.TemplateData(token.value, lineno=token.lineno))907+ next(self.stream)908+ elif token.type == "variable_begin":909+ next(self.stream)910+ add_data(self.parse_tuple(with_condexpr=True))911+ self.stream.expect("variable_end")912+ elif token.type == "block_begin":913+ flush_data()914+ next(self.stream)915+ if end_tokens is not None and self.stream.current.test_any(916+ *end_tokens917+ ):918+ return body919+ rv = self.parse_statement()920+ if isinstance(rv, list):921+ body.extend(rv)922+ else:923+ body.append(rv)924+ self.stream.expect("block_end")925+ else:926+ raise AssertionError("internal parsing error")927+928+ flush_data()929+ finally:930+ if end_tokens is not None:931+ self._end_token_stack.pop()932+933+ return body934+935+ def parse(self):936+ """Parse the whole template into a `Template` node."""937+ result = nodes.Template(self.subparse(), lineno=1)938+ result.set_environment(self.environment)939+ return resultadded:src/jinja2/runtime.py+1011 added
1+# -*- coding: utf-8 -*-2+"""The runtime functions and state used by compiled templates."""3+import sys4+from itertools import chain5+from types import MethodType6+7+from markupsafe import escape8+from markupsafe import Markup9+from markupsafe import soft_unicode10+11+from ._compat import abc12+from ._compat import imap13+from ._compat import implements_iterator14+from ._compat import implements_to_string15+from ._compat import iteritems16+from ._compat import PY217+from ._compat import string_types18+from ._compat import text_type19+from ._compat import with_metaclass20+from .exceptions import TemplateNotFound21+from .exceptions import TemplateRuntimeError22+from .exceptions import UndefinedError23+from .nodes import EvalContext24+from .utils import concat25+from .utils import evalcontextfunction26+from .utils import internalcode27+from .utils import missing28+from .utils import Namespace29+from .utils import object_type_repr30+31+# these variables are exported to the template runtime32+__all__ = [33+ "LoopContext",34+ "TemplateReference",35+ "Macro",36+ "Markup",37+ "TemplateRuntimeError",38+ "missing",39+ "concat",40+ "escape",41+ "markup_join",42+ "unicode_join",43+ "to_string",44+ "identity",45+ "TemplateNotFound",46+ "Namespace",47+ "Undefined",48+]49+50+#: the name of the function that is used to convert something into51+#: a string. We can just use the text type here.52+to_string = text_type53+54+55+def identity(x):56+ """Returns its argument. Useful for certain things in the57+ environment.58+ """59+ return x60+61+62+def markup_join(seq):63+ """Concatenation that escapes if necessary and converts to unicode."""64+ buf = []65+ iterator = imap(soft_unicode, seq)66+ for arg in iterator:67+ buf.append(arg)68+ if hasattr(arg, "__html__"):69+ return Markup(u"").join(chain(buf, iterator))70+ return concat(buf)71+72+73+def unicode_join(seq):74+ """Simple args to unicode conversion and concatenation."""75+ return concat(imap(text_type, seq))76+77+78+def new_context(79+ environment,80+ template_name,81+ blocks,82+ vars=None,83+ shared=None,84+ globals=None,85+ locals=None,86+):87+ """Internal helper for context creation."""88+ if vars is None:89+ vars = {}90+ if shared:91+ parent = vars92+ else:93+ parent = dict(globals or (), **vars)94+ if locals:95+ # if the parent is shared a copy should be created because96+ # we don't want to modify the dict passed97+ if shared:98+ parent = dict(parent)99+ for key, value in iteritems(locals):100+ if value is not missing:101+ parent[key] = value102+ return environment.context_class(environment, parent, template_name, blocks)103+104+105+class TemplateReference(object):106+ """The `self` in templates."""107+108+ def __init__(self, context):109+ self.__context = context110+111+ def __getitem__(self, name):112+ blocks = self.__context.blocks[name]113+ return BlockReference(name, self.__context, blocks, 0)114+115+ def __repr__(self):116+ return "<%s %r>" % (self.__class__.__name__, self.__context.name)117+118+119+def _get_func(x):120+ return getattr(x, "__func__", x)121+122+123+class ContextMeta(type):124+ def __new__(mcs, name, bases, d):125+ rv = type.__new__(mcs, name, bases, d)126+ if bases == ():127+ return rv128+129+ resolve = _get_func(rv.resolve)130+ default_resolve = _get_func(Context.resolve)131+ resolve_or_missing = _get_func(rv.resolve_or_missing)132+ default_resolve_or_missing = _get_func(Context.resolve_or_missing)133+134+ # If we have a changed resolve but no changed default or missing135+ # resolve we invert the call logic.136+ if (137+ resolve is not default_resolve138+ and resolve_or_missing is default_resolve_or_missing139+ ):140+ rv._legacy_resolve_mode = True141+ elif (142+ resolve is default_resolve143+ and resolve_or_missing is default_resolve_or_missing144+ ):145+ rv._fast_resolve_mode = True146+147+ return rv148+149+150+def resolve_or_missing(context, key, missing=missing):151+ if key in context.vars:152+ return context.vars[key]153+ if key in context.parent:154+ return context.parent[key]155+ return missing156+157+158+class Context(with_metaclass(ContextMeta)):159+ """The template context holds the variables of a template. It stores the160+ values passed to the template and also the names the template exports.161+ Creating instances is neither supported nor useful as it's created162+ automatically at various stages of the template evaluation and should not163+ be created by hand.164+165+ The context is immutable. Modifications on :attr:`parent` **must not**166+ happen and modifications on :attr:`vars` are allowed from generated167+ template code only. Template filters and global functions marked as168+ :func:`contextfunction`\\s get the active context passed as first argument169+ and are allowed to access the context read-only.170+171+ The template context supports read only dict operations (`get`,172+ `keys`, `values`, `items`, `iterkeys`, `itervalues`, `iteritems`,173+ `__getitem__`, `__contains__`). Additionally there is a :meth:`resolve`174+ method that doesn't fail with a `KeyError` but returns an175+ :class:`Undefined` object for missing variables.176+ """177+178+ # XXX: we want to eventually make this be a deprecation warning and179+ # remove it.180+ _legacy_resolve_mode = False181+ _fast_resolve_mode = False182+183+ def __init__(self, environment, parent, name, blocks):184+ self.parent = parent185+ self.vars = {}186+ self.environment = environment187+ self.eval_ctx = EvalContext(self.environment, name)188+ self.exported_vars = set()189+ self.name = name190+191+ # create the initial mapping of blocks. Whenever template inheritance192+ # takes place the runtime will update this mapping with the new blocks193+ # from the template.194+ self.blocks = dict((k, [v]) for k, v in iteritems(blocks))195+196+ # In case we detect the fast resolve mode we can set up an alias197+ # here that bypasses the legacy code logic.198+ if self._fast_resolve_mode:199+ self.resolve_or_missing = MethodType(resolve_or_missing, self)200+201+ def super(self, name, current):202+ """Render a parent block."""203+ try:204+ blocks = self.blocks[name]205+ index = blocks.index(current) + 1206+ blocks[index]207+ except LookupError:208+ return self.environment.undefined(209+ "there is no parent block called %r." % name, name="super"210+ )211+ return BlockReference(name, self, blocks, index)212+213+ def get(self, key, default=None):214+ """Returns an item from the template context, if it doesn't exist215+ `default` is returned.216+ """217+ try:218+ return self[key]219+ except KeyError:220+ return default221+222+ def resolve(self, key):223+ """Looks up a variable like `__getitem__` or `get` but returns an224+ :class:`Undefined` object with the name of the name looked up.225+ """226+ if self._legacy_resolve_mode:227+ rv = resolve_or_missing(self, key)228+ else:229+ rv = self.resolve_or_missing(key)230+ if rv is missing:231+ return self.environment.undefined(name=key)232+ return rv233+234+ def resolve_or_missing(self, key):235+ """Resolves a variable like :meth:`resolve` but returns the236+ special `missing` value if it cannot be found.237+ """238+ if self._legacy_resolve_mode:239+ rv = self.resolve(key)240+ if isinstance(rv, Undefined):241+ rv = missing242+ return rv243+ return resolve_or_missing(self, key)244+245+ def get_exported(self):246+ """Get a new dict with the exported variables."""247+ return dict((k, self.vars[k]) for k in self.exported_vars)248+249+ def get_all(self):250+ """Return the complete context as dict including the exported251+ variables. For optimizations reasons this might not return an252+ actual copy so be careful with using it.253+ """254+ if not self.vars:255+ return self.parent256+ if not self.parent:257+ return self.vars258+ return dict(self.parent, **self.vars)259+260+ @internalcode261+ def call(__self, __obj, *args, **kwargs): # noqa: B902262+ """Call the callable with the arguments and keyword arguments263+ provided but inject the active context or environment as first264+ argument if the callable is a :func:`contextfunction` or265+ :func:`environmentfunction`.266+ """267+ if __debug__:268+ __traceback_hide__ = True # noqa269+270+ # Allow callable classes to take a context271+ if hasattr(__obj, "__call__"): # noqa: B004272+ fn = __obj.__call__273+ for fn_type in (274+ "contextfunction",275+ "evalcontextfunction",276+ "environmentfunction",277+ ):278+ if hasattr(fn, fn_type):279+ __obj = fn280+ break281+282+ if callable(__obj):283+ if getattr(__obj, "contextfunction", 0):284+ args = (__self,) + args285+ elif getattr(__obj, "evalcontextfunction", 0):286+ args = (__self.eval_ctx,) + args287+ elif getattr(__obj, "environmentfunction", 0):288+ args = (__self.environment,) + args289+ try:290+ return __obj(*args, **kwargs)291+ except StopIteration:292+ return __self.environment.undefined(293+ "value was undefined because "294+ "a callable raised a "295+ "StopIteration exception"296+ )297+298+ def derived(self, locals=None):299+ """Internal helper function to create a derived context. This is300+ used in situations where the system needs a new context in the same301+ template that is independent.302+ """303+ context = new_context(304+ self.environment, self.name, {}, self.get_all(), True, None, locals305+ )306+ context.eval_ctx = self.eval_ctx307+ context.blocks.update((k, list(v)) for k, v in iteritems(self.blocks))308+ return context309+310+ def _all(meth): # noqa: B902311+ def proxy(self):312+ return getattr(self.get_all(), meth)()313+314+ proxy.__doc__ = getattr(dict, meth).__doc__315+ proxy.__name__ = meth316+ return proxy317+318+ keys = _all("keys")319+ values = _all("values")320+ items = _all("items")321+322+ # not available on python 3323+ if PY2:324+ iterkeys = _all("iterkeys")325+ itervalues = _all("itervalues")326+ iteritems = _all("iteritems")327+ del _all328+329+ def __contains__(self, name):330+ return name in self.vars or name in self.parent331+332+ def __getitem__(self, key):333+ """Lookup a variable or raise `KeyError` if the variable is334+ undefined.335+ """336+ item = self.resolve_or_missing(key)337+ if item is missing:338+ raise KeyError(key)339+ return item340+341+ def __repr__(self):342+ return "<%s %s of %r>" % (343+ self.__class__.__name__,344+ repr(self.get_all()),345+ self.name,346+ )347+348+349+abc.Mapping.register(Context)350+351+352+class BlockReference(object):353+ """One block on a template reference."""354+355+ def __init__(self, name, context, stack, depth):356+ self.name = name357+ self._context = context358+ self._stack = stack359+ self._depth = depth360+361+ @property362+ def super(self):363+ """Super the block."""364+ if self._depth + 1 >= len(self._stack):365+ return self._context.environment.undefined(366+ "there is no parent block called %r." % self.name, name="super"367+ )368+ return BlockReference(self.name, self._context, self._stack, self._depth + 1)369+370+ @internalcode371+ def __call__(self):372+ rv = concat(self._stack[self._depth](self._context))373+ if self._context.eval_ctx.autoescape:374+ rv = Markup(rv)375+ return rv376+377+378+@implements_iterator379+class LoopContext:380+ """A wrapper iterable for dynamic ``for`` loops, with information381+ about the loop and iteration.382+ """383+384+ #: Current iteration of the loop, starting at 0.385+ index0 = -1386+387+ _length = None388+ _after = missing389+ _current = missing390+ _before = missing391+ _last_changed_value = missing392+393+ def __init__(self, iterable, undefined, recurse=None, depth0=0):394+ """395+ :param iterable: Iterable to wrap.396+ :param undefined: :class:`Undefined` class to use for next and397+ previous items.398+ :param recurse: The function to render the loop body when the399+ loop is marked recursive.400+ :param depth0: Incremented when looping recursively.401+ """402+ self._iterable = iterable403+ self._iterator = self._to_iterator(iterable)404+ self._undefined = undefined405+ self._recurse = recurse406+ #: How many levels deep a recursive loop currently is, starting at 0.407+ self.depth0 = depth0408+409+ @staticmethod410+ def _to_iterator(iterable):411+ return iter(iterable)412+413+ @property414+ def length(self):415+ """Length of the iterable.416+417+ If the iterable is a generator or otherwise does not have a418+ size, it is eagerly evaluated to get a size.419+ """420+ if self._length is not None:421+ return self._length422+423+ try:424+ self._length = len(self._iterable)425+ except TypeError:426+ iterable = list(self._iterator)427+ self._iterator = self._to_iterator(iterable)428+ self._length = len(iterable) + self.index + (self._after is not missing)429+430+ return self._length431+432+ def __len__(self):433+ return self.length434+435+ @property436+ def depth(self):437+ """How many levels deep a recursive loop currently is, starting at 1."""438+ return self.depth0 + 1439+440+ @property441+ def index(self):442+ """Current iteration of the loop, starting at 1."""443+ return self.index0 + 1444+445+ @property446+ def revindex0(self):447+ """Number of iterations from the end of the loop, ending at 0.448+449+ Requires calculating :attr:`length`.450+ """451+ return self.length - self.index452+453+ @property454+ def revindex(self):455+ """Number of iterations from the end of the loop, ending at 1.456+457+ Requires calculating :attr:`length`.458+ """459+ return self.length - self.index0460+461+ @property462+ def first(self):463+ """Whether this is the first iteration of the loop."""464+ return self.index0 == 0465+466+ def _peek_next(self):467+ """Return the next element in the iterable, or :data:`missing`468+ if the iterable is exhausted. Only peeks one item ahead, caching469+ the result in :attr:`_last` for use in subsequent checks. The470+ cache is reset when :meth:`__next__` is called.471+ """472+ if self._after is not missing:473+ return self._after474+475+ self._after = next(self._iterator, missing)476+ return self._after477+478+ @property479+ def last(self):480+ """Whether this is the last iteration of the loop.481+482+ Causes the iterable to advance early. See483+ :func:`itertools.groupby` for issues this can cause.484+ The :func:`groupby` filter avoids that issue.485+ """486+ return self._peek_next() is missing487+488+ @property489+ def previtem(self):490+ """The item in the previous iteration. Undefined during the491+ first iteration.492+ """493+ if self.first:494+ return self._undefined("there is no previous item")495+496+ return self._before497+498+ @property499+ def nextitem(self):500+ """The item in the next iteration. Undefined during the last501+ iteration.502+503+ Causes the iterable to advance early. See504+ :func:`itertools.groupby` for issues this can cause.505+ The :func:`groupby` filter avoids that issue.506+ """507+ rv = self._peek_next()508+509+ if rv is missing:510+ return self._undefined("there is no next item")511+512+ return rv513+514+ def cycle(self, *args):515+ """Return a value from the given args, cycling through based on516+ the current :attr:`index0`.517+518+ :param args: One or more values to cycle through.519+ """520+ if not args:521+ raise TypeError("no items for cycling given")522+523+ return args[self.index0 % len(args)]524+525+ def changed(self, *value):526+ """Return ``True`` if previously called with a different value527+ (including when called for the first time).528+529+ :param value: One or more values to compare to the last call.530+ """531+ if self._last_changed_value != value:532+ self._last_changed_value = value533+ return True534+535+ return False536+537+ def __iter__(self):538+ return self539+540+ def __next__(self):541+ if self._after is not missing:542+ rv = self._after543+ self._after = missing544+ else:545+ rv = next(self._iterator)546+547+ self.index0 += 1548+ self._before = self._current549+ self._current = rv550+ return rv, self551+552+ @internalcode553+ def __call__(self, iterable):554+ """When iterating over nested data, render the body of the loop555+ recursively with the given inner iterable data.556+557+ The loop must have the ``recursive`` marker for this to work.558+ """559+ if self._recurse is None:560+ raise TypeError(561+ "The loop must have the 'recursive' marker to be called recursively."562+ )563+564+ return self._recurse(iterable, self._recurse, depth=self.depth)565+566+ def __repr__(self):567+ return "<%s %d/%d>" % (self.__class__.__name__, self.index, self.length)568+569+570+class Macro(object):571+ """Wraps a macro function."""572+573+ def __init__(574+ self,575+ environment,576+ func,577+ name,578+ arguments,579+ catch_kwargs,580+ catch_varargs,581+ caller,582+ default_autoescape=None,583+ ):584+ self._environment = environment585+ self._func = func586+ self._argument_count = len(arguments)587+ self.name = name588+ self.arguments = arguments589+ self.catch_kwargs = catch_kwargs590+ self.catch_varargs = catch_varargs591+ self.caller = caller592+ self.explicit_caller = "caller" in arguments593+ if default_autoescape is None:594+ default_autoescape = environment.autoescape595+ self._default_autoescape = default_autoescape596+597+ @internalcode598+ @evalcontextfunction599+ def __call__(self, *args, **kwargs):600+ # This requires a bit of explanation, In the past we used to601+ # decide largely based on compile-time information if a macro is602+ # safe or unsafe. While there was a volatile mode it was largely603+ # unused for deciding on escaping. This turns out to be604+ # problematic for macros because whether a macro is safe depends not605+ # on the escape mode when it was defined, but rather when it was used.606+ #607+ # Because however we export macros from the module system and608+ # there are historic callers that do not pass an eval context (and609+ # will continue to not pass one), we need to perform an instance610+ # check here.611+ #612+ # This is considered safe because an eval context is not a valid613+ # argument to callables otherwise anyway. Worst case here is614+ # that if no eval context is passed we fall back to the compile615+ # time autoescape flag.616+ if args and isinstance(args[0], EvalContext):617+ autoescape = args[0].autoescape618+ args = args[1:]619+ else:620+ autoescape = self._default_autoescape621+622+ # try to consume the positional arguments623+ arguments = list(args[: self._argument_count])624+ off = len(arguments)625+626+ # For information why this is necessary refer to the handling627+ # of caller in the `macro_body` handler in the compiler.628+ found_caller = False629+630+ # if the number of arguments consumed is not the number of631+ # arguments expected we start filling in keyword arguments632+ # and defaults.633+ if off != self._argument_count:634+ for name in self.arguments[len(arguments) :]:635+ try:636+ value = kwargs.pop(name)637+ except KeyError:638+ value = missing639+ if name == "caller":640+ found_caller = True641+ arguments.append(value)642+ else:643+ found_caller = self.explicit_caller644+645+ # it's important that the order of these arguments does not change646+ # if not also changed in the compiler's `function_scoping` method.647+ # the order is caller, keyword arguments, positional arguments!648+ if self.caller and not found_caller:649+ caller = kwargs.pop("caller", None)650+ if caller is None:651+ caller = self._environment.undefined("No caller defined", name="caller")652+ arguments.append(caller)653+654+ if self.catch_kwargs:655+ arguments.append(kwargs)656+ elif kwargs:657+ if "caller" in kwargs:658+ raise TypeError(659+ "macro %r was invoked with two values for "660+ "the special caller argument. This is "661+ "most likely a bug." % self.name662+ )663+ raise TypeError(664+ "macro %r takes no keyword argument %r"665+ % (self.name, next(iter(kwargs)))666+ )667+ if self.catch_varargs:668+ arguments.append(args[self._argument_count :])669+ elif len(args) > self._argument_count:670+ raise TypeError(671+ "macro %r takes not more than %d argument(s)"672+ % (self.name, len(self.arguments))673+ )674+675+ return self._invoke(arguments, autoescape)676+677+ def _invoke(self, arguments, autoescape):678+ """This method is being swapped out by the async implementation."""679+ rv = self._func(*arguments)680+ if autoescape:681+ rv = Markup(rv)682+ return rv683+684+ def __repr__(self):685+ return "<%s %s>" % (686+ self.__class__.__name__,687+ self.name is None and "anonymous" or repr(self.name),688+ )689+690+691+@implements_to_string692+class Undefined(object):693+ """The default undefined type. This undefined type can be printed and694+ iterated over, but every other access will raise an :exc:`UndefinedError`:695+696+ >>> foo = Undefined(name='foo')697+ >>> str(foo)698+ ''699+ >>> not foo700+ True701+ >>> foo + 42702+ Traceback (most recent call last):703+ ...704+ jinja2.exceptions.UndefinedError: 'foo' is undefined705+ """706+707+ __slots__ = (708+ "_undefined_hint",709+ "_undefined_obj",710+ "_undefined_name",711+ "_undefined_exception",712+ )713+714+ def __init__(self, hint=None, obj=missing, name=None, exc=UndefinedError):715+ self._undefined_hint = hint716+ self._undefined_obj = obj717+ self._undefined_name = name718+ self._undefined_exception = exc719+720+ @property721+ def _undefined_message(self):722+ """Build a message about the undefined value based on how it was723+ accessed.724+ """725+ if self._undefined_hint:726+ return self._undefined_hint727+728+ if self._undefined_obj is missing:729+ return "%r is undefined" % self._undefined_name730+731+ if not isinstance(self._undefined_name, string_types):732+ return "%s has no element %r" % (733+ object_type_repr(self._undefined_obj),734+ self._undefined_name,735+ )736+737+ return "%r has no attribute %r" % (738+ object_type_repr(self._undefined_obj),739+ self._undefined_name,740+ )741+742+ @internalcode743+ def _fail_with_undefined_error(self, *args, **kwargs):744+ """Raise an :exc:`UndefinedError` when operations are performed745+ on the undefined value.746+ """747+ raise self._undefined_exception(self._undefined_message)748+749+ @internalcode750+ def __getattr__(self, name):751+ if name[:2] == "__":752+ raise AttributeError(name)753+ return self._fail_with_undefined_error()754+755+ __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_error800+801+ def __eq__(self, other):802+ return type(self) is type(other)803+804+ def __ne__(self, other):805+ return not self.__eq__(other)806+807+ def __hash__(self):808+ return id(type(self))809+810+ def __str__(self):811+ return u""812+813+ def __len__(self):814+ return 0815+816+ def __iter__(self):817+ if 0:818+ yield None819+820+ def __nonzero__(self):821+ return False822+823+ __bool__ = __nonzero__824+825+ def __repr__(self):826+ return "Undefined"827+828+829+def make_logging_undefined(logger=None, base=None):830+ """Given a logger object this returns a new undefined class that will831+ log certain failures. It will log iterations and printing. If no832+ logger is given a default logger is created.833+834+ Example::835+836+ logger = logging.getLogger(__name__)837+ LoggingUndefined = make_logging_undefined(838+ logger=logger,839+ base=Undefined840+ )841+842+ .. versionadded:: 2.8843+844+ :param logger: the logger to use. If not provided, a default logger845+ is created.846+ :param base: the base class to add logging functionality to. This847+ defaults to :class:`Undefined`.848+ """849+ if logger is None:850+ import logging851+852+ logger = logging.getLogger(__name__)853+ logger.addHandler(logging.StreamHandler(sys.stderr))854+ if base is None:855+ base = Undefined856+857+ 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)874+875+ class LoggingUndefined(base):876+ def _fail_with_undefined_error(self, *args, **kwargs):877+ try:878+ return base._fail_with_undefined_error(self, *args, **kwargs)879+ except self._undefined_exception as e:880+ logger.error("Template variable error: %s", str(e))881+ raise e882+883+ def __str__(self):884+ rv = base.__str__(self)885+ _log_message(self)886+ return rv887+888+ def __iter__(self):889+ rv = base.__iter__(self)890+ _log_message(self)891+ return rv892+893+ if PY2:894+895+ def __nonzero__(self):896+ rv = base.__nonzero__(self)897+ _log_message(self)898+ return rv899+900+ def __unicode__(self):901+ rv = base.__unicode__(self)902+ _log_message(self)903+ return rv904+905+ else:906+907+ def __bool__(self):908+ rv = base.__bool__(self)909+ _log_message(self)910+ return rv911+912+ return LoggingUndefined913+914+915+# 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.918+class ChainableUndefined(Undefined):919+ """An undefined that is chainable, where both ``__getattr__`` and920+ ``__getitem__`` return itself rather than raising an921+ :exc:`UndefinedError`.922+923+ >>> foo = ChainableUndefined(name='foo')924+ >>> str(foo.bar['baz'])925+ ''926+ >>> foo.bar['baz'] + 42927+ Traceback (most recent call last):928+ ...929+ jinja2.exceptions.UndefinedError: 'foo' is undefined930+931+ .. versionadded:: 2.11.0932+ """933+934+ __slots__ = ()935+936+ def __html__(self):937+ return self.__str__()938+939+ def __getattr__(self, _):940+ return self941+942+ __getitem__ = __getattr__943+944+945+@implements_to_string946+class DebugUndefined(Undefined):947+ """An undefined that returns the debug info when printed.948+949+ >>> foo = DebugUndefined(name='foo')950+ >>> str(foo)951+ '{{ foo }}'952+ >>> not foo953+ True954+ >>> foo + 42955+ Traceback (most recent call last):956+ ...957+ jinja2.exceptions.UndefinedError: 'foo' is undefined958+ """959+960+ __slots__ = ()961+962+ def __str__(self):963+ if self._undefined_hint is None:964+ if self._undefined_obj is missing:965+ return u"{{ %s }}" % self._undefined_name966+ return "{{ no such element: %s[%r] }}" % (967+ object_type_repr(self._undefined_obj),968+ self._undefined_name,969+ )970+ return u"{{ undefined value printed: %s }}" % self._undefined_hint971+972+973+@implements_to_string974+class StrictUndefined(Undefined):975+ """An undefined that barks on print and iteration as well as boolean976+ tests and all kinds of comparisons. In other words: you can do nothing977+ with it except checking if it's defined using the `defined` test.978+979+ >>> foo = StrictUndefined(name='foo')980+ >>> str(foo)981+ Traceback (most recent call last):982+ ...983+ jinja2.exceptions.UndefinedError: 'foo' is undefined984+ >>> not foo985+ Traceback (most recent call last):986+ ...987+ jinja2.exceptions.UndefinedError: 'foo' is undefined988+ >>> foo + 42989+ Traceback (most recent call last):990+ ...991+ jinja2.exceptions.UndefinedError: 'foo' is undefined992+ """993+994+ __slots__ = ()995+ __iter__ = (996+ __str__997+ ) = (998+ __len__999+ ) = (1000+ __nonzero__1001+ ) = __eq__ = __ne__ = __bool__ = __hash__ = Undefined._fail_with_undefined_error1002+1003+1004+# remove remaining slots attributes, after the metaclass did the magic they1005+# are unneeded and irritating as they contain wrong data for the subclasses.1006+del (1007+ Undefined.__slots__,1008+ ChainableUndefined.__slots__,1009+ DebugUndefined.__slots__,1010+ StrictUndefined.__slots__,1011+)added:src/jinja2/sandbox.py+510 added
1+# -*- coding: utf-8 -*-2+"""A sandbox layer that ensures unsafe operations cannot be performed.3+Useful when the template itself comes from an untrusted source.4+"""5+import operator6+import types7+import warnings8+from collections import deque9+from string import Formatter10+11+from markupsafe import EscapeFormatter12+13+from ._compat import abc14+from ._compat import PY215+from ._compat import range_type16+from ._compat import string_types17+from .environment import Environment18+from .exceptions import SecurityError19+from .utils import Markup20+21+#: maximum number of items a range may produce22+MAX_RANGE = 10000023+24+#: attributes of function objects that are considered unsafe.25+if PY2:26+ UNSAFE_FUNCTION_ATTRIBUTES = {27+ "func_closure",28+ "func_code",29+ "func_dict",30+ "func_defaults",31+ "func_globals",32+ }33+else: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()37+38+#: unsafe method attributes. function attributes are unsafe for methods too39+UNSAFE_METHOD_ATTRIBUTES = {"im_class", "im_func", "im_self"}40+41+#: unsafe generator attributes.42+UNSAFE_GENERATOR_ATTRIBUTES = {"gi_frame", "gi_code"}43+44+#: unsafe attributes on coroutines45+UNSAFE_COROUTINE_ATTRIBUTES = {"cr_frame", "cr_code"}46+47+#: unsafe attributes on async generators48+UNSAFE_ASYNC_GENERATOR_ATTRIBUTES = {"ag_code", "ag_frame"}49+50+# make sure we don't warn in python 2.6 about stuff we don't care about51+warnings.filterwarnings(52+ "ignore", "the sets module", DeprecationWarning, module=__name__53+)54+55+_mutable_set_types = (set,)56+_mutable_mapping_types = (dict,)57+_mutable_sequence_types = (list,)58+59+# on python 2.x we can register the user collection types60+try:61+ from UserDict import UserDict, DictMixin62+ from UserList import UserList63+64+ _mutable_mapping_types += (UserDict, DictMixin)65+ _mutable_set_types += (UserList,)66+except ImportError:67+ pass68+69+# if sets is still available, register the mutable set from there as well70+try:71+ from sets import Set72+73+ _mutable_set_types += (Set,)74+except ImportError:75+ pass76+77+#: register Python 2.6 abstract base classes78+_mutable_set_types += (abc.MutableSet,)79+_mutable_mapping_types += (abc.MutableMapping,)80+_mutable_sequence_types += (abc.MutableSequence,)81+82+_mutable_spec = (83+ (84+ _mutable_set_types,85+ frozenset(86+ [87+ "add",88+ "clear",89+ "difference_update",90+ "discard",91+ "pop",92+ "remove",93+ "symmetric_difference_update",94+ "update",95+ ]96+ ),97+ ),98+ (99+ _mutable_mapping_types,100+ frozenset(["clear", "pop", "popitem", "setdefault", "update"]),101+ ),102+ (103+ _mutable_sequence_types,104+ frozenset(["append", "reverse", "insert", "sort", "extend", "remove"]),105+ ),106+ (107+ deque,108+ frozenset(109+ [110+ "append",111+ "appendleft",112+ "clear",113+ "extend",114+ "extendleft",115+ "pop",116+ "popleft",117+ "remove",118+ "rotate",119+ ]120+ ),121+ ),122+)123+124+125+class _MagicFormatMapping(abc.Mapping):126+ """This class implements a dummy wrapper to fix a bug in the Python127+ standard library for string formatting.128+129+ See https://bugs.python.org/issue13598 for information about why130+ this is necessary.131+ """132+133+ def __init__(self, args, kwargs):134+ self._args = args135+ self._kwargs = kwargs136+ self._last_index = 0137+138+ def __getitem__(self, key):139+ if key == "":140+ idx = self._last_index141+ self._last_index += 1142+ try:143+ return self._args[idx]144+ except LookupError:145+ pass146+ key = str(idx)147+ return self._kwargs[key]148+149+ def __iter__(self):150+ return iter(self._kwargs)151+152+ def __len__(self):153+ return len(self._kwargs)154+155+156+def inspect_format_method(callable):157+ if not isinstance(158+ callable, (types.MethodType, types.BuiltinMethodType)159+ ) or callable.__name__ not in ("format", "format_map"):160+ return None161+ obj = callable.__self__162+ if isinstance(obj, string_types):163+ return obj164+165+166+def safe_range(*args):167+ """A range that can't generate ranges with a length of more than168+ MAX_RANGE items.169+ """170+ rng = range_type(*args)171+172+ if len(rng) > MAX_RANGE:173+ raise OverflowError(174+ "Range too big. The sandbox blocks ranges larger than"175+ " MAX_RANGE (%d)." % MAX_RANGE176+ )177+178+ return rng179+180+181+def unsafe(f):182+ """Marks a function or method as unsafe.183+184+ ::185+186+ @unsafe187+ def delete(self):188+ pass189+ """190+ f.unsafe_callable = True191+ return f192+193+194+def is_internal_attribute(obj, attr):195+ """Test if the attribute given is an internal python attribute. For196+ example this function returns `True` for the `func_code` attribute of197+ python objects. This is useful if the environment method198+ :meth:`~SandboxedEnvironment.is_safe_attribute` is overridden.199+200+ >>> from jinja2.sandbox import is_internal_attribute201+ >>> is_internal_attribute(str, "mro")202+ True203+ >>> is_internal_attribute(str, "upper")204+ False205+ """206+ if isinstance(obj, types.FunctionType):207+ if attr in UNSAFE_FUNCTION_ATTRIBUTES:208+ return True209+ elif isinstance(obj, types.MethodType):210+ if attr in UNSAFE_FUNCTION_ATTRIBUTES or attr in UNSAFE_METHOD_ATTRIBUTES:211+ return True212+ elif isinstance(obj, type):213+ if attr == "mro":214+ return True215+ elif isinstance(obj, (types.CodeType, types.TracebackType, types.FrameType)):216+ return True217+ elif isinstance(obj, types.GeneratorType):218+ if attr in UNSAFE_GENERATOR_ATTRIBUTES:219+ return True220+ elif hasattr(types, "CoroutineType") and isinstance(obj, types.CoroutineType):221+ if attr in UNSAFE_COROUTINE_ATTRIBUTES:222+ return True223+ elif hasattr(types, "AsyncGeneratorType") and isinstance(224+ obj, types.AsyncGeneratorType225+ ):226+ if attr in UNSAFE_ASYNC_GENERATOR_ATTRIBUTES:227+ return True228+ return attr.startswith("__")229+230+231+def modifies_known_mutable(obj, attr):232+ """This function checks if an attribute on a builtin mutable object233+ (list, dict, set or deque) would modify it if called. It also supports234+ the "user"-versions of the objects (`sets.Set`, `UserDict.*` etc.) and235+ with Python 2.6 onwards the abstract base classes `MutableSet`,236+ `MutableMapping`, and `MutableSequence`.237+238+ >>> modifies_known_mutable({}, "clear")239+ True240+ >>> modifies_known_mutable({}, "keys")241+ False242+ >>> modifies_known_mutable([], "append")243+ True244+ >>> modifies_known_mutable([], "index")245+ False246+247+ If called with an unsupported object (such as unicode) `False` is248+ returned.249+250+ >>> modifies_known_mutable("foo", "upper")251+ False252+ """253+ for typespec, unsafe in _mutable_spec:254+ if isinstance(obj, typespec):255+ return attr in unsafe256+ return False257+258+259+class SandboxedEnvironment(Environment):260+ """The sandboxed environment. It works like the regular environment but261+ tells the compiler to generate sandboxed code. Additionally subclasses of262+ this environment may override the methods that tell the runtime what263+ attributes or functions are safe to access.264+265+ If the template tries to access insecure code a :exc:`SecurityError` is266+ raised. However also other exceptions may occur during the rendering so267+ the caller has to ensure that all exceptions are caught.268+ """269+270+ sandboxed = True271+272+ #: default callback table for the binary operators. A copy of this is273+ #: available on each instance of a sandboxed environment as274+ #: :attr:`binop_table`275+ default_binop_table = {276+ "+": operator.add,277+ "-": operator.sub,278+ "*": operator.mul,279+ "/": operator.truediv,280+ "//": operator.floordiv,281+ "**": operator.pow,282+ "%": operator.mod,283+ }284+285+ #: default callback table for the unary operators. A copy of this is286+ #: available on each instance of a sandboxed environment as287+ #: :attr:`unop_table`288+ default_unop_table = {"+": operator.pos, "-": operator.neg}289+290+ #: a set of binary operators that should be intercepted. Each operator291+ #: that is added to this set (empty by default) is delegated to the292+ #: :meth:`call_binop` method that will perform the operator. The default293+ #: operator callback is specified by :attr:`binop_table`.294+ #:295+ #: The following binary operators are interceptable:296+ #: ``//``, ``%``, ``+``, ``*``, ``-``, ``/``, and ``**``297+ #:298+ #: The default operation form the operator table corresponds to the299+ #: builtin function. Intercepted calls are always slower than the native300+ #: operator call, so make sure only to intercept the ones you are301+ #: interested in.302+ #:303+ #: .. versionadded:: 2.6304+ intercepted_binops = frozenset()305+306+ #: a set of unary operators that should be intercepted. Each operator307+ #: that is added to this set (empty by default) is delegated to the308+ #: :meth:`call_unop` method that will perform the operator. The default309+ #: operator callback is specified by :attr:`unop_table`.310+ #:311+ #: The following unary operators are interceptable: ``+``, ``-``312+ #:313+ #: The default operation form the operator table corresponds to the314+ #: builtin function. Intercepted calls are always slower than the native315+ #: operator call, so make sure only to intercept the ones you are316+ #: interested in.317+ #:318+ #: .. versionadded:: 2.6319+ intercepted_unops = frozenset()320+321+ def intercept_unop(self, operator):322+ """Called during template compilation with the name of a unary323+ operator to check if it should be intercepted at runtime. If this324+ method returns `True`, :meth:`call_unop` is executed for this unary325+ operator. The default implementation of :meth:`call_unop` will use326+ the :attr:`unop_table` dictionary to perform the operator with the327+ same logic as the builtin one.328+329+ The following unary operators are interceptable: ``+`` and ``-``330+331+ Intercepted calls are always slower than the native operator call,332+ so make sure only to intercept the ones you are interested in.333+334+ .. versionadded:: 2.6335+ """336+ return False337+338+ def __init__(self, *args, **kwargs):339+ Environment.__init__(self, *args, **kwargs)340+ self.globals["range"] = safe_range341+ self.binop_table = self.default_binop_table.copy()342+ self.unop_table = self.default_unop_table.copy()343+344+ def is_safe_attribute(self, obj, attr, value):345+ """The sandboxed environment will call this method to check if the346+ attribute of an object is safe to access. Per default all attributes347+ starting with an underscore are considered private as well as the348+ special attributes of internal python objects as returned by the349+ :func:`is_internal_attribute` function.350+ """351+ return not (attr.startswith("_") or is_internal_attribute(obj, attr))352+353+ def is_safe_callable(self, obj):354+ """Check if an object is safely callable. Per default a function is355+ considered safe unless the `unsafe_callable` attribute exists and is356+ True. Override this method to alter the behavior, but this won't357+ affect the `unsafe` decorator from this module.358+ """359+ return not (360+ getattr(obj, "unsafe_callable", False) or getattr(obj, "alters_data", False)361+ )362+363+ def call_binop(self, context, operator, left, right):364+ """For intercepted binary operator calls (:meth:`intercepted_binops`)365+ this function is executed instead of the builtin operator. This can366+ be used to fine tune the behavior of certain operators.367+368+ .. versionadded:: 2.6369+ """370+ return self.binop_table[operator](left, right)371+372+ def call_unop(self, context, operator, arg):373+ """For intercepted unary operator calls (:meth:`intercepted_unops`)374+ this function is executed instead of the builtin operator. This can375+ be used to fine tune the behavior of certain operators.376+377+ .. versionadded:: 2.6378+ """379+ return self.unop_table[operator](arg)380+381+ def getitem(self, obj, argument):382+ """Subscribe an object from sandboxed code."""383+ try:384+ return obj[argument]385+ except (TypeError, LookupError):386+ if isinstance(argument, string_types):387+ try:388+ attr = str(argument)389+ except Exception:390+ pass391+ else:392+ try:393+ value = getattr(obj, attr)394+ except AttributeError:395+ pass396+ else:397+ if self.is_safe_attribute(obj, argument, value):398+ return value399+ return self.unsafe_undefined(obj, argument)400+ return self.undefined(obj=obj, name=argument)401+402+ def getattr(self, obj, attribute):403+ """Subscribe an object from sandboxed code and prefer the404+ attribute. The attribute passed *must* be a bytestring.405+ """406+ try:407+ value = getattr(obj, attribute)408+ except AttributeError:409+ try:410+ return obj[attribute]411+ except (TypeError, LookupError):412+ pass413+ else:414+ if self.is_safe_attribute(obj, attribute, value):415+ return value416+ return self.unsafe_undefined(obj, attribute)417+ return self.undefined(obj=obj, name=attribute)418+419+ def unsafe_undefined(self, obj, attribute):420+ """Return an undefined object for unsafe attributes."""421+ return self.undefined(422+ "access to attribute %r of %r "423+ "object is unsafe." % (attribute, obj.__class__.__name__),424+ name=attribute,425+ obj=obj,426+ exc=SecurityError,427+ )428+429+ def format_string(self, s, args, kwargs, format_func=None):430+ """If a format call is detected, then this is routed through this431+ method so that our safety sandbox can be used for it.432+ """433+ if isinstance(s, Markup):434+ formatter = SandboxedEscapeFormatter(self, s.escape)435+ else:436+ formatter = SandboxedFormatter(self)437+438+ if format_func is not None and format_func.__name__ == "format_map":439+ if len(args) != 1 or kwargs:440+ raise TypeError(441+ "format_map() takes exactly one argument %d given"442+ % (len(args) + (kwargs is not None))443+ )444+445+ kwargs = args[0]446+ args = None447+448+ kwargs = _MagicFormatMapping(args, kwargs)449+ rv = formatter.vformat(s, args, kwargs)450+ return type(s)(rv)451+452+ def call(__self, __context, __obj, *args, **kwargs): # noqa: B902453+ """Call an object from sandboxed code."""454+ fmt = inspect_format_method(__obj)455+ if fmt is not None:456+ return __self.format_string(fmt, args, kwargs, __obj)457+458+ # the double prefixes are to avoid double keyword argument459+ # errors when proxying the call.460+ if not __self.is_safe_callable(__obj):461+ raise SecurityError("%r is not safely callable" % (__obj,))462+ return __context.call(__obj, *args, **kwargs)463+464+465+class ImmutableSandboxedEnvironment(SandboxedEnvironment):466+ """Works exactly like the regular `SandboxedEnvironment` but does not467+ permit modifications on the builtin mutable objects `list`, `set`, and468+ `dict` by using the :func:`modifies_known_mutable` function.469+ """470+471+ def is_safe_attribute(self, obj, attr, value):472+ if not SandboxedEnvironment.is_safe_attribute(self, obj, attr, value):473+ return False474+ return not modifies_known_mutable(obj, attr)475+476+477+# This really is not a public API apparently.478+try:479+ from _string import formatter_field_name_split480+except ImportError:481+482+ def formatter_field_name_split(field_name):483+ return field_name._formatter_field_name_split()484+485+486+class SandboxedFormatterMixin(object):487+ def __init__(self, env):488+ self._env = env489+490+ def get_field(self, field_name, args, kwargs):491+ first, rest = formatter_field_name_split(field_name)492+ obj = self.get_value(first, args, kwargs)493+ for is_attr, i in rest:494+ if is_attr:495+ obj = self._env.getattr(obj, i)496+ else:497+ obj = self._env.getitem(obj, i)498+ return obj, first499+500+501+class SandboxedFormatter(SandboxedFormatterMixin, Formatter):502+ def __init__(self, env):503+ SandboxedFormatterMixin.__init__(self, env)504+ Formatter.__init__(self)505+506+507+class SandboxedEscapeFormatter(SandboxedFormatterMixin, EscapeFormatter):508+ def __init__(self, env, escape):509+ SandboxedFormatterMixin.__init__(self, env)510+ EscapeFormatter.__init__(self, escape)added:src/jinja2/tests.py+215 added
1+# -*- coding: utf-8 -*-2+"""Built-in template tests used with the ``is`` operator."""3+import decimal4+import operator5+import re6+7+from ._compat import abc8+from ._compat import integer_types9+from ._compat import string_types10+from ._compat import text_type11+from .runtime import Undefined12+13+number_re = re.compile(r"^-?\d+(\.\d+)?$")14+regex_type = type(number_re)15+test_callable = callable16+17+18+def test_odd(value):19+ """Return true if the variable is odd."""20+ return value % 2 == 121+22+23+def test_even(value):24+ """Return true if the variable is even."""25+ return value % 2 == 026+27+28+def test_divisibleby(value, num):29+ """Check if a variable is divisible by a number."""30+ return value % num == 031+32+33+def test_defined(value):34+ """Return true if the variable is defined:35+36+ .. sourcecode:: jinja37+38+ {% if variable is defined %}39+ value of variable: {{ variable }}40+ {% else %}41+ variable is not defined42+ {% endif %}43+44+ See the :func:`default` filter for a simple way to set undefined45+ variables.46+ """47+ return not isinstance(value, Undefined)48+49+50+def test_undefined(value):51+ """Like :func:`defined` but the other way round."""52+ return isinstance(value, Undefined)53+54+55+def test_none(value):56+ """Return true if the variable is none."""57+ return value is None58+59+60+def test_boolean(value):61+ """Return true if the object is a boolean value.62+63+ .. versionadded:: 2.1164+ """65+ return value is True or value is False66+67+68+def test_false(value):69+ """Return true if the object is False.70+71+ .. versionadded:: 2.1172+ """73+ return value is False74+75+76+def test_true(value):77+ """Return true if the object is True.78+79+ .. versionadded:: 2.1180+ """81+ return value is True82+83+84+# NOTE: The existing 'number' test matches booleans and floats85+def test_integer(value):86+ """Return true if the object is an integer.87+88+ .. versionadded:: 2.1189+ """90+ return isinstance(value, integer_types) and value is not True and value is not False91+92+93+# NOTE: The existing 'number' test matches booleans and integers94+def test_float(value):95+ """Return true if the object is a float.96+97+ .. versionadded:: 2.1198+ """99+ return isinstance(value, float)100+101+102+def test_lower(value):103+ """Return true if the variable is lowercased."""104+ return text_type(value).islower()105+106+107+def test_upper(value):108+ """Return true if the variable is uppercased."""109+ return text_type(value).isupper()110+111+112+def test_string(value):113+ """Return true if the object is a string."""114+ return isinstance(value, string_types)115+116+117+def test_mapping(value):118+ """Return true if the object is a mapping (dict etc.).119+120+ .. versionadded:: 2.6121+ """122+ return isinstance(value, abc.Mapping)123+124+125+def test_number(value):126+ """Return true if the variable is a number."""127+ return isinstance(value, integer_types + (float, complex, decimal.Decimal))128+129+130+def test_sequence(value):131+ """Return true if the variable is a sequence. Sequences are variables132+ that are iterable.133+ """134+ try:135+ len(value)136+ value.__getitem__137+ except Exception:138+ return False139+ return True140+141+142+def test_sameas(value, other):143+ """Check if an object points to the same memory address than another144+ object:145+146+ .. sourcecode:: jinja147+148+ {% if foo.attribute is sameas false %}149+ the foo attribute really is the `False` singleton150+ {% endif %}151+ """152+ return value is other153+154+155+def test_iterable(value):156+ """Check if it's possible to iterate over an object."""157+ try:158+ iter(value)159+ except TypeError:160+ return False161+ return True162+163+164+def test_escaped(value):165+ """Check if the value is escaped."""166+ return hasattr(value, "__html__")167+168+169+def test_in(value, seq):170+ """Check if value is in seq.171+172+ .. versionadded:: 2.10173+ """174+ return value in seq175+176+177+TESTS = {178+ "odd": test_odd,179+ "even": test_even,180+ "divisibleby": test_divisibleby,181+ "defined": test_defined,182+ "undefined": test_undefined,183+ "none": test_none,184+ "boolean": test_boolean,185+ "false": test_false,186+ "true": test_true,187+ "integer": test_integer,188+ "float": test_float,189+ "lower": test_lower,190+ "upper": test_upper,191+ "string": test_string,192+ "mapping": test_mapping,193+ "number": test_number,194+ "sequence": test_sequence,195+ "iterable": test_iterable,196+ "callable": test_callable,197+ "sameas": test_sameas,198+ "escaped": test_escaped,199+ "in": test_in,200+ "==": operator.eq,201+ "eq": operator.eq,202+ "equalto": operator.eq,203+ "!=": operator.ne,204+ "ne": operator.ne,205+ ">": operator.gt,206+ "gt": operator.gt,207+ "greaterthan": operator.gt,208+ "ge": operator.ge,209+ ">=": operator.ge,210+ "<": operator.lt,211+ "lt": operator.lt,212+ "lessthan": operator.lt,213+ "<=": operator.le,214+ "le": operator.le,215+}added:src/jinja2/utils.py+727 added
1+# -*- coding: utf-8 -*-2+import json3+import os4+import re5+import warnings6+from collections import deque7+from random import choice8+from random import randrange9+from threading import Lock10+11+from markupsafe import escape12+from markupsafe import Markup13+14+from ._compat import abc15+from ._compat import string_types16+from ._compat import text_type17+from ._compat import url_quote18+19+_word_split_re = re.compile(r"(\s+)")20+_punctuation_re = re.compile(21+ "^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$"22+ % (23+ "|".join(map(re.escape, ("(", "<", "<"))),24+ "|".join(map(re.escape, (".", ",", ")", ">", "\n", ">"))),25+ )26+)27+_simple_email_re = re.compile(r"^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$")28+_striptags_re = re.compile(r"(<!--.*?-->|<[^>]*>)")29+_entity_re = re.compile(r"&([^;]+);")30+_letters = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"31+_digits = "0123456789"32+33+# special singleton representing missing values for the runtime34+missing = type("MissingType", (), {"__repr__": lambda x: "missing"})()35+36+# internal code37+internal_code = set()38+39+concat = u"".join40+41+_slash_escape = "\\/" not in json.dumps("/")42+43+44+def contextfunction(f):45+ """This decorator can be used to mark a function or method context callable.46+ A context callable is passed the active :class:`Context` as first argument when47+ called from the template. This is useful if a function wants to get access48+ to the context or functions provided on the context object. For example49+ a function that returns a sorted list of template variables the current50+ template exports could look like this::51+52+ @contextfunction53+ def get_exported_names(context):54+ return sorted(context.exported_vars)55+ """56+ f.contextfunction = True57+ return f58+59+60+def evalcontextfunction(f):61+ """This decorator can be used to mark a function or method as an eval62+ context callable. This is similar to the :func:`contextfunction`63+ but instead of passing the context, an evaluation context object is64+ passed. For more information about the eval context, see65+ :ref:`eval-context`.66+67+ .. versionadded:: 2.468+ """69+ f.evalcontextfunction = True70+ return f71+72+73+def environmentfunction(f):74+ """This decorator can be used to mark a function or method as environment75+ callable. This decorator works exactly like the :func:`contextfunction`76+ decorator just that the first argument is the active :class:`Environment`77+ and not context.78+ """79+ f.environmentfunction = True80+ return f81+82+83+def internalcode(f):84+ """Marks the function as internally used"""85+ internal_code.add(f.__code__)86+ return f87+88+89+def is_undefined(obj):90+ """Check if the object passed is undefined. This does nothing more than91+ performing an instance check against :class:`Undefined` but looks nicer.92+ This can be used for custom filters or tests that want to react to93+ undefined variables. For example a custom default filter can look like94+ this::95+96+ def default(var, default=''):97+ if is_undefined(var):98+ return default99+ return var100+ """101+ from .runtime import Undefined102+103+ return isinstance(obj, Undefined)104+105+106+def consume(iterable):107+ """Consumes an iterable without doing anything with it."""108+ for _ in iterable:109+ pass110+111+112+def clear_caches():113+ """Jinja keeps internal caches for environments and lexers. These are114+ used so that Jinja doesn't have to recreate environments and lexers all115+ the time. Normally you don't have to care about that but if you are116+ measuring memory consumption you may want to clean the caches.117+ """118+ from .environment import _spontaneous_environments119+ from .lexer import _lexer_cache120+121+ _spontaneous_environments.clear()122+ _lexer_cache.clear()123+124+125+def import_string(import_name, silent=False):126+ """Imports an object based on a string. This is useful if you want to127+ use import paths as endpoints or something similar. An import path can128+ be specified either in dotted notation (``xml.sax.saxutils.escape``)129+ or with a colon as object delimiter (``xml.sax.saxutils:escape``).130+131+ If the `silent` is True the return value will be `None` if the import132+ fails.133+134+ :return: imported object135+ """136+ try:137+ if ":" in import_name:138+ module, obj = import_name.split(":", 1)139+ elif "." in import_name:140+ module, _, obj = import_name.rpartition(".")141+ else:142+ return __import__(import_name)143+ return getattr(__import__(module, None, None, [obj]), obj)144+ except (ImportError, AttributeError):145+ if not silent:146+ raise147+148+149+def open_if_exists(filename, mode="rb"):150+ """Returns a file descriptor for the filename if that file exists,151+ otherwise ``None``.152+ """153+ if not os.path.isfile(filename):154+ return None155+156+ return open(filename, mode)157+158+159+def object_type_repr(obj):160+ """Returns the name of the object's type. For some recognized161+ singletons the name of the object is returned instead. (For162+ example for `None` and `Ellipsis`).163+ """164+ if obj is None:165+ return "None"166+ elif obj is Ellipsis:167+ return "Ellipsis"168+ # __builtin__ in 2.x, builtins in 3.x169+ if obj.__class__.__module__ in ("__builtin__", "builtins"):170+ name = obj.__class__.__name__171+ else:172+ name = obj.__class__.__module__ + "." + obj.__class__.__name__173+ return "%s object" % name174+175+176+def pformat(obj, verbose=False):177+ """Prettyprint an object. Either use the `pretty` library or the178+ builtin `pprint`.179+ """180+ try:181+ from pretty import pretty182+183+ return pretty(obj, verbose=verbose)184+ except ImportError:185+ from pprint import pformat186+187+ return pformat(obj)188+189+190+def urlize(text, trim_url_limit=None, rel=None, target=None):191+ """Converts any URLs in text into clickable links. Works on http://,192+ https:// and www. links. Links can have trailing punctuation (periods,193+ commas, close-parens) and leading punctuation (opening parens) and194+ it'll still do the right thing.195+196+ If trim_url_limit is not None, the URLs in link text will be limited197+ to trim_url_limit characters.198+199+ If nofollow is True, the URLs in link text will get a rel="nofollow"200+ attribute.201+202+ If target is not None, a target attribute will be added to the link.203+ """204+ trim_url = (205+ lambda x, limit=trim_url_limit: limit is not None206+ and (x[:limit] + (len(x) >= limit and "..." or ""))207+ or x208+ )209+ words = _word_split_re.split(text_type(escape(text)))210+ rel_attr = rel and ' rel="%s"' % text_type(escape(rel)) or ""211+ target_attr = target and ' target="%s"' % escape(target) or ""212+213+ for i, word in enumerate(words):214+ match = _punctuation_re.match(word)215+ if match:216+ lead, middle, trail = match.groups()217+ if middle.startswith("www.") or (218+ "@" not in middle219+ and not middle.startswith("http://")220+ and not middle.startswith("https://")221+ and len(middle) > 0222+ and middle[0] in _letters + _digits223+ and (224+ middle.endswith(".org")225+ or middle.endswith(".net")226+ or middle.endswith(".com")227+ )228+ ):229+ middle = '<a href="http://%s"%s%s>%s</a>' % (230+ middle,231+ rel_attr,232+ target_attr,233+ trim_url(middle),234+ )235+ if middle.startswith("http://") or middle.startswith("https://"):236+ middle = '<a href="%s"%s%s>%s</a>' % (237+ middle,238+ rel_attr,239+ target_attr,240+ trim_url(middle),241+ )242+ if (243+ "@" in middle244+ and not middle.startswith("www.")245+ and ":" not in middle246+ and _simple_email_re.match(middle)247+ ):248+ middle = '<a href="mailto:%s">%s</a>' % (middle, middle)249+ if lead + middle + trail != word:250+ words[i] = lead + middle + trail251+ return u"".join(words)252+253+254+def generate_lorem_ipsum(n=5, html=True, min=20, max=100):255+ """Generate some lorem ipsum for the template."""256+ from .constants import LOREM_IPSUM_WORDS257+258+ words = LOREM_IPSUM_WORDS.split()259+ result = []260+261+ for _ in range(n):262+ next_capitalized = True263+ last_comma = last_fullstop = 0264+ word = None265+ last = None266+ p = []267+268+ # each paragraph contains out of 20 to 100 words.269+ for idx, _ in enumerate(range(randrange(min, max))):270+ while True:271+ word = choice(words)272+ if word != last:273+ last = word274+ break275+ if next_capitalized:276+ word = word.capitalize()277+ next_capitalized = False278+ # add commas279+ if idx - randrange(3, 8) > last_comma:280+ last_comma = idx281+ last_fullstop += 2282+ word += ","283+ # add end of sentences284+ if idx - randrange(10, 20) > last_fullstop:285+ last_comma = last_fullstop = idx286+ word += "."287+ next_capitalized = True288+ p.append(word)289+290+ # ensure that the paragraph ends with a dot.291+ p = u" ".join(p)292+ if p.endswith(","):293+ p = p[:-1] + "."294+ elif not p.endswith("."):295+ p += "."296+ result.append(p)297+298+ 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))301+302+303+def unicode_urlencode(obj, charset="utf-8", for_qs=False):304+ """Quote a string for use in a URL using the given charset.305+306+ This function is misnamed, it is a wrapper around307+ :func:`urllib.parse.quote`.308+309+ :param obj: String or bytes to quote. Other types are converted to310+ string then encoded to bytes using the given charset.311+ :param charset: Encode text to bytes using this charset.312+ :param for_qs: Quote "/" and use "+" for spaces.313+ """314+ if not isinstance(obj, string_types):315+ obj = text_type(obj)316+317+ if isinstance(obj, text_type):318+ obj = obj.encode(charset)319+320+ safe = b"" if for_qs else b"/"321+ rv = url_quote(obj, safe)322+323+ if not isinstance(rv, text_type):324+ rv = rv.decode("utf-8")325+326+ if for_qs:327+ rv = rv.replace("%20", "+")328+329+ return rv330+331+332+class LRUCache(object):333+ """A simple LRU Cache implementation."""334+335+ # this is fast for small capacities (something below 1000) but doesn't336+ # scale. But as long as it's only used as storage for templates this337+ # won't do any harm.338+339+ def __init__(self, capacity):340+ self.capacity = capacity341+ self._mapping = {}342+ self._queue = deque()343+ self._postinit()344+345+ def _postinit(self):346+ # alias all queue methods for faster lookup347+ self._popleft = self._queue.popleft348+ self._pop = self._queue.pop349+ self._remove = self._queue.remove350+ self._wlock = Lock()351+ self._append = self._queue.append352+353+ def __getstate__(self):354+ return {355+ "capacity": self.capacity,356+ "_mapping": self._mapping,357+ "_queue": self._queue,358+ }359+360+ def __setstate__(self, d):361+ self.__dict__.update(d)362+ self._postinit()363+364+ def __getnewargs__(self):365+ return (self.capacity,)366+367+ def copy(self):368+ """Return a shallow copy of the instance."""369+ rv = self.__class__(self.capacity)370+ rv._mapping.update(self._mapping)371+ rv._queue.extend(self._queue)372+ return rv373+374+ def get(self, key, default=None):375+ """Return an item from the cache dict or `default`"""376+ try:377+ return self[key]378+ except KeyError:379+ return default380+381+ def setdefault(self, key, default=None):382+ """Set `default` if the key is not in the cache otherwise383+ leave unchanged. Return the value of this key.384+ """385+ try:386+ return self[key]387+ except KeyError:388+ self[key] = default389+ return default390+391+ def clear(self):392+ """Clear the cache."""393+ self._wlock.acquire()394+ try:395+ self._mapping.clear()396+ self._queue.clear()397+ finally:398+ self._wlock.release()399+400+ def __contains__(self, key):401+ """Check if a key exists in this cache."""402+ return key in self._mapping403+404+ def __len__(self):405+ """Return the current size of the cache."""406+ return len(self._mapping)407+408+ def __repr__(self):409+ return "<%s %r>" % (self.__class__.__name__, self._mapping)410+411+ def __getitem__(self, key):412+ """Get an item from the cache. Moves the item up so that it has the413+ highest priority then.414+415+ Raise a `KeyError` if it does not exist.416+ """417+ self._wlock.acquire()418+ try:419+ rv = self._mapping[key]420+ if self._queue[-1] != key:421+ try:422+ self._remove(key)423+ except ValueError:424+ # if something removed the key from the container425+ # when we read, ignore the ValueError that we would426+ # get otherwise.427+ pass428+ self._append(key)429+ return rv430+ finally:431+ self._wlock.release()432+433+ def __setitem__(self, key, value):434+ """Sets the value for an item. Moves the item up so that it435+ has the highest priority then.436+ """437+ self._wlock.acquire()438+ try:439+ if key in self._mapping:440+ self._remove(key)441+ elif len(self._mapping) == self.capacity:442+ del self._mapping[self._popleft()]443+ self._append(key)444+ self._mapping[key] = value445+ finally:446+ self._wlock.release()447+448+ def __delitem__(self, key):449+ """Remove an item from the cache dict.450+ Raise a `KeyError` if it does not exist.451+ """452+ self._wlock.acquire()453+ try:454+ del self._mapping[key]455+ try:456+ self._remove(key)457+ except ValueError:458+ pass459+ finally:460+ self._wlock.release()461+462+ def items(self):463+ """Return a list of items."""464+ result = [(key, self._mapping[key]) for key in list(self._queue)]465+ result.reverse()466+ return result467+468+ 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())477+478+ def values(self):479+ """Return a list of all values."""480+ return [x[1] for x in self.items()]481+482+ 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())491+492+ 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())501+502+ def keys(self):503+ """Return a list of all keys ordered by most recent usage."""504+ return list(self)505+506+ 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)517+518+ def __iter__(self):519+ return reversed(tuple(self._queue))520+521+ def __reversed__(self):522+ """Iterate over the keys in the cache dict, oldest items523+ coming first.524+ """525+ return iter(tuple(self._queue))526+527+ __copy__ = copy528+529+530+abc.MutableMapping.register(LRUCache)531+532+533+def select_autoescape(534+ enabled_extensions=("html", "htm", "xml"),535+ disabled_extensions=(),536+ default_for_string=True,537+ default=False,538+):539+ """Intelligently sets the initial value of autoescaping based on the540+ filename of the template. This is the recommended way to configure541+ autoescaping if you do not want to write a custom function yourself.542+543+ If you want to enable it for all templates created from strings or544+ for all templates with `.html` and `.xml` extensions::545+546+ from jinja2 import Environment, select_autoescape547+ env = Environment(autoescape=select_autoescape(548+ enabled_extensions=('html', 'xml'),549+ default_for_string=True,550+ ))551+552+ Example configuration to turn it on at all times except if the template553+ ends with `.txt`::554+555+ from jinja2 import Environment, select_autoescape556+ env = Environment(autoescape=select_autoescape(557+ disabled_extensions=('txt',),558+ default_for_string=True,559+ default=True,560+ ))561+562+ The `enabled_extensions` is an iterable of all the extensions that563+ autoescaping should be enabled for. Likewise `disabled_extensions` is564+ a list of all templates it should be disabled for. If a template is565+ loaded from a string then the default from `default_for_string` is used.566+ If nothing matches then the initial value of autoescaping is set to the567+ value of `default`.568+569+ For security reasons this function operates case insensitive.570+571+ .. versionadded:: 2.9572+ """573+ enabled_patterns = tuple("." + x.lstrip(".").lower() for x in enabled_extensions)574+ disabled_patterns = tuple("." + x.lstrip(".").lower() for x in disabled_extensions)575+576+ def autoescape(template_name):577+ if template_name is None:578+ return default_for_string579+ template_name = template_name.lower()580+ if template_name.endswith(enabled_patterns):581+ return True582+ if template_name.endswith(disabled_patterns):583+ return False584+ return default585+586+ return autoescape587+588+589+def htmlsafe_json_dumps(obj, dumper=None, **kwargs):590+ """Works exactly like :func:`dumps` but is safe for use in ``<script>``591+ tags. It accepts the same arguments and returns a JSON string. Note that592+ this is available in templates through the ``|tojson`` filter which will593+ also mark the result as safe. Due to how this function escapes certain594+ characters this is safe even if used outside of ``<script>`` tags.595+596+ The following characters are escaped in strings:597+598+ - ``<``599+ - ``>``600+ - ``&``601+ - ``'``602+603+ This makes it safe to embed such strings in any place in HTML with the604+ notable exception of double quoted attributes. In that case single605+ quote your attributes or HTML escape it in addition.606+ """607+ if dumper is None:608+ dumper = json.dumps609+ rv = (610+ dumper(obj, **kwargs)611+ .replace(u"<", u"\\u003c")612+ .replace(u">", u"\\u003e")613+ .replace(u"&", u"\\u0026")614+ .replace(u"'", u"\\u0027")615+ )616+ return Markup(rv)617+618+619+class Cycler(object):620+ """Cycle through values by yield them one at a time, then restarting621+ once the end is reached. Available as ``cycler`` in templates.622+623+ Similar to ``loop.cycle``, but can be used outside loops or across624+ multiple loops. For example, render a list of folders and files in a625+ list, alternating giving them "odd" and "even" classes.626+627+ .. code-block:: html+jinja628+629+ {% set row_class = cycler("odd", "even") %}630+ <ul class="browser">631+ {% for folder in folders %}632+ <li class="folder {{ row_class.next() }}">{{ folder }}633+ {% endfor %}634+ {% for file in files %}635+ <li class="file {{ row_class.next() }}">{{ file }}636+ {% endfor %}637+ </ul>638+639+ :param items: Each positional argument will be yielded in the order640+ given for each cycle.641+642+ .. versionadded:: 2.1643+ """644+645+ def __init__(self, *items):646+ if not items:647+ raise RuntimeError("at least one item has to be provided")648+ self.items = items649+ self.pos = 0650+651+ def reset(self):652+ """Resets the current item to the first item."""653+ self.pos = 0654+655+ @property656+ def current(self):657+ """Return the current item. Equivalent to the item that will be658+ returned next time :meth:`next` is called.659+ """660+ return self.items[self.pos]661+662+ def next(self):663+ """Return the current item, then advance :attr:`current` to the664+ next item.665+ """666+ rv = self.current667+ self.pos = (self.pos + 1) % len(self.items)668+ return rv669+670+ __next__ = next671+672+673+class Joiner(object):674+ """A joining helper for templates."""675+676+ def __init__(self, sep=u", "):677+ self.sep = sep678+ self.used = False679+680+ def __call__(self):681+ if not self.used:682+ self.used = True683+ return u""684+ return self.sep685+686+687+class Namespace(object):688+ """A namespace object that can hold arbitrary attributes. It may be689+ initialized from a dictionary or with keyword arguments."""690+691+ def __init__(*args, **kwargs): # noqa: B902692+ self, args = args[0], args[1:]693+ self.__attrs = dict(*args, **kwargs)694+695+ def __getattribute__(self, name):696+ if name == "_Namespace__attrs":697+ return object.__getattribute__(self, name)698+ try:699+ return self.__attrs[name]700+ except KeyError:701+ raise AttributeError(name)702+703+ def __setitem__(self, name, value):704+ self.__attrs[name] = value705+706+ def __repr__(self):707+ return "<Namespace %r>" % self.__attrs708+709+710+# does this python version support async for in and async generators?711+try:712+ exec("async def _():\n async for _ in ():\n yield _")713+ have_async_gen = True714+except SyntaxError:715+ have_async_gen = False716+717+718+def soft_unicode(s):719+ from markupsafe import soft_unicode720+721+ 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)added:src/jinja2/visitor.py+81 added
1+# -*- coding: utf-8 -*-2+"""API for traversing the AST nodes. Implemented by the compiler and3+meta introspection.4+"""5+from .nodes import Node6+7+8+class NodeVisitor(object):9+ """Walks the abstract syntax tree and call visitor functions for every10+ node found. The visitor functions may return values which will be11+ forwarded by the `visit` method.12+13+ Per default the visitor functions for the nodes are ``'visit_'`` +14+ class name of the node. So a `TryFinally` node visit function would15+ be `visit_TryFinally`. This behavior can be changed by overriding16+ the `get_visitor` function. If no visitor function exists for a node17+ (return value `None`) the `generic_visit` visitor is used instead.18+ """19+20+ def get_visitor(self, node):21+ """Return the visitor function for this node or `None` if no visitor22+ exists for this node. In that case the generic visit function is23+ used instead.24+ """25+ method = "visit_" + node.__class__.__name__26+ return getattr(self, method, None)27+28+ def visit(self, node, *args, **kwargs):29+ """Visit a node."""30+ f = self.get_visitor(node)31+ if f is not None:32+ return f(node, *args, **kwargs)33+ return self.generic_visit(node, *args, **kwargs)34+35+ def generic_visit(self, node, *args, **kwargs):36+ """Called if no explicit visitor function exists for a node."""37+ for node in node.iter_child_nodes():38+ self.visit(node, *args, **kwargs)39+40+41+class NodeTransformer(NodeVisitor):42+ """Walks the abstract syntax tree and allows modifications of nodes.43+44+ The `NodeTransformer` will walk the AST and use the return value of the45+ visitor functions to replace or remove the old node. If the return46+ value of the visitor function is `None` the node will be removed47+ from the previous location otherwise it's replaced with the return48+ value. The return value may be the original node in which case no49+ replacement takes place.50+ """51+52+ def generic_visit(self, node, *args, **kwargs):53+ for field, old_value in node.iter_fields():54+ if isinstance(old_value, list):55+ new_values = []56+ for value in old_value:57+ if isinstance(value, Node):58+ value = self.visit(value, *args, **kwargs)59+ if value is None:60+ continue61+ elif not isinstance(value, Node):62+ new_values.extend(value)63+ continue64+ new_values.append(value)65+ old_value[:] = new_values66+ elif isinstance(old_value, Node):67+ new_node = self.visit(old_value, *args, **kwargs)68+ if new_node is None:69+ delattr(node, field)70+ else:71+ setattr(node, field, new_node)72+ return node73+74+ def visit_list(self, node, *args, **kwargs):75+ """As transformers may return lists in some places this method76+ can be used to enforce a list as return value.77+ """78+ rv = self.visit(node, *args, **kwargs)79+ if not isinstance(rv, list):80+ rv = [rv]81+ return rvadded:tests/res/templates/mojibake.txt+1 added
1+文字化けdeleted:tests/res/templates/variable_encoding.txt-1 removed
1-techmodified:tests/conftest.py+53 added-73 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.conftest4- ~~~~~~~~~~~~~~~~~~~~~~~~~2+import os3 6- Configuration and Fixtures for the tests7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""4 import pytest12-import os5 6+from jinja2 import Environment7 from jinja2 import loaders8 from jinja2.utils import have_async_gen16-from jinja2 import Environment9 10 11 def pytest_ignore_collect(path):20- if 'async' in path.basename and not have_async_gen:12+ if "async" in path.basename and not have_async_gen:13 return True14 return False15 16 17 def pytest_configure(config):26- '''Register custom marks for test categories.'''18+ """Register custom marks for test categories."""19 custom_markers = [28- 'api',29- 'byte_code_cache',30- 'core_tags',31- 'debug',32- 'escapeUrlizeTarget',33- 'ext',34- 'extended',35- 'filesystemloader',36- 'filter',37- 'for_loop',38- 'helpers',39- 'if_condition',40- 'imports',41- 'includes',42- 'inheritance',43- 'lexer',44- 'lexnparse',45- 'loaders',46- 'loremIpsum',47- 'lowlevel',48- 'lrucache',49- 'lstripblocks',50- 'macros',51- 'meta',52- 'moduleloader',53- 'parser',54- 'regression',55- 'sandbox',56- 'set',57- 'streaming',58- 'syntax',59- 'test_tests',60- 'tokenstream',61- 'undefined',62- 'utils',63- 'with_',20+ "api",21+ "byte_code_cache",22+ "core_tags",23+ "debug",24+ "escapeUrlizeTarget",25+ "ext",26+ "extended",27+ "filesystemloader",28+ "filter",29+ "for_loop",30+ "helpers",31+ "if_condition",32+ "imports",33+ "includes",34+ "inheritance",35+ "lexer",36+ "lexnparse",37+ "loaders",38+ "loremIpsum",39+ "lowlevel",40+ "lrucache",41+ "lstripblocks",42+ "macros",43+ "meta",44+ "moduleloader",45+ "parser",46+ "regression",47+ "sandbox",48+ "set",49+ "streaming",50+ "syntax",51+ "test_tests",52+ "tokenstream",53+ "undefined",54+ "utils",55+ "with_",56 ]57 for mark in custom_markers:66- config.addinivalue_line('markers', mark + ': test category')58+ config.addinivalue_line("markers", mark + ": test category")59 60 61 @pytest.fixture62 def env():71- '''returns a new environment.72- '''63+ """returns a new environment."""64 return Environment()65 66 67 @pytest.fixture68 def dict_loader():78- '''returns DictLoader79- '''80- return loaders.DictLoader({81- 'justdict.html': 'FOO'82- })69+ """returns DictLoader"""70+ return loaders.DictLoader({"justdict.html": "FOO"})71 72 73 @pytest.fixture74 def package_loader():87- '''returns PackageLoader initialized from templates88- '''89- return loaders.PackageLoader('res', 'templates')75+ """returns PackageLoader initialized from templates"""76+ return loaders.PackageLoader("res", "templates")77 78 79 @pytest.fixture80 def filesystem_loader():94- '''returns FileSystemLoader initialized to res/templates directory95- '''81+ """returns FileSystemLoader initialized to res/templates directory"""82 here = os.path.dirname(os.path.abspath(__file__))97- return loaders.FileSystemLoader(here + '/res/templates')83+ return loaders.FileSystemLoader(here + "/res/templates")84 85 86 @pytest.fixture87 def function_loader():102- '''returns a FunctionLoader103- '''104- return loaders.FunctionLoader({'justfunction.html': 'FOO'}.get)88+ """returns a FunctionLoader"""89+ return loaders.FunctionLoader({"justfunction.html": "FOO"}.get)90 91 92 @pytest.fixture93 def choice_loader(dict_loader, package_loader):109- '''returns a ChoiceLoader110- '''94+ """returns a ChoiceLoader"""95 return loaders.ChoiceLoader([dict_loader, package_loader])96 97 98 @pytest.fixture99 def prefix_loader(filesystem_loader, dict_loader):116- '''returns a PrefixLoader117- '''118- return loaders.PrefixLoader({119- 'a': filesystem_loader,120- 'b': dict_loader121- })100+ """returns a PrefixLoader"""101+ return loaders.PrefixLoader({"a": filesystem_loader, "b": dict_loader})modified:tests/test_api.py+150 added-158 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.api4- ~~~~~~~~~~~~~~~~~~~~5-6- Tests the public API and related stuff.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import os12-import tempfile3 import shutil14-from io import StringIO4+import tempfile5 6 import pytest17-from jinja2 import Environment, Undefined, ChainableUndefined, \18- DebugUndefined, StrictUndefined, UndefinedError, meta, \19- is_undefined, Template, DictLoader, make_logging_undefined7+8+from jinja2 import ChainableUndefined9+from jinja2 import DebugUndefined10+from jinja2 import DictLoader11+from jinja2 import Environment12+from jinja2 import is_undefined13+from jinja2 import make_logging_undefined14+from jinja2 import meta15+from jinja2 import StrictUndefined16+from jinja2 import Template17 from jinja2 import TemplatesNotFound18+from jinja2 import Undefined19+from jinja2 import UndefinedError20 from jinja2.compiler import CodeGenerator21 from jinja2.runtime import Context23-from jinja2.utils import Cycler22 from jinja2.utils import contextfunction25-from jinja2.utils import evalcontextfunction23+from jinja2.utils import Cycler24 from jinja2.utils import environmentfunction25+from jinja2.utils import evalcontextfunction26 27 28 @pytest.mark.api29 @pytest.mark.extended30 class TestExtendedAPI(object):32-31 def test_item_and_attribute(self, env):32 from jinja2.sandbox import SandboxedEnvironment33 34 for env in Environment(), SandboxedEnvironment():35 # the |list is necessary for python338- tmpl = env.from_string('{{ foo.items()|list }}')39- assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"36+ tmpl = env.from_string("{{ foo.items()|list }}")37+ assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"38 tmpl = env.from_string('{{ foo|attr("items")()|list }}')41- assert tmpl.render(foo={'items': 42}) == "[('items', 42)]"39+ assert tmpl.render(foo={"items": 42}) == "[('items', 42)]"40 tmpl = env.from_string('{{ foo["items"] }}')43- assert tmpl.render(foo={'items': 42}) == '42'41+ assert tmpl.render(foo={"items": 42}) == "42"42 43 def test_finalize(self):44 e = Environment(finalize=lambda v: "" if v is None else v)45 t = e.from_string("{% for item in seq %}|{{ item }}{% endfor %}")49 unmodified lines95 assert c.current == 296 c.reset()97 assert c.current == 198 101- def test_cycler_nextmethod(self, env):102- items = 1, 2, 3103- c = Cycler(*items)104- for item in items + items:105- assert c.current == item106- assert c.next() == item107- c.next()108- assert c.current == 2109- c.reset()110- assert c.current == 1111-99 def test_expressions(self, env):100 expr = env.compile_expression("foo")101 assert expr() is None102 assert expr(foo=42) == 423 unmodified lines106 expr = env.compile_expression("42 + foo")107 assert expr(foo=42) == 84108 109 def test_template_passthrough(self, env):123- t = Template('Content')110+ t = Template("Content")111 assert env.get_template(t) is t112 assert env.select_template([t]) is t113 assert env.get_or_select_template([t]) is t114 assert env.get_or_select_template(t) is t1 unmodified line116 def test_get_template_undefined(self, env):117 """Passing Undefined to get/select_template raises an118 UndefinedError or shows the undefined message in the list.119 """133- env.loader=DictLoader({})120+ env.loader = DictLoader({})121 t = Undefined(name="no_name_1")122 123 with pytest.raises(UndefinedError):124 env.get_template(t)10 unmodified lines135 exc_message = str(exc_info.value)136 assert "'no_name_1' is undefined" in exc_message137 assert "no_name_2" in exc_message138 152-139 def test_autoescape_autoselect(self, env):140 def select_autoescape(name):155- if name is None or '.' not in name:141+ if name is None or "." not in name:142 return False157- return name.endswith('.html')158- env = Environment(autoescape=select_autoescape,159- loader=DictLoader({160- 'test.txt': '{{ foo }}',161- 'test.html': '{{ foo }}'162- }))163- t = env.get_template('test.txt')164- assert t.render(foo='<foo>') == '<foo>'165- t = env.get_template('test.html')166- assert t.render(foo='<foo>') == '<foo>'167- t = env.from_string('{{ foo }}')168- assert t.render(foo='<foo>') == '<foo>'143+ return name.endswith(".html")144 145+ env = Environment(146+ autoescape=select_autoescape,147+ loader=DictLoader({"test.txt": "{{ foo }}", "test.html": "{{ foo }}"}),148+ )149+ t = env.get_template("test.txt")150+ assert t.render(foo="<foo>") == "<foo>"151+ t = env.get_template("test.html")152+ assert t.render(foo="<foo>") == "<foo>"153+ t = env.from_string("{{ foo }}")154+ assert t.render(foo="<foo>") == "<foo>"155+156 def test_sandbox_max_range(self, env):157 from jinja2.sandbox import SandboxedEnvironment, MAX_RANGE158 159 env = SandboxedEnvironment()5 unmodified lines165 166 @pytest.mark.api167 @pytest.mark.meta168 class TestMeta(object):183-169 def test_find_undeclared_variables(self, env):185- ast = env.parse('{% set foo = 42 %}{{ bar + foo }}')170+ ast = env.parse("{% set foo = 42 %}{{ bar + foo }}")171 x = meta.find_undeclared_variables(ast)187- assert x == set(['bar'])172+ assert x == set(["bar"])173 189- ast = env.parse('{% set foo = 42 %}{{ bar + foo }}'190- '{% macro meh(x) %}{{ x }}{% endmacro %}'191- '{% for item in seq %}{{ muh(item) + meh(seq) }}'192- '{% endfor %}')174+ ast = env.parse(175+ "{% set foo = 42 %}{{ bar + foo }}"176+ "{% macro meh(x) %}{{ x }}{% endmacro %}"177+ "{% for item in seq %}{{ muh(item) + meh(seq) }}"178+ "{% endfor %}"179+ )180 x = meta.find_undeclared_variables(ast)194- assert x == set(['bar', 'seq', 'muh'])181+ assert x == set(["bar", "seq", "muh"])182 196- ast = env.parse('{% for x in range(5) %}{{ x }}{% endfor %}{{ foo }}')183+ ast = env.parse("{% for x in range(5) %}{{ x }}{% endfor %}{{ foo }}")184 x = meta.find_undeclared_variables(ast)198- assert x == set(['foo'])185+ assert x == set(["foo"])186 187 def test_find_refererenced_templates(self, env):188 ast = env.parse('{% extends "layout.html" %}{% include helper %}')189 i = meta.find_referenced_templates(ast)203- assert next(i) == 'layout.html'190+ assert next(i) == "layout.html"191 assert next(i) is None192 assert list(i) == []193 194+ ast = env.parse(207- ast = env.parse('{% extends "layout.html" %}'208- '{% from "test.html" import a, b as c %}'209- '{% import "meh.html" as meh %}'210- '{% include "muh.html" %}')195+ '{% extends "layout.html" %}'196+ '{% from "test.html" import a, b as c %}'197+ '{% import "meh.html" as meh %}'198+ '{% include "muh.html" %}'199+ )200 i = meta.find_referenced_templates(ast)212- assert list(i) == ['layout.html', 'test.html', 'meh.html', 'muh.html']201+ assert list(i) == ["layout.html", "test.html", "meh.html", "muh.html"]202 203 def test_find_included_templates(self, env):204 ast = env.parse('{% include ["foo.html", "bar.html"] %}')205 i = meta.find_referenced_templates(ast)217- assert list(i) == ['foo.html', 'bar.html']206+ assert list(i) == ["foo.html", "bar.html"]207 208 ast = env.parse('{% include ("foo.html", "bar.html") %}')209 i = meta.find_referenced_templates(ast)221- assert list(i) == ['foo.html', 'bar.html']210+ assert list(i) == ["foo.html", "bar.html"]211 212 ast = env.parse('{% include ["foo.html", "bar.html", foo] %}')213 i = meta.find_referenced_templates(ast)225- assert list(i) == ['foo.html', 'bar.html', None]214+ assert list(i) == ["foo.html", "bar.html", None]215 216 ast = env.parse('{% include ("foo.html", "bar.html", foo) %}')217 i = meta.find_referenced_templates(ast)229- assert list(i) == ['foo.html', 'bar.html', None]218+ assert list(i) == ["foo.html", "bar.html", None]219 220 221 @pytest.mark.api222 @pytest.mark.streaming13 unmodified lines236 "{%- endfor %}</ul>"237 )238 stream = tmpl.stream(seq=list(range(3)))239 stream.enable_buffering(size=3)251- assert next(stream) == u'<ul><li>1'252- assert next(stream) == u' - 0</li>'240+ assert next(stream) == u"<ul><li>1"241+ assert next(stream) == u" - 0</li>"242 243 def test_streaming_behavior(self, env):244 tmpl = env.from_string("")245 stream = tmpl.stream()7 unmodified lines253 tmp = tempfile.mkdtemp()254 try:255 tmpl = env.from_string(u"\u2713")256 stream = tmpl.stream()268- stream.dump(os.path.join(tmp, 'dump.txt'), 'utf-8')269- with open(os.path.join(tmp, 'dump.txt'), 'rb') as f:270- assert f.read() == b'\xe2\x9c\x93'257+ stream.dump(os.path.join(tmp, "dump.txt"), "utf-8")258+ with open(os.path.join(tmp, "dump.txt"), "rb") as f:259+ assert f.read() == b"\xe2\x9c\x93"260 finally:261 shutil.rmtree(tmp)262 263 264 @pytest.mark.api265 @pytest.mark.undefined266 class TestUndefined(object):278-267 def test_stopiteration_is_undefined(self):268 def test():269 raise StopIteration()270+282- t = Template('A{{ test() }}B')283- assert t.render(test=test) == 'AB'284- t = Template('A{{ test().missingattribute }}B')271+ t = Template("A{{ test() }}B")272+ assert t.render(test=test) == "AB"273+ t = Template("A{{ test().missingattribute }}B")274 pytest.raises(UndefinedError, t.render, test=test)275 276 def test_undefined_and_special_attributes(self):277 with pytest.raises(AttributeError):289- Undefined('Foo').__dict__278+ Undefined("Foo").__dict__279 280 def test_logging_undefined(self):281 _messages = []282 283 class DebugLogger(object):284 def warning(self, msg, *args):296- _messages.append('W:' + msg % args)285+ _messages.append("W:" + msg % args)286 287 def error(self, msg, *args):299- _messages.append('E:' + msg % args)288+ _messages.append("E:" + msg % args)289 290 logging_undefined = make_logging_undefined(DebugLogger())291 env = Environment(undefined=logging_undefined)303- assert env.from_string('{{ missing }}').render() == u''304- pytest.raises(UndefinedError,305- env.from_string('{{ missing.attribute }}').render)306- assert env.from_string('{{ missing|list }}').render() == '[]'307- assert env.from_string('{{ missing is not defined }}').render() \308- == 'True'309- assert env.from_string('{{ foo.missing }}').render(foo=42) == ''310- assert env.from_string('{{ not missing }}').render() == 'True'292+ assert env.from_string("{{ missing }}").render() == u""293+ pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)294+ assert env.from_string("{{ missing|list }}").render() == "[]"295+ assert env.from_string("{{ missing is not defined }}").render() == "True"296+ assert env.from_string("{{ foo.missing }}").render(foo=42) == ""297+ assert env.from_string("{{ not missing }}").render() == "True"298 assert _messages == [312- 'W:Template variable warning: missing is undefined',299+ "W:Template variable warning: missing is undefined",300 "E:Template variable error: 'missing' is undefined",314- 'W:Template variable warning: missing is undefined',315- 'W:Template variable warning: int object has no attribute missing',316- 'W:Template variable warning: 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",304 ]305 306 def test_default_undefined(self):307 env = Environment(undefined=Undefined)321- assert env.from_string('{{ missing }}').render() == u''322- pytest.raises(UndefinedError,323- env.from_string('{{ missing.attribute }}').render)324- assert env.from_string('{{ missing|list }}').render() == '[]'325- assert env.from_string('{{ missing is not defined }}').render() \326- == 'True'327- assert env.from_string('{{ foo.missing }}').render(foo=42) == ''328- assert env.from_string('{{ not missing }}').render() == 'True'329- pytest.raises(UndefinedError,330- env.from_string('{{ missing - 1}}').render)331- und1 = Undefined(name='x')332- und2 = Undefined(name='y')308+ assert env.from_string("{{ missing }}").render() == u""309+ pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)310+ assert env.from_string("{{ missing|list }}").render() == "[]"311+ assert env.from_string("{{ missing is not defined }}").render() == "True"312+ assert env.from_string("{{ foo.missing }}").render(foo=42) == ""313+ assert env.from_string("{{ not missing }}").render() == "True"314+ pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)315+ und1 = Undefined(name="x")316+ und2 = Undefined(name="y")317 assert und1 == und2318 assert und1 != 42319 assert hash(und1) == hash(und2) == hash(Undefined())320 with pytest.raises(AttributeError):337- getattr(Undefined, '__slots__')321+ getattr(Undefined, "__slots__") # noqa: B009322 323 def test_chainable_undefined(self):324 env = Environment(undefined=ChainableUndefined)325 # The following tests are copied from test_default_undefined342- assert env.from_string('{{ missing }}').render() == u''343- assert env.from_string('{{ missing|list }}').render() == '[]'344- assert env.from_string('{{ missing is not defined }}').render() \345- == 'True'346- assert env.from_string('{{ foo.missing }}').render(foo=42) == ''347- assert env.from_string('{{ not missing }}').render() == 'True'348- pytest.raises(UndefinedError,349- env.from_string('{{ missing - 1}}').render)326+ assert env.from_string("{{ missing }}").render() == u""327+ assert env.from_string("{{ missing|list }}").render() == "[]"328+ assert env.from_string("{{ missing is not defined }}").render() == "True"329+ assert env.from_string("{{ foo.missing }}").render(foo=42) == ""330+ assert env.from_string("{{ not missing }}").render() == "True"331+ pytest.raises(UndefinedError, env.from_string("{{ missing - 1}}").render)332 with pytest.raises(AttributeError):351- getattr(ChainableUndefined, '__slots__')333+ getattr(ChainableUndefined, "__slots__") # noqa: B009334 335 # The following tests ensure subclass functionality works as expected354- assert env.from_string('{{ missing.bar["baz"] }}').render() == u''355- assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() \356- == u'foo'357- assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(358- foo=42) == u'bar'359- assert env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(360- foo={'bar': 42}) == u'baz'336+ assert env.from_string('{{ missing.bar["baz"] }}').render() == u""337+ assert (338+ env.from_string('{{ foo.bar["baz"]._undefined_name }}').render() == u"foo"339+ )340+ assert (341+ env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(foo=42)342+ == u"bar"343+ )344+ assert (345+ env.from_string('{{ foo.bar["baz"]._undefined_name }}').render(346+ foo={"bar": 42}347+ )348+ == u"baz"349+ )350 351 def test_debug_undefined(self):352 env = Environment(undefined=DebugUndefined)364- assert env.from_string('{{ missing }}').render() == '{{ missing }}'365- pytest.raises(UndefinedError,366- env.from_string('{{ missing.attribute }}').render)367- assert env.from_string('{{ missing|list }}').render() == '[]'368- assert env.from_string('{{ missing is not defined }}').render() \369- == 'True'370- assert env.from_string('{{ foo.missing }}').render(foo=42) \353+ assert env.from_string("{{ missing }}").render() == "{{ missing }}"354+ pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)355+ assert env.from_string("{{ missing|list }}").render() == "[]"356+ assert env.from_string("{{ missing is not defined }}").render() == "True"357+ assert (358+ env.from_string("{{ foo.missing }}").render(foo=42)359 == u"{{ no such element: int object['missing'] }}"372- assert env.from_string('{{ not missing }}').render() == 'True'373- undefined_hint = 'this is testing undefined hint of DebugUndefined'374- assert str(DebugUndefined(hint=undefined_hint)) == u'{{ undefined value printed: %s }}' % undefined_hint360+ )361+ assert env.from_string("{{ not missing }}").render() == "True"362+ undefined_hint = "this is testing undefined hint of DebugUndefined"363+ assert (364+ str(DebugUndefined(hint=undefined_hint))365+ == u"{{ undefined value printed: %s }}" % undefined_hint366+ )367 with pytest.raises(AttributeError):376- getattr(DebugUndefined, '__slots__')368+ getattr(DebugUndefined, "__slots__") # noqa: B009369 370 def test_strict_undefined(self):371 env = Environment(undefined=StrictUndefined)380- pytest.raises(UndefinedError, env.from_string('{{ missing }}').render)381- pytest.raises(UndefinedError,382- env.from_string('{{ missing.attribute }}').render)383- pytest.raises(UndefinedError,384- env.from_string('{{ missing|list }}').render)385- assert env.from_string('{{ missing is not defined }}').render() \386- == 'True'387- pytest.raises(UndefinedError,388- env.from_string('{{ foo.missing }}').render, foo=42)389- pytest.raises(UndefinedError,390- env.from_string('{{ not missing }}').render)391- assert env.from_string('{{ missing|default("default", true) }}')\392- .render() == 'default'372+ pytest.raises(UndefinedError, env.from_string("{{ missing }}").render)373+ pytest.raises(UndefinedError, env.from_string("{{ missing.attribute }}").render)374+ pytest.raises(UndefinedError, env.from_string("{{ missing|list }}").render)375+ assert env.from_string("{{ missing is not defined }}").render() == "True"376+ pytest.raises(377+ UndefinedError, env.from_string("{{ foo.missing }}").render, foo=42378+ )379+ pytest.raises(UndefinedError, env.from_string("{{ not missing }}").render)380+ assert (381+ env.from_string('{{ missing|default("default", true) }}').render()382+ == "default"383+ )384 with pytest.raises(AttributeError):394- getattr(StrictUndefined, '__slots__')395- assert env.from_string('{{ "foo" if false }}').render() == ''385+ getattr(StrictUndefined, "__slots__") # noqa: B009386+ assert env.from_string('{{ "foo" if false }}').render() == ""387 388 def test_indexing_gives_undefined(self):389 t = Template("{{ var[42].foo }}")390 pytest.raises(UndefinedError, t.render, var=0)391 392 def test_none_gives_proper_error(self):402- with pytest.raises(UndefinedError, match= "'None' has no attribute 'split'"):403- Environment().getattr(None, 'split')()393+ with pytest.raises(UndefinedError, match="'None' has no attribute 'split'"):394+ Environment().getattr(None, "split")()395 396 def test_object_repr(self):406- with pytest.raises(UndefinedError, match="'int object' has no attribute 'upper'"):407- Undefined(obj=42, name='upper')()397+ with pytest.raises(398+ UndefinedError, match="'int object' has no attribute 'upper'"399+ ):400+ Undefined(obj=42, name="upper")()401 402 403 @pytest.mark.api404 @pytest.mark.lowlevel405 class TestLowLevel(object):413-406 def test_custom_code_generator(self):407 class CustomCodeGenerator(CodeGenerator):408 def visit_Const(self, node, frame=None):409 # This method is pure nonsense, but works fine for testing...418- if node.value == 'foo':419- self.write(repr('bar'))410+ if node.value == "foo":411+ self.write(repr("bar"))412 else:413 super(CustomCodeGenerator, self).visit_Const(node, frame)414 415 class CustomEnvironment(Environment):416 code_generator_class = CustomCodeGenerator417 418 env = CustomEnvironment()419 tmpl = env.from_string('{% set foo = "foo" %}{{ foo }}')428- assert tmpl.render() == 'bar'420+ assert tmpl.render() == "bar"421 422 def test_custom_context(self):423 class CustomContext(Context):424 def resolve_or_missing(self, key):433- return 'resolve-' + key425+ return "resolve-" + key426 427 class CustomEnvironment(Environment):428 context_class = CustomContext429 430 env = CustomEnvironment()439- tmpl = env.from_string('{{ foo }}')440- assert tmpl.render() == 'resolve-foo'431+ tmpl = env.from_string("{{ foo }}")432+ assert tmpl.render() == "resolve-foo"modified:tests/test_async.py+281 added-201 removed
1-import pytest1 import asyncio2 3+import pytest4+4-from jinja2 import Template, Environment, DictLoader5+from jinja2 import DictLoader6+from jinja2 import Environment7+from jinja2 import Template8 from jinja2.asyncsupport import auto_aiter6-from jinja2.exceptions import TemplateNotFound, TemplatesNotFound, \7- UndefinedError9+from jinja2.exceptions import TemplateNotFound10+from jinja2.exceptions import TemplatesNotFound11+from jinja2.exceptions import UndefinedError12 13 14 def run(coro):15 loop = asyncio.get_event_loop()16 return loop.run_until_complete(coro)17 18 19 def test_basic_async():16- t = Template('{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}',17- enable_async=True)20+ t = Template(21+ "{% for item in [1, 2, 3] %}[{{ item }}]{% endfor %}", enable_async=True22+ )23+24 async def func():25 return await t.render_async()26 27 rv = run(func())22- assert rv == '[1][2][3]'28+ assert rv == "[1][2][3]"29 30 31 def test_await_on_calls():26- t = Template('{{ async_func() + normal_func() }}',27- enable_async=True)32+ t = Template("{{ async_func() + normal_func() }}", enable_async=True)33 34 async def async_func():35 return 4236 37 def normal_func():38 return 2339 40 async def func():36- return await t.render_async(37- async_func=async_func,38- normal_func=normal_func39- )41+ return await t.render_async(async_func=async_func, normal_func=normal_func)42 43 rv = run(func())42- assert rv == '65'44+ assert rv == "65"45 46 47 def test_await_on_calls_normal_render():46- t = Template('{{ async_func() + normal_func() }}',47- enable_async=True)48+ t = Template("{{ async_func() + normal_func() }}", enable_async=True)49 50 async def async_func():51 return 4252 53 def normal_func():54 return 2355 55- rv = t.render(56- async_func=async_func,57- normal_func=normal_func58- )56+ rv = t.render(async_func=async_func, normal_func=normal_func)57 60- assert rv == '65'58+ assert rv == "65"59 60 61 def test_await_and_macros():64- t = Template('{% macro foo(x) %}[{{ x }}][{{ async_func() }}]'65- '{% endmacro %}{{ foo(42) }}', enable_async=True)62+ t = Template(63+ "{% macro foo(x) %}[{{ x }}][{{ async_func() }}]{% endmacro %}{{ foo(42) }}",64+ enable_async=True,65+ )66 67 async def async_func():68 return 4269 70 async def func():71 return await t.render_async(async_func=async_func)72 73 rv = run(func())74- assert rv == '[42][42]'74+ assert rv == "[42][42]"75 76 77 def test_async_blocks():78- t = Template('{% block foo %}<Test>{% endblock %}{{ self.foo() }}',79- enable_async=True, autoescape=True)78+ t = Template(79+ "{% block foo %}<Test>{% endblock %}{{ self.foo() }}",80+ enable_async=True,81+ autoescape=True,82+ )83+84 async def func():85 return await t.render_async()86 87 rv = run(func())84- assert rv == '<Test><Test>'88+ assert rv == "<Test><Test>"89 90 91 def test_async_generate():88- t = Template('{% for x in [1, 2, 3] %}{{ x }}{% endfor %}',89- enable_async=True)92+ t = Template("{% for x in [1, 2, 3] %}{{ x }}{% endfor %}", enable_async=True)93 rv = list(t.generate())91- assert rv == ['1', '2', '3']94+ assert rv == ["1", "2", "3"]95 96 97 def test_async_iteration_in_templates():95- t = Template('{% for x in rng %}{{ x }}{% endfor %}',96- enable_async=True)98+ t = Template("{% for x in rng %}{{ x }}{% endfor %}", enable_async=True)99+100 async def async_iterator():101 for item in [1, 2, 3]:102 yield item103+104 rv = list(t.generate(rng=async_iterator()))101- assert rv == ['1', '2', '3']105+ assert rv == ["1", "2", "3"]106 107 108 def test_async_iteration_in_templates_extended():109 t = Template(5 unmodified lines115 116 117 @pytest.fixture118 def test_env_async():115- env = Environment(loader=DictLoader(dict(116- module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',117- header='[{{ foo }}|{{ 23 }}]',118- o_printer='({{ o }})'119- )), enable_async=True)120- env.globals['bar'] = 23119+ env = Environment(120+ loader=DictLoader(121+ dict(122+ module="{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}",123+ header="[{{ foo }}|{{ 23 }}]",124+ o_printer="({{ o }})",125+ )126+ ),127+ enable_async=True,128+ )129+ env.globals["bar"] = 23130 return env131 132 133 @pytest.mark.imports134 class TestAsyncImports(object):126-135 def test_context_imports(self, test_env_async):136 t = test_env_async.from_string('{% import "module" as m %}{{ m.test() }}')129- assert t.render(foo=42) == '[|23]'137+ assert t.render(foo=42) == "[|23]"138 t = test_env_async.from_string(139 '{% import "module" as m without context %}{{ m.test() }}'140 )133- assert t.render(foo=42) == '[|23]'141+ assert t.render(foo=42) == "[|23]"142 t = test_env_async.from_string(143 '{% import "module" as m with context %}{{ m.test() }}'144 )137- assert t.render(foo=42) == '[42|23]'145+ assert t.render(foo=42) == "[42|23]"146 t = test_env_async.from_string('{% from "module" import test %}{{ test() }}')139- assert t.render(foo=42) == '[|23]'147+ assert t.render(foo=42) == "[|23]"148 t = test_env_async.from_string(149 '{% from "module" import test without context %}{{ test() }}'150 )143- assert t.render(foo=42) == '[|23]'151+ assert t.render(foo=42) == "[|23]"152 t = test_env_async.from_string(153 '{% from "module" import test with context %}{{ test() }}'154 )147- assert t.render(foo=42) == '[42|23]'155+ assert t.render(foo=42) == "[42|23]"156 157 def test_trailing_comma(self, test_env_async):158 test_env_async.from_string('{% from "foo" import bar, baz with context %}')159 test_env_async.from_string('{% from "foo" import bar, baz, with context %}')1 unmodified line161 test_env_async.from_string('{% from "foo" import bar, with, context %}')162 test_env_async.from_string('{% from "foo" import bar, with with context %}')163 164 def test_exports(self, test_env_async):157- m = run(test_env_async.from_string('''165+ m = run(166+ test_env_async.from_string(167+ """168 {% macro toplevel() %}...{% endmacro %}169 {% macro __private() %}...{% endmacro %}170 {% set variable = 42 %}171 {% for item in [1] %}172 {% macro notthere() %}{% endmacro %}173 {% endfor %}164- ''')._get_default_module_async())165- assert run(m.toplevel()) == '...'166- assert not hasattr(m, '__missing')174+ """175+ )._get_default_module_async()176+ )177+ assert run(m.toplevel()) == "..."178+ assert not hasattr(m, "__missing")179 assert m.variable == 42168- assert not hasattr(m, 'notthere')180+ assert not hasattr(m, "notthere")181 182 183 @pytest.mark.imports184 @pytest.mark.includes185 class TestAsyncIncludes(object):174-186 def test_context_include(self, test_env_async):187 t = test_env_async.from_string('{% include "header" %}')177- assert t.render(foo=42) == '[42|23]'188+ assert t.render(foo=42) == "[42|23]"189 t = test_env_async.from_string('{% include "header" with context %}')179- assert t.render(foo=42) == '[42|23]'190+ assert t.render(foo=42) == "[42|23]"191 t = test_env_async.from_string('{% include "header" without context %}')181- assert t.render(foo=42) == '[|23]'192+ assert t.render(foo=42) == "[|23]"193 194 def test_choice_includes(self, test_env_async):195 t = test_env_async.from_string('{% include ["missing", "header"] %}')185- assert t.render(foo=42) == '[42|23]'196+ assert t.render(foo=42) == "[42|23]"197 198 t = test_env_async.from_string(199 '{% include ["missing", "missing2"] ignore missing %}'200 )190- assert t.render(foo=42) == ''201+ assert t.render(foo=42) == ""202 203 t = test_env_async.from_string('{% include ["missing", "missing2"] %}')204 pytest.raises(TemplateNotFound, t.render)205 with pytest.raises(TemplatesNotFound) as e:206 t.render()207 197- assert e.value.templates == ['missing', 'missing2']198- assert e.value.name == 'missing2'208+ assert e.value.templates == ["missing", "missing2"]209+ assert e.value.name == "missing2"210 211 def test_includes(t, **ctx):201- ctx['foo'] = 42202- assert t.render(ctx) == '[42|23]'212+ ctx["foo"] = 42213+ assert t.render(ctx) == "[42|23]"214 215 t = test_env_async.from_string('{% include ["missing", "header"] %}')216 test_includes(t)206- t = test_env_async.from_string('{% include x %}')207- test_includes(t, x=['missing', 'header'])217+ t = test_env_async.from_string("{% include x %}")218+ test_includes(t, x=["missing", "header"])219 t = test_env_async.from_string('{% include [x, "header"] %}')209- test_includes(t, x='missing')210- t = test_env_async.from_string('{% include x %}')211- test_includes(t, x='header')212- t = test_env_async.from_string('{% include x %}')213- test_includes(t, x='header')214- t = test_env_async.from_string('{% include [x] %}')215- test_includes(t, x='header')220+ test_includes(t, x="missing")221+ t = test_env_async.from_string("{% include x %}")222+ test_includes(t, x="header")223+ t = test_env_async.from_string("{% include x %}")224+ test_includes(t, x="header")225+ t = test_env_async.from_string("{% include [x] %}")226+ test_includes(t, x="header")227 228 def test_include_ignoring_missing(self, test_env_async):229 t = test_env_async.from_string('{% include "missing" %}')230 pytest.raises(TemplateNotFound, t.render)220- for extra in '', 'with context', 'without context':221- t = test_env_async.from_string('{% include "missing" ignore missing ' +222- extra + ' %}')223- assert t.render() == ''231+ for extra in "", "with context", "without context":232+ t = test_env_async.from_string(233+ '{% include "missing" ignore missing ' + extra + " %}"234+ )235+ assert t.render() == ""236 237 def test_context_include_with_overrides(self, test_env_async):226- env = Environment(loader=DictLoader(dict(227- main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",228- item="{{ item }}"229- )))238+ env = Environment(239+ loader=DictLoader(240+ dict(241+ main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",242+ item="{{ item }}",243+ )244+ )245+ )246 assert env.get_template("main").render() == "123"247 248 def test_unoptimized_scopes(self, test_env_async):233- t = test_env_async.from_string("""249+ t = test_env_async.from_string(250+ """251 {% macro outer(o) %}252 {% macro inner() %}253 {% include "o_printer" %}254 {% endmacro %}255 {{ inner() }}256 {% endmacro %}257 {{ outer("FOO") }}241- """)242- assert t.render().strip() == '(FOO)'258+ """259+ )260+ assert t.render().strip() == "(FOO)"261 262 def test_unoptimized_scopes_autoescape(self):245- env = Environment(loader=DictLoader(dict(246- o_printer='({{ o }})',247- )), autoescape=True, enable_async=True)248- t = env.from_string("""263+ env = Environment(264+ loader=DictLoader(dict(o_printer="({{ o }})",)),265+ autoescape=True,266+ enable_async=True,267+ )268+ t = env.from_string(269+ """270 {% macro outer(o) %}271 {% macro inner() %}272 {% include "o_printer" %}273 {% endmacro %}274 {{ inner() }}275 {% endmacro %}276 {{ outer("FOO") }}256- """)257- assert t.render().strip() == '(FOO)'277+ """278+ )279+ assert t.render().strip() == "(FOO)"280 281 282 @pytest.mark.core_tags283 @pytest.mark.for_loop284 class TestAsyncForLoop(object):263-285 def test_simple(self, test_env_async):265- tmpl = test_env_async.from_string('{% for item in seq %}{{ item }}{% endfor %}')266- assert tmpl.render(seq=list(range(10))) == '0123456789'286+ tmpl = test_env_async.from_string("{% for item in seq %}{{ item }}{% endfor %}")287+ assert tmpl.render(seq=list(range(10))) == "0123456789"288 289 def test_else(self, test_env_async):290 tmpl = test_env_async.from_string(270- '{% for item in seq %}XXX{% else %}...{% endfor %}')271- assert tmpl.render() == '...'291+ "{% for item in seq %}XXX{% else %}...{% endfor %}"292+ )293+ assert tmpl.render() == "..."294 295 def test_empty_blocks(self, test_env_async):274- tmpl = test_env_async.from_string('<{% for item in seq %}{% else %}{% endfor %}>')275- assert tmpl.render() == '<>'296+ tmpl = test_env_async.from_string(297+ "<{% for item in seq %}{% else %}{% endfor %}>"298+ )299+ assert tmpl.render() == "<>"300 301 @pytest.mark.parametrize(302 "transform", [lambda x: x, iter, reversed, lambda x: (i for i in x), auto_aiter]303 )6 unmodified lines310 out = t.render(seq=transform([42, 24]))311 assert out == "1|0|2|1|True|False|2\n2|1|1|0|False|True|2\n"312 313 def test_cycling(self, test_env_async):290- tmpl = test_env_async.from_string('''{% for item in seq %}{{314+ tmpl = test_env_async.from_string(315+ """{% for item in seq %}{{316 loop.cycle('<1>', '<2>') }}{% endfor %}{%292- for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')293- output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))294- assert output == '<1><2>' * 4317+ for item in seq %}{{ loop.cycle(*through) }}{% endfor %}"""318+ )319+ output = tmpl.render(seq=list(range(4)), through=("<1>", "<2>"))320+ assert output == "<1><2>" * 4321 322 def test_lookaround(self, test_env_async):297- tmpl = test_env_async.from_string('''{% for item in seq -%}323+ tmpl = test_env_async.from_string(324+ """{% for item in seq -%}325 {{ loop.previtem|default('x') }}-{{ item }}-{{326 loop.nextitem|default('x') }}|300- {%- endfor %}''')327+ {%- endfor %}"""328+ )329 output = tmpl.render(seq=list(range(4)))302- assert output == 'x-0-1|0-1-2|1-2-3|2-3-x|'330+ assert output == "x-0-1|0-1-2|1-2-3|2-3-x|"331 332 def test_changed(self, test_env_async):305- tmpl = test_env_async.from_string('''{% for item in seq -%}333+ tmpl = test_env_async.from_string(334+ """{% for item in seq -%}335 {{ loop.changed(item) }},307- {%- endfor %}''')336+ {%- endfor %}"""337+ )338 output = tmpl.render(seq=[None, None, 1, 2, 2, 3, 4, 4, 4])309- assert output == 'True,False,True,True,False,True,True,False,False,'339+ assert output == "True,False,True,True,False,True,True,False,False,"340 341 def test_scope(self, test_env_async):312- tmpl = test_env_async.from_string('{% for item in seq %}{% endfor %}{{ item }}')342+ tmpl = test_env_async.from_string("{% for item in seq %}{% endfor %}{{ item }}")343 output = tmpl.render(seq=list(range(10)))344 assert not output345 346 def test_varlen(self, test_env_async):347 def inner():348 for item in range(5):349 yield item320- tmpl = test_env_async.from_string('{% for item in iter %}{{ item }}{% endfor %}')350+351+ tmpl = test_env_async.from_string(352+ "{% for item in iter %}{{ item }}{% endfor %}"353+ )354 output = tmpl.render(iter=inner())322- assert output == '01234'355+ assert output == "01234"356 357 def test_noniter(self, test_env_async):325- tmpl = test_env_async.from_string('{% for item in none %}...{% endfor %}')358+ tmpl = test_env_async.from_string("{% for item in none %}...{% endfor %}")359 pytest.raises(TypeError, tmpl.render)360 361 def test_recursive(self, test_env_async):329- tmpl = test_env_async.from_string('''{% for item in seq recursive -%}362+ tmpl = test_env_async.from_string(363+ """{% for item in seq recursive -%}364 [{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]331- {%- endfor %}''')332- assert tmpl.render(seq=[333- dict(a=1, b=[dict(a=1), dict(a=2)]),334- dict(a=2, b=[dict(a=1), dict(a=2)]),335- dict(a=3, b=[dict(a='a')])336- ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'365+ {%- endfor %}"""366+ )367+ assert (368+ tmpl.render(369+ seq=[370+ dict(a=1, b=[dict(a=1), dict(a=2)]),371+ dict(a=2, b=[dict(a=1), dict(a=2)]),372+ dict(a=3, b=[dict(a="a")]),373+ ]374+ )375+ == "[1<[1][2]>][2<[1][2]>][3<[a]>]"376+ )377 378 def test_recursive_lookaround(self, test_env_async):339- tmpl = test_env_async.from_string('''{% for item in seq recursive -%}379+ tmpl = test_env_async.from_string(380+ """{% for item in seq recursive -%}381 [{{ loop.previtem.a if loop.previtem is defined else 'x' }}.{{382 item.a }}.{{ loop.nextitem.a if loop.nextitem is defined else 'x'383 }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]343- {%- endfor %}''')344- assert tmpl.render(seq=[345- dict(a=1, b=[dict(a=1), dict(a=2)]),346- dict(a=2, b=[dict(a=1), dict(a=2)]),347- dict(a=3, b=[dict(a='a')])348- ]) == '[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]'384+ {%- endfor %}"""385+ )386+ assert (387+ tmpl.render(388+ seq=[389+ dict(a=1, b=[dict(a=1), dict(a=2)]),390+ dict(a=2, b=[dict(a=1), dict(a=2)]),391+ dict(a=3, b=[dict(a="a")]),392+ ]393+ )394+ == "[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]"395+ )396 397 def test_recursive_depth0(self, test_env_async):351- tmpl = test_env_async.from_string('''{% for item in seq recursive -%}352- [{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]353- {%- endfor %}''')354- assert tmpl.render(seq=[355- dict(a=1, b=[dict(a=1), dict(a=2)]),356- dict(a=2, b=[dict(a=1), dict(a=2)]),357- dict(a=3, b=[dict(a='a')])358- ]) == '[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]'398+ tmpl = test_env_async.from_string(399+ "{% for item in seq recursive %}[{{ loop.depth0 }}:{{ item.a }}"400+ "{% if item.b %}<{{ loop(item.b) }}>{% endif %}]{% endfor %}"401+ )402+ assert (403+ tmpl.render(404+ seq=[405+ dict(a=1, b=[dict(a=1), dict(a=2)]),406+ dict(a=2, b=[dict(a=1), dict(a=2)]),407+ dict(a=3, b=[dict(a="a")]),408+ ]409+ )410+ == "[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]"411+ )412 413 def test_recursive_depth(self, test_env_async):361- tmpl = test_env_async.from_string('''{% for item in seq recursive -%}362- [{{ loop.depth }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]363- {%- endfor %}''')364- assert tmpl.render(seq=[365- dict(a=1, b=[dict(a=1), dict(a=2)]),366- dict(a=2, b=[dict(a=1), dict(a=2)]),367- dict(a=3, b=[dict(a='a')])368- ]) == '[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]'414+ tmpl = test_env_async.from_string(415+ "{% for item in seq recursive %}[{{ loop.depth }}:{{ item.a }}"416+ "{% if item.b %}<{{ loop(item.b) }}>{% endif %}]{% endfor %}"417+ )418+ assert (419+ tmpl.render(420+ seq=[421+ dict(a=1, b=[dict(a=1), dict(a=2)]),422+ dict(a=2, b=[dict(a=1), dict(a=2)]),423+ dict(a=3, b=[dict(a="a")]),424+ ]425+ )426+ == "[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]"427+ )428 429 def test_looploop(self, test_env_async):371- tmpl = test_env_async.from_string('''{% for row in table %}430+ tmpl = test_env_async.from_string(431+ """{% for row in table %}432 {%- set rowloop = loop -%}433 {% for cell in row -%}434 [{{ rowloop.index }}|{{ loop.index }}]435 {%- endfor %}376- {%- endfor %}''')377- assert tmpl.render(table=['ab', 'cd']) == '[1|1][1|2][2|1][2|2]'436+ {%- endfor %}"""437+ )438+ assert tmpl.render(table=["ab", "cd"]) == "[1|1][1|2][2|1][2|2]"439 440 def test_reversed_bug(self, test_env_async):380- tmpl = test_env_async.from_string('{% for i in items %}{{ i }}'381- '{% if not loop.last %}'382- ',{% endif %}{% endfor %}')383- assert tmpl.render(items=reversed([3, 2, 1])) == '1,2,3'441+ tmpl = test_env_async.from_string(442+ "{% for i in items %}{{ i }}"443+ "{% if not loop.last %}"444+ ",{% endif %}{% endfor %}"445+ )446+ assert tmpl.render(items=reversed([3, 2, 1])) == "1,2,3"447 448 def test_loop_errors(self, test_env_async):386- tmpl = test_env_async.from_string('''{% for item in [1] if loop.index387- == 0 %}...{% endfor %}''')449+ tmpl = test_env_async.from_string(450+ """{% for item in [1] if loop.index451+ == 0 %}...{% endfor %}"""452+ )453 pytest.raises(UndefinedError, tmpl.render)389- tmpl = test_env_async.from_string('''{% for item in [] %}...{% else390- %}{{ loop }}{% endfor %}''')391- assert tmpl.render() == ''454+ tmpl = test_env_async.from_string(455+ """{% for item in [] %}...{% else456+ %}{{ loop }}{% endfor %}"""457+ )458+ assert tmpl.render() == ""459 460 def test_loop_filter(self, test_env_async):394- tmpl = test_env_async.from_string('{% for item in range(10) if item '395- 'is even %}[{{ item }}]{% endfor %}')396- assert tmpl.render() == '[0][2][4][6][8]'397- tmpl = test_env_async.from_string('''461+ tmpl = test_env_async.from_string(462+ "{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}"463+ )464+ assert tmpl.render() == "[0][2][4][6][8]"465+ tmpl = test_env_async.from_string(466+ """467 {%- for item in range(10) if item is even %}[{{399- loop.index }}:{{ item }}]{% endfor %}''')400- assert tmpl.render() == '[1:0][2:2][3:4][4:6][5:8]'468+ loop.index }}:{{ item }}]{% endfor %}"""469+ )470+ assert tmpl.render() == "[1:0][2:2][3:4][4:6][5:8]"471 472 def test_scoped_special_var(self, test_env_async):473 t = test_env_async.from_string(404- '{% for s in seq %}[{{ loop.first }}{% for c in s %}'405- '|{{ loop.first }}{% endfor %}]{% endfor %}')406- assert t.render(seq=('ab', 'cd')) \407- == '[True|True|False][False|True|False]'474+ "{% for s in seq %}[{{ loop.first }}{% for c in s %}"475+ "|{{ loop.first }}{% endfor %}]{% endfor %}"476+ )477+ assert t.render(seq=("ab", "cd")) == "[True|True|False][False|True|False]"478 479 def test_scoped_loop_var(self, test_env_async):410- t = test_env_async.from_string('{% for x in seq %}{{ loop.first }}'411- '{% for y in seq %}{% endfor %}{% endfor %}')412- assert t.render(seq='ab') == 'TrueFalse'413- t = test_env_async.from_string('{% for x in seq %}{% for y in seq %}'414- '{{ loop.first }}{% endfor %}{% endfor %}')415- assert t.render(seq='ab') == 'TrueFalseTrueFalse'480+ t = test_env_async.from_string(481+ "{% for x in seq %}{{ loop.first }}"482+ "{% for y in seq %}{% endfor %}{% endfor %}"483+ )484+ assert t.render(seq="ab") == "TrueFalse"485+ t = test_env_async.from_string(486+ "{% for x in seq %}{% for y in seq %}"487+ "{{ loop.first }}{% endfor %}{% endfor %}"488+ )489+ assert t.render(seq="ab") == "TrueFalseTrueFalse"490 491 def test_recursive_empty_loop_iter(self, test_env_async):418- t = test_env_async.from_string('''492+ t = test_env_async.from_string(493+ """494 {%- for item in foo recursive -%}{%- endfor -%}495+ """420- ''')421- assert t.render(dict(foo=[])) == ''496+ )497+ assert t.render(dict(foo=[])) == ""498 499 def test_call_in_loop(self, test_env_async):424- t = test_env_async.from_string('''500+ t = test_env_async.from_string(501+ """502 {%- macro do_something() -%}503 [{{ caller() }}]504 {%- endmacro %}505 1 unmodified line507 {%- call do_something() -%}508 {{ i }}509 {%- endcall %}510 {%- endfor -%}434- ''')435- assert t.render() == '[1][2][3]'511+ """512+ )513+ assert t.render() == "[1][2][3]"514 515 def test_scoping_bug(self, test_env_async):438- t = test_env_async.from_string('''516+ t = test_env_async.from_string(517+ """518 {%- for item in foo %}...{{ item }}...{% endfor %}519 {%- macro item(a) %}...{{ a }}...{% endmacro %}520 {{- item(2) -}}442- ''')443- assert t.render(foo=(1,)) == '...1......2...'521+ """522+ )523+ assert t.render(foo=(1,)) == "...1......2..."524 525 def test_unpacking(self, test_env_async):446- tmpl = test_env_async.from_string('{% for a, b, c in [[1, 2, 3]] %}'447- '{{ a }}|{{ b }}|{{ c }}{% endfor %}')448- assert tmpl.render() == '1|2|3'526+ tmpl = test_env_async.from_string(527+ "{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}"528+ )529+ assert tmpl.render() == "1|2|3"530 531 def test_recursive_loop_filter(self, test_env_async):451- t = test_env_async.from_string('''532+ t = test_env_async.from_string(533+ """534 <?xml version="1.0" encoding="UTF-8"?>535 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">536 {%- for page in [site.root] if page.url != this recursive %}537 <url><loc>{{ page.url }}</loc></url>538 {{- loop(page.children) }}539 {%- endfor %}540 </urlset>459- ''')460- sm =t.render(this='/foo', site={'root': {461- 'url': '/',462- 'children': [463- {'url': '/foo'},464- {'url': '/bar'},465- ]466- }})541+ """542+ )543+ sm = t.render(544+ this="/foo",545+ site={"root": {"url": "/", "children": [{"url": "/foo"}, {"url": "/bar"}]}},546+ )547 lines = [x.strip() for x in sm.splitlines() if x.strip()]548 assert lines == [549 '<?xml version="1.0" encoding="UTF-8"?>',550 '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',471- '<url><loc>/</loc></url>',472- '<url><loc>/bar</loc></url>',473- '</urlset>',551+ "<url><loc>/</loc></url>",552+ "<url><loc>/bar</loc></url>",553+ "</urlset>",554 ]555 556 def test_nonrecursive_loop_filter(self, test_env_async):477- t = test_env_async.from_string('''557+ t = test_env_async.from_string(558+ """559 <?xml version="1.0" encoding="UTF-8"?>560 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">561 {%- for page in items if page.url != this %}562 <url><loc>{{ page.url }}</loc></url>563 {%- endfor %}564 </urlset>484- ''')485- sm =t.render(this='/foo', items=[486- {'url': '/'},487- {'url': '/foo'},488- {'url': '/bar'},489- ])565+ """566+ )567+ sm = t.render(568+ this="/foo", items=[{"url": "/"}, {"url": "/foo"}, {"url": "/bar"}]569+ )570 lines = [x.strip() for x in sm.splitlines() if x.strip()]571 assert lines == [572 '<?xml version="1.0" encoding="UTF-8"?>',573 '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',494- '<url><loc>/</loc></url>',495- '<url><loc>/bar</loc></url>',496- '</urlset>',574+ "<url><loc>/</loc></url>",575+ "<url><loc>/bar</loc></url>",576+ "</urlset>",577 ]578 579 def test_bare_async(self, test_env_async):580 t = test_env_async.from_string('{% extends "header" %}')501- assert t.render(foo=42) == '[42|23]'581+ assert t.render(foo=42) == "[42|23]"modified:tests/test_asyncfilters.py+105 added-113 removed
1+from collections import namedtuple2+3 import pytest4+5 from jinja2 import Environment6 from jinja2.utils import Markup7 8 3 unmodified lines12 13 14 def mark_dualiter(parameter, factory):15 def decorator(f):13- return pytest.mark.parametrize(parameter, [14- lambda: factory(),15- lambda: make_aiter(factory()),16- ])(f)16+ return pytest.mark.parametrize(17+ parameter, [lambda: factory(), lambda: make_aiter(factory())]18+ )(f)19+20 return decorator21 22 23 @pytest.fixture24 def env_async():25 return Environment(enable_async=True)26 27 25-@mark_dualiter('foo', lambda: range(10))28+@mark_dualiter("foo", lambda: range(10))29 def test_first(env_async, foo):27- tmpl = env_async.from_string('{{ foo()|first }}')30+ tmpl = env_async.from_string("{{ foo()|first }}")31 out = tmpl.render(foo=foo)29- assert out == '0'32+ assert out == "0"33 34 32-@mark_dualiter('items', lambda: [33- {'foo': 1, 'bar': 2},34- {'foo': 2, 'bar': 3},35- {'foo': 1, 'bar': 1},36- {'foo': 3, 'bar': 4}37-])35+@mark_dualiter(36+ "items",37+ lambda: [38+ {"foo": 1, "bar": 2},39+ {"foo": 2, "bar": 3},40+ {"foo": 1, "bar": 1},41+ {"foo": 3, "bar": 4},42+ ],43+)44 def test_groupby(env_async, items):39- tmpl = env_async.from_string('''45+ tmpl = env_async.from_string(46+ """47 {%- for grouper, list in items()|groupby('foo') -%}48 {{ grouper }}{% for x in list %}: {{ x.foo }}, {{ x.bar }}{% endfor %}|42- {%- endfor %}''')43- assert tmpl.render(items=items).split('|') == [49+ {%- endfor %}"""50+ )51+ assert tmpl.render(items=items).split("|") == [52 "1: 1, 2: 1, 1",53 "2: 2, 3",54 "3: 3, 4",47- ""55+ "",56 ]57 58 51-@mark_dualiter('items', lambda: [('a', 1), ('a', 2), ('b', 1)])59+@mark_dualiter("items", lambda: [("a", 1), ("a", 2), ("b", 1)])60 def test_groupby_tuple_index(env_async, items):53- tmpl = env_async.from_string('''61+ tmpl = env_async.from_string(62+ """63 {%- for grouper, list in items()|groupby(0) -%}64 {{ grouper }}{% for x in list %}:{{ x.1 }}{% endfor %}|56- {%- endfor %}''')57- assert tmpl.render(items=items) == 'a:1:2|b:1|'65+ {%- endfor %}"""66+ )67+ assert tmpl.render(items=items) == "a:1:2|b:1|"68 69 70 def make_articles():61- class Date(object):62- def __init__(self, day, month, year):63- self.day = day64- self.month = month65- self.year = year66-67- class Article(object):68- def __init__(self, title, *date):69- self.date = Date(*date)70- self.title = title71-71+ Date = namedtuple("Date", "day,month,year")72+ Article = namedtuple("Article", "title,date")73 return [73- Article('aha', 1, 1, 1970),74- Article('interesting', 2, 1, 1970),75- Article('really?', 3, 1, 1970),76- Article('totally not', 1, 1, 1971)74+ Article("aha", Date(1, 1, 1970)),75+ Article("interesting", Date(2, 1, 1970)),76+ Article("really?", Date(3, 1, 1970)),77+ Article("totally not", Date(1, 1, 1971)),78 ]79 80 80-@mark_dualiter('articles', make_articles)81+@mark_dualiter("articles", make_articles)82 def test_groupby_multidot(env_async, articles):82- tmpl = env_async.from_string('''83+ tmpl = env_async.from_string(84+ """85 {%- for year, list in articles()|groupby('date.year') -%}86 {{ year }}{% for x in list %}[{{ x.title }}]{% endfor %}|85- {%- endfor %}''')86- assert tmpl.render(articles=articles).split('|') == [87- '1970[aha][interesting][really?]',88- '1971[totally not]',89- ''87+ {%- endfor %}"""88+ )89+ assert tmpl.render(articles=articles).split("|") == [90+ "1970[aha][interesting][really?]",91+ "1971[totally not]",92+ "",93 ]94 95 93-@mark_dualiter('int_items', lambda: [1, 2, 3])96+@mark_dualiter("int_items", lambda: [1, 2, 3])97 def test_join_env_int(env_async, int_items):98 tmpl = env_async.from_string('{{ items()|join("|") }}')99 out = tmpl.render(items=int_items)97- assert out == '1|2|3'100+ assert out == "1|2|3"101 102 100-@mark_dualiter('string_items', lambda: ["<foo>", Markup("<span>foo</span>")])103+@mark_dualiter("string_items", lambda: ["<foo>", Markup("<span>foo</span>")])104 def test_join_string_list(string_items):105 env2 = Environment(autoescape=True, enable_async=True)103- tmpl = env2.from_string(104- '{{ ["<foo>", "<span>foo</span>"|safe]|join }}')105- assert tmpl.render(items=string_items) == '<foo><span>foo</span>'106+ tmpl = env2.from_string('{{ ["<foo>", "<span>foo</span>"|safe]|join }}')107+ assert tmpl.render(items=string_items) == "<foo><span>foo</span>"108 109 110 def make_users():109- class User(object):110- def __init__(self, username):111- self.username = username112- return map(User, ['foo', 'bar'])111+ User = namedtuple("User", "username")112+ return map(User, ["foo", "bar"])113 114 115-@mark_dualiter('users', make_users)115+@mark_dualiter("users", make_users)116 def test_join_attribute(env_async, users):117- tmpl = env_async.from_string('''{{ users()|join(', ', 'username') }}''')118- assert tmpl.render(users=users) == 'foo, bar'117+ tmpl = env_async.from_string("""{{ users()|join(', ', 'username') }}""")118+ assert tmpl.render(users=users) == "foo, bar"119 120 121-@mark_dualiter('items', lambda: [1, 2, 3, 4, 5])121+@mark_dualiter("items", lambda: [1, 2, 3, 4, 5])122 def test_simple_reject(env_async, items):123 tmpl = env_async.from_string('{{ items()|reject("odd")|join("|") }}')124- assert tmpl.render(items=items) == '2|4'124+ assert tmpl.render(items=items) == "2|4"125 126 127-@mark_dualiter('items', lambda: [None, False, 0, 1, 2, 3, 4, 5])127+@mark_dualiter("items", lambda: [None, False, 0, 1, 2, 3, 4, 5])128 def test_bool_reject(env_async, items):129- tmpl = env_async.from_string(130- '{{ items()|reject|join("|") }}'131- )132- assert tmpl.render(items=items) == 'None|False|0'129+ tmpl = env_async.from_string('{{ items()|reject|join("|") }}')130+ assert tmpl.render(items=items) == "None|False|0"131 132 135-@mark_dualiter('items', lambda: [1, 2, 3, 4, 5])133+@mark_dualiter("items", lambda: [1, 2, 3, 4, 5])134 def test_simple_select(env_async, items):135 tmpl = env_async.from_string('{{ items()|select("odd")|join("|") }}')138- assert tmpl.render(items=items) == '1|3|5'136+ assert tmpl.render(items=items) == "1|3|5"137 138 141-@mark_dualiter('items', lambda: [None, False, 0, 1, 2, 3, 4, 5])139+@mark_dualiter("items", lambda: [None, False, 0, 1, 2, 3, 4, 5])140 def test_bool_select(env_async, items):143- tmpl = env_async.from_string(144- '{{ items()|select|join("|") }}'145- )146- assert tmpl.render(items=items) == '1|2|3|4|5'141+ tmpl = env_async.from_string('{{ items()|select|join("|") }}')142+ assert tmpl.render(items=items) == "1|2|3|4|5"143 144 145 def make_users():150- class User(object):151- def __init__(self, name, is_active):152- self.name = name153- self.is_active = is_active146+ User = namedtuple("User", "name,is_active")147 return [155- User('john', True),156- User('jane', True),157- User('mike', False),148+ User("john", True),149+ User("jane", True),150+ User("mike", False),151 ]152 153 161-@mark_dualiter('users', make_users)154+@mark_dualiter("users", make_users)155 def test_simple_select_attr(env_async, users):156 tmpl = env_async.from_string(164- '{{ users()|selectattr("is_active")|'165- 'map(attribute="name")|join("|") }}'157+ '{{ users()|selectattr("is_active")|map(attribute="name")|join("|") }}'158 )167- assert tmpl.render(users=users) == 'john|jane'159+ assert tmpl.render(users=users) == "john|jane"160 161 170-@mark_dualiter('items', lambda: list('123'))162+@mark_dualiter("items", lambda: list("123"))163 def test_simple_map(env_async, items):164 tmpl = env_async.from_string('{{ items()|map("int")|sum }}')173- assert tmpl.render(items=items) == '6'165+ assert tmpl.render(items=items) == "6"166 167 168 def test_map_sum(env_async): # async map + async filter169 tmpl = env_async.from_string('{{ [[1,2], [3], [4,5,6]]|map("sum")|list }}')178- assert tmpl.render() == '[3, 3, 15]'170+ assert tmpl.render() == "[3, 3, 15]"171 172 181-@mark_dualiter('users', make_users)173+@mark_dualiter("users", make_users)174 def test_attribute_map(env_async, users):175 tmpl = env_async.from_string('{{ users()|map(attribute="name")|join("|") }}')184- assert tmpl.render(users=users) == 'john|jane|mike'176+ assert tmpl.render(users=users) == "john|jane|mike"177 178 179 def test_empty_map(env_async):180 tmpl = env_async.from_string('{{ none|map("upper")|list }}')189- assert tmpl.render() == '[]'181+ assert tmpl.render() == "[]"182 183 192-@mark_dualiter('items', lambda: [1, 2, 3, 4, 5, 6])184+@mark_dualiter("items", lambda: [1, 2, 3, 4, 5, 6])185 def test_sum(env_async, items):194- tmpl = env_async.from_string('''{{ items()|sum }}''')195- assert tmpl.render(items=items) == '21'186+ tmpl = env_async.from_string("""{{ items()|sum }}""")187+ assert tmpl.render(items=items) == "21"188 189 198-@mark_dualiter('items', lambda: [199- {'value': 23},200- {'value': 1},201- {'value': 18},202-])190+@mark_dualiter("items", lambda: [{"value": 23}, {"value": 1}, {"value": 18}])191 def test_sum_attributes(env_async, items):204- tmpl = env_async.from_string('''{{ items()|sum('value') }}''')192+ tmpl = env_async.from_string("""{{ items()|sum('value') }}""")193 assert tmpl.render(items=items)194 195 196 def test_sum_attributes_nested(env_async):209- tmpl = env_async.from_string('''{{ values|sum('real.value') }}''')210- assert tmpl.render(values=[211- {'real': {'value': 23}},212- {'real': {'value': 1}},213- {'real': {'value': 18}},214- ]) == '42'197+ tmpl = env_async.from_string("""{{ values|sum('real.value') }}""")198+ assert (199+ tmpl.render(200+ values=[201+ {"real": {"value": 23}},202+ {"real": {"value": 1}},203+ {"real": {"value": 18}},204+ ]205+ )206+ == "42"207+ )208 209 210 def test_sum_attributes_tuple(env_async):218- tmpl = env_async.from_string('''{{ values.items()|sum('1') }}''')219- assert tmpl.render(values={220- 'foo': 23,221- 'bar': 1,222- 'baz': 18,223- }) == '42'211+ tmpl = env_async.from_string("""{{ values.items()|sum('1') }}""")212+ assert tmpl.render(values={"foo": 23, "bar": 1, "baz": 18}) == "42"213 214 226-@mark_dualiter('items', lambda: range(10))215+@mark_dualiter("items", lambda: range(10))216 def test_slice(env_async, items):228- tmpl = env_async.from_string('{{ items()|slice(3)|list }}|'229- '{{ items()|slice(3, "X")|list }}')217+ tmpl = env_async.from_string(218+ "{{ items()|slice(3)|list }}|{{ items()|slice(3, 'X')|list }}"219+ )220 out = tmpl.render(items=items)231- assert out == ("[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"232- "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]")221+ assert out == (222+ "[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"223+ "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]"224+ )modified:tests/test_bytecode_cache.py+14 added-27 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.bytecode_cache4- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Test bytecode caching7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-2 import pytest3 4 from jinja2 import Environment15-from jinja2.bccache import Bucket, FileSystemBytecodeCache, \16- MemcachedBytecodeCache5+from jinja2.bccache import Bucket6+from jinja2.bccache import FileSystemBytecodeCache7+from jinja2.bccache import MemcachedBytecodeCache8 from jinja2.exceptions import TemplateNotFound9 10 11 @pytest.fixture12 def env(package_loader):13 bytecode_cache = FileSystemBytecodeCache()23- return Environment(24- loader=package_loader,25- bytecode_cache=bytecode_cache,26- )14+ return Environment(loader=package_loader, bytecode_cache=bytecode_cache,)15 16 17 @pytest.mark.byte_code_cache18 class TestByteCodeCache(object):31-19 def test_simple(self, env):33- tmpl = env.get_template('test.html')34- assert tmpl.render().strip() == 'BAR'35- pytest.raises(TemplateNotFound, env.get_template, 'missing.html')20+ tmpl = env.get_template("test.html")21+ assert tmpl.render().strip() == "BAR"22+ pytest.raises(TemplateNotFound, env.get_template, "missing.html")23 24 25 class MockMemcached(object):26 class Error(Exception):22 unmodified lines49 def test_dump_load(self):50 memcached = MockMemcached()51 m = MemcachedBytecodeCache(memcached)52 66- b = Bucket(None, 'key', '')67- b.code = 'code'53+ b = Bucket(None, "key", "")54+ b.code = "code"55 m.dump_bytecode(b)69- assert memcached.key == 'jinja2/bytecode/key'56+ assert memcached.key == "jinja2/bytecode/key"57 71- b = Bucket(None, 'key', '')58+ b = Bucket(None, "key", "")59 m.load_bytecode(b)73- assert b.code == 'code'60+ assert b.code == "code"61 62 def test_exception(self):63 memcached = MockMemcached()64 memcached.get = memcached.get_side_effect65 memcached.set = memcached.set_side_effect66 m = MemcachedBytecodeCache(memcached)80- b = Bucket(None, 'key', '')81- b.code = 'code'67+ b = Bucket(None, "key", "")68+ b.code = "code"69 70 m.dump_bytecode(b)71 m.load_bytecode(b)72 7 unmodified linesmodified:tests/test_core_tags.py+371 added-263 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.core_tags4- ~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Test the core tags like for and if.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import pytest12-from jinja2 import Environment, TemplateSyntaxError, TemplateRuntimeError, \13- UndefinedError, DictLoader3 4+from jinja2 import DictLoader5+from jinja2 import Environment6+from jinja2 import TemplateRuntimeError7+from jinja2 import TemplateSyntaxError8+from jinja2 import UndefinedError9 10+11 @pytest.fixture12 def env_trim():13 return Environment(trim_blocks=True)14 15 16 @pytest.mark.core_tags17 @pytest.mark.for_loop18 class TestForLoop(object):24-19 def test_simple(self, env):26- tmpl = env.from_string('{% for item in seq %}{{ item }}{% endfor %}')27- assert tmpl.render(seq=list(range(10))) == '0123456789'20+ tmpl = env.from_string("{% for item in seq %}{{ item }}{% endfor %}")21+ assert tmpl.render(seq=list(range(10))) == "0123456789"22 23 def test_else(self, env):30- tmpl = env.from_string(31- '{% for item in seq %}XXX{% else %}...{% endfor %}')32- assert tmpl.render() == '...'24+ tmpl = env.from_string("{% for item in seq %}XXX{% else %}...{% endfor %}")25+ assert tmpl.render() == "..."26 27 def test_else_scoping_item(self, env):35- tmpl = env.from_string(36- '{% for item in [] %}{% else %}{{ item }}{% endfor %}')37- assert tmpl.render(item=42) == '42'28+ tmpl = env.from_string("{% for item in [] %}{% else %}{{ item }}{% endfor %}")29+ assert tmpl.render(item=42) == "42"30 31 def test_empty_blocks(self, env):40- tmpl = env.from_string('<{% for item in seq %}{% else %}{% endfor %}>')41- assert tmpl.render() == '<>'32+ tmpl = env.from_string("<{% for item in seq %}{% else %}{% endfor %}>")33+ assert tmpl.render() == "<>"34 35 def test_context_vars(self, env):36 slist = [42, 24]37 for seq in [slist, iter(slist), reversed(slist), (_ for _ in slist)]:46- tmpl = env.from_string('''{% for item in seq -%}38+ tmpl = env.from_string(39+ """{% for item in seq -%}40 {{ loop.index }}|{{ loop.index0 }}|{{ loop.revindex }}|{{41 loop.revindex0 }}|{{ loop.first }}|{{ loop.last }}|{{49- loop.length }}###{% endfor %}''')50- one, two, _ = tmpl.render(seq=seq).split('###')51- (one_index, one_index0, one_revindex, one_revindex0, one_first,52- one_last, one_length) = one.split('|')53- (two_index, two_index0, two_revindex, two_revindex0, two_first,54- two_last, two_length) = two.split('|')42+ loop.length }}###{% endfor %}"""43+ )44+ one, two, _ = tmpl.render(seq=seq).split("###")45+ (46+ one_index,47+ one_index0,48+ one_revindex,49+ one_revindex0,50+ one_first,51+ one_last,52+ one_length,53+ ) = one.split("|")54+ (55+ two_index,56+ two_index0,57+ two_revindex,58+ two_revindex0,59+ two_first,60+ two_last,61+ two_length,62+ ) = two.split("|")63 64 assert int(one_index) == 1 and int(two_index) == 265 assert int(one_index0) == 0 and int(two_index0) == 166 assert int(one_revindex) == 2 and int(two_revindex) == 167 assert int(one_revindex0) == 1 and int(two_revindex0) == 060- assert one_first == 'True' and two_first == 'False'61- assert one_last == 'False' and two_last == 'True'62- assert one_length == two_length == '2'68+ assert one_first == "True" and two_first == "False"69+ assert one_last == "False" and two_last == "True"70+ assert one_length == two_length == "2"71 72 def test_cycling(self, env):65- tmpl = env.from_string('''{% for item in seq %}{{73+ tmpl = env.from_string(74+ """{% for item in seq %}{{75 loop.cycle('<1>', '<2>') }}{% endfor %}{%67- for item in seq %}{{ loop.cycle(*through) }}{% endfor %}''')68- output = tmpl.render(seq=list(range(4)), through=('<1>', '<2>'))69- assert output == '<1><2>' * 476+ for item in seq %}{{ loop.cycle(*through) }}{% endfor %}"""77+ )78+ output = tmpl.render(seq=list(range(4)), through=("<1>", "<2>"))79+ assert output == "<1><2>" * 480 81 def test_lookaround(self, env):72- tmpl = env.from_string('''{% for item in seq -%}82+ tmpl = env.from_string(83+ """{% for item in seq -%}84 {{ loop.previtem|default('x') }}-{{ item }}-{{85 loop.nextitem|default('x') }}|75- {%- endfor %}''')86+ {%- endfor %}"""87+ )88 output = tmpl.render(seq=list(range(4)))77- assert output == 'x-0-1|0-1-2|1-2-3|2-3-x|'89+ assert output == "x-0-1|0-1-2|1-2-3|2-3-x|"90 91 def test_changed(self, env):80- tmpl = env.from_string('''{% for item in seq -%}92+ tmpl = env.from_string(93+ """{% for item in seq -%}94 {{ loop.changed(item) }},82- {%- endfor %}''')95+ {%- endfor %}"""96+ )97 output = tmpl.render(seq=[None, None, 1, 2, 2, 3, 4, 4, 4])84- assert output == 'True,False,True,True,False,True,True,False,False,'98+ assert output == "True,False,True,True,False,True,True,False,False,"99 100 def test_scope(self, env):87- tmpl = env.from_string('{% for item in seq %}{% endfor %}{{ item }}')101+ tmpl = env.from_string("{% for item in seq %}{% endfor %}{{ item }}")102 output = tmpl.render(seq=list(range(10)))103 assert not output104 105 def test_varlen(self, env):106 def inner():107 for item in range(5):108 yield item95- tmpl = env.from_string('{% for item in iter %}{{ item }}{% endfor %}')109+110+ tmpl = env.from_string("{% for item in iter %}{{ item }}{% endfor %}")111 output = tmpl.render(iter=inner())97- assert output == '01234'112+ assert output == "01234"113 114 def test_noniter(self, env):100- tmpl = env.from_string('{% for item in none %}...{% endfor %}')115+ tmpl = env.from_string("{% for item in none %}...{% endfor %}")116 pytest.raises(TypeError, tmpl.render)117 118 def test_recursive(self, env):104- tmpl = env.from_string('''{% for item in seq recursive -%}119+ tmpl = env.from_string(120+ """{% for item in seq recursive -%}121 [{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]106- {%- endfor %}''')107- assert tmpl.render(seq=[108- dict(a=1, b=[dict(a=1), dict(a=2)]),109- dict(a=2, b=[dict(a=1), dict(a=2)]),110- dict(a=3, b=[dict(a='a')])111- ]) == '[1<[1][2]>][2<[1][2]>][3<[a]>]'122+ {%- endfor %}"""123+ )124+ assert (125+ tmpl.render(126+ seq=[127+ dict(a=1, b=[dict(a=1), dict(a=2)]),128+ dict(a=2, b=[dict(a=1), dict(a=2)]),129+ dict(a=3, b=[dict(a="a")]),130+ ]131+ )132+ == "[1<[1][2]>][2<[1][2]>][3<[a]>]"133+ )134 135 def test_recursive_lookaround(self, env):114- tmpl = env.from_string('''{% for item in seq recursive -%}136+ tmpl = env.from_string(137+ """{% for item in seq recursive -%}138 [{{ loop.previtem.a if loop.previtem is defined else 'x' }}.{{139 item.a }}.{{ loop.nextitem.a if loop.nextitem is defined else 'x'140 }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]118- {%- endfor %}''')119- assert tmpl.render(seq=[120- dict(a=1, b=[dict(a=1), dict(a=2)]),121- dict(a=2, b=[dict(a=1), dict(a=2)]),122- dict(a=3, b=[dict(a='a')])123- ]) == '[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]'141+ {%- endfor %}"""142+ )143+ assert (144+ tmpl.render(145+ seq=[146+ dict(a=1, b=[dict(a=1), dict(a=2)]),147+ dict(a=2, b=[dict(a=1), dict(a=2)]),148+ dict(a=3, b=[dict(a="a")]),149+ ]150+ )151+ == "[x.1.2<[x.1.2][1.2.x]>][1.2.3<[x.1.2][1.2.x]>][2.3.x<[x.a.x]>]"152+ )153 154 def test_recursive_depth0(self, env):126- tmpl = env.from_string('''{% for item in seq recursive -%}127- [{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]128- {%- endfor %}''')129- assert tmpl.render(seq=[130- dict(a=1, b=[dict(a=1), dict(a=2)]),131- dict(a=2, b=[dict(a=1), dict(a=2)]),132- dict(a=3, b=[dict(a='a')])133- ]) == '[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]'155+ tmpl = env.from_string(156+ """{% for item in seq recursive -%}157+ [{{ loop.depth0 }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]158+ {%- endfor %}"""159+ )160+ assert (161+ tmpl.render(162+ seq=[163+ dict(a=1, b=[dict(a=1), dict(a=2)]),164+ dict(a=2, b=[dict(a=1), dict(a=2)]),165+ dict(a=3, b=[dict(a="a")]),166+ ]167+ )168+ == "[0:1<[1:1][1:2]>][0:2<[1:1][1:2]>][0:3<[1:a]>]"169+ )170 171 def test_recursive_depth(self, env):136- tmpl = env.from_string('''{% for item in seq recursive -%}137- [{{ loop.depth }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]138- {%- endfor %}''')139- assert tmpl.render(seq=[140- dict(a=1, b=[dict(a=1), dict(a=2)]),141- dict(a=2, b=[dict(a=1), dict(a=2)]),142- dict(a=3, b=[dict(a='a')])143- ]) == '[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]'172+ tmpl = env.from_string(173+ """{% for item in seq recursive -%}174+ [{{ loop.depth }}:{{ item.a }}{% if item.b %}<{{ loop(item.b) }}>{% endif %}]175+ {%- endfor %}"""176+ )177+ assert (178+ tmpl.render(179+ seq=[180+ dict(a=1, b=[dict(a=1), dict(a=2)]),181+ dict(a=2, b=[dict(a=1), dict(a=2)]),182+ dict(a=3, b=[dict(a="a")]),183+ ]184+ )185+ == "[1:1<[2:1][2:2]>][1:2<[2:1][2:2]>][1:3<[2:a]>]"186+ )187 188 def test_looploop(self, env):146- tmpl = env.from_string('''{% for row in table %}189+ tmpl = env.from_string(190+ """{% for row in table %}191 {%- set rowloop = loop -%}192 {% for cell in row -%}193 [{{ rowloop.index }}|{{ loop.index }}]194 {%- endfor %}151- {%- endfor %}''')152- assert tmpl.render(table=['ab', 'cd']) == '[1|1][1|2][2|1][2|2]'195+ {%- endfor %}"""196+ )197+ assert tmpl.render(table=["ab", "cd"]) == "[1|1][1|2][2|1][2|2]"198 199 def test_reversed_bug(self, env):155- tmpl = env.from_string('{% for i in items %}{{ i }}'156- '{% if not loop.last %}'157- ',{% endif %}{% endfor %}')158- assert tmpl.render(items=reversed([3, 2, 1])) == '1,2,3'200+ tmpl = env.from_string(201+ "{% for i in items %}{{ i }}"202+ "{% if not loop.last %}"203+ ",{% endif %}{% endfor %}"204+ )205+ assert tmpl.render(items=reversed([3, 2, 1])) == "1,2,3"206 207 def test_loop_errors(self, env):161- tmpl = env.from_string('''{% for item in [1] if loop.index162- == 0 %}...{% endfor %}''')208+ tmpl = env.from_string(209+ """{% for item in [1] if loop.index210+ == 0 %}...{% endfor %}"""211+ )212 pytest.raises(UndefinedError, tmpl.render)164- tmpl = env.from_string('''{% for item in [] %}...{% else165- %}{{ loop }}{% endfor %}''')166- assert tmpl.render() == ''213+ tmpl = env.from_string(214+ """{% for item in [] %}...{% else215+ %}{{ loop }}{% endfor %}"""216+ )217+ assert tmpl.render() == ""218 219 def test_loop_filter(self, env):169- tmpl = env.from_string('{% for item in range(10) if item '170- 'is even %}[{{ item }}]{% endfor %}')171- assert tmpl.render() == '[0][2][4][6][8]'172- tmpl = env.from_string('''220+ tmpl = env.from_string(221+ "{% for item in range(10) if item is even %}[{{ item }}]{% endfor %}"222+ )223+ assert tmpl.render() == "[0][2][4][6][8]"224+ tmpl = env.from_string(225+ """226 {%- for item in range(10) if item is even %}[{{174- loop.index }}:{{ item }}]{% endfor %}''')175- assert tmpl.render() == '[1:0][2:2][3:4][4:6][5:8]'227+ loop.index }}:{{ item }}]{% endfor %}"""228+ )229+ assert tmpl.render() == "[1:0][2:2][3:4][4:6][5:8]"230 231 def test_loop_unassignable(self, env):178- pytest.raises(TemplateSyntaxError, env.from_string,179- '{% for loop in seq %}...{% endfor %}')232+ pytest.raises(233+ TemplateSyntaxError, env.from_string, "{% for loop in seq %}...{% endfor %}"234+ )235 236 def test_scoped_special_var(self, env):237 t = env.from_string(183- '{% for s in seq %}[{{ loop.first }}{% for c in s %}'184- '|{{ loop.first }}{% endfor %}]{% endfor %}')185- assert t.render(seq=('ab', 'cd')) \186- == '[True|True|False][False|True|False]'238+ "{% for s in seq %}[{{ loop.first }}{% for c in s %}"239+ "|{{ loop.first }}{% endfor %}]{% endfor %}"240+ )241+ assert t.render(seq=("ab", "cd")) == "[True|True|False][False|True|False]"242 243 def test_scoped_loop_var(self, env):189- t = env.from_string('{% for x in seq %}{{ loop.first }}'190- '{% for y in seq %}{% endfor %}{% endfor %}')191- assert t.render(seq='ab') == 'TrueFalse'192- t = env.from_string('{% for x in seq %}{% for y in seq %}'193- '{{ loop.first }}{% endfor %}{% endfor %}')194- assert t.render(seq='ab') == 'TrueFalseTrueFalse'244+ t = env.from_string(245+ "{% for x in seq %}{{ loop.first }}"246+ "{% for y in seq %}{% endfor %}{% endfor %}"247+ )248+ assert t.render(seq="ab") == "TrueFalse"249+ t = env.from_string(250+ "{% for x in seq %}{% for y in seq %}"251+ "{{ loop.first }}{% endfor %}{% endfor %}"252+ )253+ assert t.render(seq="ab") == "TrueFalseTrueFalse"254 255 def test_recursive_empty_loop_iter(self, env):197- t = env.from_string('''256+ t = env.from_string(257+ """258 {%- for item in foo recursive -%}{%- endfor -%}259+ """199- ''')200- assert t.render(dict(foo=[])) == ''260+ )261+ assert t.render(dict(foo=[])) == ""262 263 def test_call_in_loop(self, env):203- t = env.from_string('''264+ t = env.from_string(265+ """266 {%- macro do_something() -%}267 [{{ caller() }}]268 {%- endmacro %}269 1 unmodified line271 {%- call do_something() -%}272 {{ i }}273 {%- endcall %}274 {%- endfor -%}213- ''')214- assert t.render() == '[1][2][3]'275+ """276+ )277+ assert t.render() == "[1][2][3]"278 279 def test_scoping_bug(self, env):217- t = env.from_string('''280+ t = env.from_string(281+ """282 {%- for item in foo %}...{{ item }}...{% endfor %}283 {%- macro item(a) %}...{{ a }}...{% endmacro %}284 {{- item(2) -}}221- ''')222- assert t.render(foo=(1,)) == '...1......2...'285+ """286+ )287+ assert t.render(foo=(1,)) == "...1......2..."288 289 def test_unpacking(self, env):225- tmpl = env.from_string('{% for a, b, c in [[1, 2, 3]] %}'226- '{{ a }}|{{ b }}|{{ c }}{% endfor %}')227- assert tmpl.render() == '1|2|3'290+ tmpl = env.from_string(291+ "{% for a, b, c in [[1, 2, 3]] %}{{ a }}|{{ b }}|{{ c }}{% endfor %}"292+ )293+ assert tmpl.render() == "1|2|3"294 295 def test_intended_scoping_with_set(self, env):230- tmpl = env.from_string('{% for item in seq %}{{ x }}'231- '{% set x = item %}{{ x }}{% endfor %}')232- assert tmpl.render(x=0, seq=[1, 2, 3]) == '010203'296+ tmpl = env.from_string(297+ "{% for item in seq %}{{ x }}{% set x = item %}{{ x }}{% endfor %}"298+ )299+ assert tmpl.render(x=0, seq=[1, 2, 3]) == "010203"300 234- tmpl = env.from_string('{% set x = 9 %}{% for item in seq %}{{ x }}'235- '{% set x = item %}{{ x }}{% endfor %}')236- assert tmpl.render(x=0, seq=[1, 2, 3]) == '919293'301+ tmpl = env.from_string(302+ "{% set x = 9 %}{% for item in seq %}{{ x }}"303+ "{% set x = item %}{{ x }}{% endfor %}"304+ )305+ assert tmpl.render(x=0, seq=[1, 2, 3]) == "919293"306 307 308 @pytest.mark.core_tags309 @pytest.mark.if_condition310 class TestIfCondition(object):242-311 def test_simple(self, env):244- tmpl = env.from_string('''{% if true %}...{% endif %}''')245- assert tmpl.render() == '...'312+ tmpl = env.from_string("""{% if true %}...{% endif %}""")313+ assert tmpl.render() == "..."314 315 def test_elif(self, env):248- tmpl = env.from_string('''{% if false %}XXX{% elif true249- %}...{% else %}XXX{% endif %}''')250- assert tmpl.render() == '...'316+ tmpl = env.from_string(317+ """{% if false %}XXX{% elif true318+ %}...{% else %}XXX{% endif %}"""319+ )320+ assert tmpl.render() == "..."321 322 def test_elif_deep(self, env):253- elifs = '\n'.join('{{% elif a == {0} %}}{0}'.format(i)254- for i in range(1, 1000))255- tmpl = env.from_string('{{% if a == 0 %}}0{0}{{% else %}}x{{% endif %}}'256- .format(elifs))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+ )327 for x in (0, 10, 999):328 assert tmpl.render(a=x).strip() == str(x)259- assert tmpl.render(a=1000).strip() == 'x'329+ assert tmpl.render(a=1000).strip() == "x"330 331 def test_else(self, env):262- tmpl = env.from_string('{% if false %}XXX{% else %}...{% endif %}')263- assert tmpl.render() == '...'332+ tmpl = env.from_string("{% if false %}XXX{% else %}...{% endif %}")333+ assert tmpl.render() == "..."334 335 def test_empty(self, env):266- tmpl = env.from_string('[{% if true %}{% else %}{% endif %}]')267- assert tmpl.render() == '[]'336+ tmpl = env.from_string("[{% if true %}{% else %}{% endif %}]")337+ assert tmpl.render() == "[]"338 339 def test_complete(self, env):270- tmpl = env.from_string('{% if a %}A{% elif b %}B{% elif c == d %}'271- 'C{% else %}D{% endif %}')272- assert tmpl.render(a=0, b=False, c=42, d=42.0) == 'C'340+ tmpl = env.from_string(341+ "{% if a %}A{% elif b %}B{% elif c == d %}C{% else %}D{% endif %}"342+ )343+ assert tmpl.render(a=0, b=False, c=42, d=42.0) == "C"344 345 def test_no_scope(self, env):275- tmpl = env.from_string(276- '{% if a %}{% set foo = 1 %}{% endif %}{{ foo }}')277- assert tmpl.render(a=True) == '1'278- tmpl = env.from_string(279- '{% if true %}{% set foo = 1 %}{% endif %}{{ foo }}')280- assert tmpl.render() == '1'346+ tmpl = env.from_string("{% if a %}{% set foo = 1 %}{% endif %}{{ foo }}")347+ assert tmpl.render(a=True) == "1"348+ tmpl = env.from_string("{% if true %}{% set foo = 1 %}{% endif %}{{ foo }}")349+ assert tmpl.render() == "1"350 351 352 @pytest.mark.core_tags353 @pytest.mark.macros354 class TestMacros(object):355 def test_simple(self, env_trim):287- tmpl = env_trim.from_string('''\356+ tmpl = env_trim.from_string(357+ """\358 {% macro say_hello(name) %}Hello {{ name }}!{% endmacro %}289-{{ say_hello('Peter') }}''')290- assert tmpl.render() == 'Hello Peter!'359+{{ say_hello('Peter') }}"""360+ )361+ assert tmpl.render() == "Hello Peter!"362 363 def test_scoping(self, env_trim):293- tmpl = env_trim.from_string('''\364+ tmpl = env_trim.from_string(365+ """\366 {% macro level1(data1) %}367 {% macro level2(data2) %}{{ data1 }}|{{ data2 }}{% endmacro %}368 {{ level2('bar') }}{% endmacro %}297-{{ level1('foo') }}''')298- assert tmpl.render() == 'foo|bar'369+{{ level1('foo') }}"""370+ )371+ assert tmpl.render() == "foo|bar"372 373 def test_arguments(self, env_trim):301- tmpl = env_trim.from_string('''\374+ tmpl = env_trim.from_string(375+ """\376 {% macro m(a, b, c='c', d='d') %}{{ a }}|{{ b }}|{{ c }}|{{ d }}{% endmacro %}303-{{ m() }}|{{ m('a') }}|{{ m('a', 'b') }}|{{ m(1, 2, 3) }}''')304- assert tmpl.render() == '||c|d|a||c|d|a|b|c|d|1|2|3|d'377+{{ m() }}|{{ m('a') }}|{{ m('a', 'b') }}|{{ m(1, 2, 3) }}"""378+ )379+ assert tmpl.render() == "||c|d|a||c|d|a|b|c|d|1|2|3|d"380 381 def test_arguments_defaults_nonsense(self, env_trim):307- pytest.raises(TemplateSyntaxError, env_trim.from_string, '''\308-{% macro m(a, b=1, c) %}a={{ a }}, b={{ b }}, c={{ c }}{% endmacro %}''')382+ pytest.raises(383+ TemplateSyntaxError,384+ env_trim.from_string,385+ """\386+{% macro m(a, b=1, c) %}a={{ a }}, b={{ b }}, c={{ c }}{% endmacro %}""",387+ )388 389 def test_caller_defaults_nonsense(self, env_trim):311- pytest.raises(TemplateSyntaxError, env_trim.from_string, '''\390+ pytest.raises(391+ TemplateSyntaxError,392+ env_trim.from_string,393+ """\394 {% macro a() %}{{ caller() }}{% endmacro %}313-{% call(x, y=1, z) a() %}{% endcall %}''')395+{% call(x, y=1, z) a() %}{% endcall %}""",396+ )397 398 def test_varargs(self, env_trim):316- tmpl = env_trim.from_string('''\399+ tmpl = env_trim.from_string(400+ """\401 {% macro test() %}{{ varargs|join('|') }}{% endmacro %}\318-{{ test(1, 2, 3) }}''')319- assert tmpl.render() == '1|2|3'402+{{ test(1, 2, 3) }}"""403+ )404+ assert tmpl.render() == "1|2|3"405 406 def test_simple_call(self, env_trim):322- tmpl = env_trim.from_string('''\407+ tmpl = env_trim.from_string(408+ """\409 {% macro test() %}[[{{ caller() }}]]{% endmacro %}\324-{% call test() %}data{% endcall %}''')325- assert tmpl.render() == '[[data]]'410+{% call test() %}data{% endcall %}"""411+ )412+ assert tmpl.render() == "[[data]]"413 414 def test_complex_call(self, env_trim):328- tmpl = env_trim.from_string('''\415+ tmpl = env_trim.from_string(416+ """\417 {% macro test() %}[[{{ caller('data') }}]]{% endmacro %}\330-{% call(data) test() %}{{ data }}{% endcall %}''')331- assert tmpl.render() == '[[data]]'418+{% call(data) test() %}{{ data }}{% endcall %}"""419+ )420+ assert tmpl.render() == "[[data]]"421 422 def test_caller_undefined(self, env_trim):334- tmpl = env_trim.from_string('''\423+ tmpl = env_trim.from_string(424+ """\425 {% set caller = 42 %}\426 {% macro test() %}{{ caller is not defined }}{% endmacro %}\337-{{ test() }}''')338- assert tmpl.render() == 'True'427+{{ test() }}"""428+ )429+ assert tmpl.render() == "True"430 431 def test_include(self, env_trim):432 env_trim = Environment(342- loader=DictLoader({343- 'include': '{% macro test(foo) %}[{{ foo }}]{% endmacro %}'344- })433+ loader=DictLoader(434+ {"include": "{% macro test(foo) %}[{{ foo }}]{% endmacro %}"}435+ )436 )346- tmpl = env_trim.from_string(347- '{% from "include" import test %}{{ test("foo") }}')348- assert tmpl.render() == '[foo]'437+ tmpl = env_trim.from_string('{% from "include" import test %}{{ test("foo") }}')438+ assert tmpl.render() == "[foo]"439 440 def test_macro_api(self, env_trim):441 tmpl = env_trim.from_string(352- '{% macro foo(a, b) %}{% endmacro %}'353- '{% macro bar() %}{{ varargs }}{{ kwargs }}{% endmacro %}'354- '{% macro baz() %}{{ caller() }}{% endmacro %}')355- assert tmpl.module.foo.arguments == ('a', 'b')356- assert tmpl.module.foo.name == 'foo'442+ "{% macro foo(a, b) %}{% endmacro %}"443+ "{% macro bar() %}{{ varargs }}{{ kwargs }}{% endmacro %}"444+ "{% macro baz() %}{{ caller() }}{% endmacro %}"445+ )446+ assert tmpl.module.foo.arguments == ("a", "b")447+ assert tmpl.module.foo.name == "foo"448 assert not tmpl.module.foo.caller449 assert not tmpl.module.foo.catch_kwargs450 assert not tmpl.module.foo.catch_varargs451 assert tmpl.module.bar.arguments == ()2 unmodified lines454 assert tmpl.module.bar.catch_varargs455 assert tmpl.module.baz.caller456 457 def test_callself(self, env_trim):367- tmpl = env_trim.from_string('{% macro foo(x) %}{{ x }}{% if x > 1 %}|'368- '{{ foo(x - 1) }}{% endif %}{% endmacro %}'369- '{{ foo(5) }}')370- assert tmpl.render() == '5|4|3|2|1'458+ tmpl = env_trim.from_string(459+ "{% macro foo(x) %}{{ x }}{% if x > 1 %}|"460+ "{{ foo(x - 1) }}{% endif %}{% endmacro %}"461+ "{{ foo(5) }}"462+ )463+ assert tmpl.render() == "5|4|3|2|1"464 465 def test_macro_defaults_self_ref(self, env):373- tmpl = env.from_string('''466+ tmpl = env.from_string(467+ """468 {%- set x = 42 %}469 {%- macro m(a, b=x, x=23) %}{{ a }}|{{ b }}|{{ x }}{% endmacro -%}376- ''')377- assert tmpl.module.m(1) == '1||23'378- assert tmpl.module.m(1, 2) == '1|2|23'379- assert tmpl.module.m(1, 2, 3) == '1|2|3'380- assert tmpl.module.m(1, x=7) == '1|7|7'470+ """471+ )472+ assert tmpl.module.m(1) == "1||23"473+ assert tmpl.module.m(1, 2) == "1|2|23"474+ assert tmpl.module.m(1, 2, 3) == "1|2|3"475+ assert tmpl.module.m(1, x=7) == "1|7|7"476 477 478 @pytest.mark.core_tags479 @pytest.mark.set480 class TestSet(object):386-481 def test_normal(self, env_trim):388- tmpl = env_trim.from_string('{% set foo = 1 %}{{ foo }}')389- assert tmpl.render() == '1'482+ tmpl = env_trim.from_string("{% set foo = 1 %}{{ foo }}")483+ assert tmpl.render() == "1"484 assert tmpl.module.foo == 1485 486 def test_block(self, env_trim):393- tmpl = env_trim.from_string('{% set foo %}42{% endset %}{{ foo }}')394- assert tmpl.render() == '42'395- assert tmpl.module.foo == u'42'487+ tmpl = env_trim.from_string("{% set foo %}42{% endset %}{{ foo }}")488+ assert tmpl.render() == "42"489+ assert tmpl.module.foo == u"42"490 491 def test_block_escaping(self):492 env = Environment(autoescape=True)399- tmpl = env.from_string('{% set foo %}<em>{{ test }}</em>'400- '{% endset %}foo: {{ foo }}')401- assert tmpl.render(test='<unsafe>') == 'foo: <em><unsafe></em>'493+ tmpl = env.from_string(494+ "{% set foo %}<em>{{ test }}</em>{% endset %}foo: {{ foo }}"495+ )496+ assert tmpl.render(test="<unsafe>") == "foo: <em><unsafe></em>"497 498 def test_set_invalid(self, env_trim):404- pytest.raises(TemplateSyntaxError, env_trim.from_string,405- "{% set foo['bar'] = 1 %}")406- tmpl = env_trim.from_string('{% set foo.bar = 1 %}')499+ pytest.raises(500+ TemplateSyntaxError, env_trim.from_string, "{% set foo['bar'] = 1 %}"501+ )502+ tmpl = env_trim.from_string("{% set foo.bar = 1 %}")503 exc_info = pytest.raises(TemplateRuntimeError, tmpl.render, foo={})408- assert 'non-namespace object' in exc_info.value.message504+ assert "non-namespace object" in exc_info.value.message505 506 def test_namespace_redefined(self, env_trim):411- tmpl = env_trim.from_string('{% set ns = namespace() %}'412- '{% set ns.bar = "hi" %}')413- exc_info = pytest.raises(TemplateRuntimeError, tmpl.render,414- namespace=dict)415- assert 'non-namespace object' in exc_info.value.message507+ tmpl = env_trim.from_string("{% set ns = namespace() %}{% set ns.bar = 'hi' %}")508+ exc_info = pytest.raises(TemplateRuntimeError, tmpl.render, namespace=dict)509+ assert "non-namespace object" in exc_info.value.message510 511 def test_namespace(self, env_trim):418- tmpl = env_trim.from_string('{% set ns = namespace() %}'419- '{% set ns.bar = "42" %}'420- '{{ ns.bar }}')421- assert tmpl.render() == '42'512+ tmpl = env_trim.from_string(513+ "{% set ns = namespace() %}{% set ns.bar = '42' %}{{ ns.bar }}"514+ )515+ assert tmpl.render() == "42"516 517 def test_namespace_block(self, env_trim):424- tmpl = env_trim.from_string('{% set ns = namespace() %}'425- '{% set ns.bar %}42{% endset %}'426- '{{ ns.bar }}')427- assert tmpl.render() == '42'518+ tmpl = env_trim.from_string(519+ "{% set ns = namespace() %}{% set ns.bar %}42{% endset %}{{ ns.bar }}"520+ )521+ assert tmpl.render() == "42"522 523 def test_init_namespace(self, env_trim):430- tmpl = env_trim.from_string('{% set ns = namespace(d, self=37) %}'431- '{% set ns.b = 42 %}'432- '{{ ns.a }}|{{ ns.self }}|{{ ns.b }}')433- assert tmpl.render(d={'a': 13}) == '13|37|42'524+ tmpl = env_trim.from_string(525+ "{% set ns = namespace(d, self=37) %}"526+ "{% set ns.b = 42 %}"527+ "{{ ns.a }}|{{ ns.self }}|{{ ns.b }}"528+ )529+ assert tmpl.render(d={"a": 13}) == "13|37|42"530 531 def test_namespace_loop(self, env_trim):436- tmpl = env_trim.from_string('{% set ns = namespace(found=false) %}'437- '{% for x in range(4) %}'438- '{% if x == v %}'439- '{% set ns.found = true %}'440- '{% endif %}'441- '{% endfor %}'442- '{{ ns.found }}')443- assert tmpl.render(v=3) == 'True'444- assert tmpl.render(v=4) == 'False'532+ tmpl = env_trim.from_string(533+ "{% set ns = namespace(found=false) %}"534+ "{% for x in range(4) %}"535+ "{% if x == v %}"536+ "{% set ns.found = true %}"537+ "{% endif %}"538+ "{% endfor %}"539+ "{{ ns.found }}"540+ )541+ assert tmpl.render(v=3) == "True"542+ assert tmpl.render(v=4) == "False"543 544 def test_namespace_macro(self, env_trim):447- tmpl = env_trim.from_string('{% set ns = namespace() %}'448- '{% set ns.a = 13 %}'449- '{% macro magic(x) %}'450- '{% set x.b = 37 %}'451- '{% endmacro %}'452- '{{ magic(ns) }}'453- '{{ ns.a }}|{{ ns.b }}')454- assert tmpl.render() == '13|37'545+ tmpl = env_trim.from_string(546+ "{% set ns = namespace() %}"547+ "{% set ns.a = 13 %}"548+ "{% macro magic(x) %}"549+ "{% set x.b = 37 %}"550+ "{% endmacro %}"551+ "{{ magic(ns) }}"552+ "{{ ns.a }}|{{ ns.b }}"553+ )554+ assert tmpl.render() == "13|37"555 556 def test_block_escaping_filtered(self):557 env = Environment(autoescape=True)458- tmpl = env.from_string('{% set foo | trim %}<em>{{ test }}</em> '459- '{% endset %}foo: {{ foo }}')460- assert tmpl.render(test='<unsafe>') == 'foo: <em><unsafe></em>'558+ tmpl = env.from_string(559+ "{% set foo | trim %}<em>{{ test }}</em> {% endset %}foo: {{ foo }}"560+ )561+ assert tmpl.render(test="<unsafe>") == "foo: <em><unsafe></em>"562 563 def test_block_filtered(self, env_trim):564 tmpl = env_trim.from_string(464- '{% set foo | trim | length | string %} 42 {% endset %}'465- '{{ foo }}')466- assert tmpl.render() == '2'467- assert tmpl.module.foo == u'2'565+ "{% set foo | trim | length | string %} 42 {% endset %}{{ foo }}"566+ )567+ assert tmpl.render() == "2"568+ assert tmpl.module.foo == u"2"569 570 def test_block_filtered_set(self, env_trim):571 def _myfilter(val, arg):471- assert arg == ' xxx '572+ assert arg == " xxx "573 return val574+473- env_trim.filters['myfilter'] = _myfilter575+ env_trim.filters["myfilter"] = _myfilter576 tmpl = env_trim.from_string(577 '{% set a = " xxx " %}'476- '{% set foo | myfilter(a) | trim | length | string %}'578+ "{% set foo | myfilter(a) | trim | length | string %}"579 ' {% set b = " yy " %} 42 {{ a }}{{ b }} '478- '{% endset %}'479- '{{ foo }}')480- assert tmpl.render() == '11'481- assert tmpl.module.foo == u'11'580+ "{% endset %}"581+ "{{ foo }}"582+ )583+ assert tmpl.render() == "11"584+ assert tmpl.module.foo == u"11"585 586 587 @pytest.mark.core_tags588 @pytest.mark.with_589 class TestWith(object):487-590 def test_with(self, env):489- tmpl = env.from_string('''\591+ tmpl = env.from_string(592+ """\593 {% with a=42, b=23 -%}594 {{ a }} = {{ b }}595 {% endwith -%}596 {{ a }} = {{ b }}\494- ''')495- assert [x.strip() for x in tmpl.render(a=1, b=2).splitlines()] \496- == ['42 = 23', '1 = 2']597+ """598+ )599+ assert [x.strip() for x in tmpl.render(a=1, b=2).splitlines()] == [600+ "42 = 23",601+ "1 = 2",602+ ]603 604 def test_with_argument_scoping(self, env):499- tmpl = env.from_string('''\605+ tmpl = env.from_string(606+ """\607 {%- with a=1, b=2, c=b, d=e, e=5 -%}608 {{ a }}|{{ b }}|{{ c }}|{{ d }}|{{ e }}609 {%- endwith -%}503- ''')504- assert tmpl.render(b=3, e=4) == '1|2|3|4|5'610+ """611+ )612+ assert tmpl.render(b=3, e=4) == "1|2|3|4|5"modified:tests/test_debug.py+58 added-51 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.debug4- ~~~~~~~~~~~~~~~~~~~~~~5-6- Tests the debug system.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-import pytest12-2 import pickle3 import re15-import sys4 from traceback import format_exception5 6+import pytest7+8 from jinja2 import ChoiceLoader9 from jinja2 import DictLoader20-from jinja2 import Environment, TemplateSyntaxError10+from jinja2 import Environment11+from jinja2 import TemplateSyntaxError12 13 14 @pytest.fixture15 def fs_env(filesystem_loader):25- '''returns a new environment.26- '''16+ """returns a new environment."""17 return Environment(loader=filesystem_loader)18 19 20 @pytest.mark.debug21 class TestDebug(object):32-22 def assert_traceback_matches(self, callback, expected_tb):34- try:23+ with pytest.raises(Exception) as exc_info:24 callback()36- except Exception as e:37- tb = format_exception(*sys.exc_info())38- if re.search(expected_tb.strip(), ''.join(tb)) is None:39- assert False, ('Traceback did not match:\n\n%s\nexpected:\n%s' %40- (''.join(tb), expected_tb))41- else:42- assert False, 'Expected exception'25 26+ tb = format_exception(exc_info.type, exc_info.value, exc_info.tb)27+ 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+ )32+33 def test_runtime_error(self, fs_env):34 def test():35 tmpl.render(fail=lambda: 1 / 0)36+47- tmpl = fs_env.get_template('broken.html')48- self.assert_traceback_matches(test, r'''37+ tmpl = fs_env.get_template("broken.html")38+ self.assert_traceback_matches(39+ test,40+ r"""41 File ".*?broken.html", line 2, in (top-level template code|<module>)42 \{\{ fail\(\) \}\}43 File ".*debug?.pyc?", line \d+, in <lambda>44 tmpl\.render\(fail=lambda: 1 / 0\)45 ZeroDivisionError: (int(eger)? )?division (or modulo )?by zero54-''')46+""",47+ )48 49 def test_syntax_error(self, fs_env):50 # The trailing .*? is for PyPy 2 and 3, which don't seem to51 # clear the exception's original traceback, leaving the syntax52 # error in the middle of other compiler frames.60- self.assert_traceback_matches(lambda: fs_env.get_template('syntaxerror.html'), r'''(?sm)53+ self.assert_traceback_matches(54+ lambda: fs_env.get_template("syntaxerror.html"),55+ """(?sm)56 File ".*?syntaxerror.html", line 4, in (template|<module>)62- \{% endif %\}.*?63-(jinja2\.exceptions\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja was looking for the following tags: 'endfor' or 'else'. The innermost block that needs to be closed is 'for'.64- ''')57+ \\{% endif %\\}.*?58+(jinja2\\.exceptions\\.)?TemplateSyntaxError: Encountered unknown tag 'endif'. Jinja \59+was looking for the following tags: 'endfor' or 'else'. The innermost block that needs \60+to be closed is 'for'.61+ """,62+ )63 64 def test_regular_syntax_error(self, fs_env):65 def test():68- raise TemplateSyntaxError('wtf', 42)69- self.assert_traceback_matches(test, r'''66+ raise TemplateSyntaxError("wtf", 42)67+68+ self.assert_traceback_matches(69+ test,70+ r"""71 File ".*debug.pyc?", line \d+, in test71- raise TemplateSyntaxError\('wtf', 42\)72+ raise TemplateSyntaxError\("wtf", 42\)73 (jinja2\.exceptions\.)?TemplateSyntaxError: wtf73- line 42''')74+ line 42""",75+ )76 77 def test_pickleable_syntax_error(self, fs_env):78 original = TemplateSyntaxError("bad template", 42, "test", "test.txt")79 unpickled = pickle.loads(pickle.dumps(original))80 assert str(original) == str(unpickled)81 assert original.name == unpickled.name82 83 def test_include_syntax_error_source(self, filesystem_loader):84+ e = Environment(82- e = Environment(loader=ChoiceLoader(83- [84- filesystem_loader,85- DictLoader({"inc": "a\n{% include 'syntaxerror.html' %}\nb"}),86- ]87- ))85+ loader=ChoiceLoader(86+ [87+ filesystem_loader,88+ DictLoader({"inc": "a\n{% include 'syntaxerror.html' %}\nb"}),89+ ]90+ )91+ )92 t = e.get_template("inc")93 94 with pytest.raises(TemplateSyntaxError) as exc_info:95 t.render()2 unmodified lines98 99 def test_local_extraction(self):100 from jinja2.debug import get_template_locals101 from jinja2.runtime import missing98- locals = get_template_locals({99- 'l_0_foo': 42,100- 'l_1_foo': 23,101- 'l_2_foo': 13,102- 'l_0_bar': 99,103- 'l_1_bar': missing,104- 'l_0_baz': missing,105- })106- assert locals == {'foo': 13, 'bar': 99}102 103+ locals = get_template_locals(104+ {105+ "l_0_foo": 42,106+ "l_1_foo": 23,107+ "l_2_foo": 13,108+ "l_0_bar": 99,109+ "l_1_bar": missing,110+ "l_0_baz": missing,111+ }112+ )113+ assert locals == {"foo": 13, "bar": 99}114+115 def test_get_corresponding_lineno_traceback(self, fs_env):109- tmpl = fs_env.get_template('test.html')116+ tmpl = fs_env.get_template("test.html")117 assert tmpl.get_corresponding_lineno(1) == 1modified:tests/test_ext.py+324 added-277 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.ext4- ~~~~~~~~~~~~~~~~~~~~5-6- Tests for the extensions.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import re3+4 import pytest5 14-from jinja2 import Environment, DictLoader, contextfunction, nodes6+from jinja2 import contextfunction7+from jinja2 import DictLoader8+from jinja2 import Environment9+from jinja2 import nodes10+from jinja2._compat import BytesIO11+from jinja2._compat import itervalues12+from jinja2._compat import text_type13 from jinja2.exceptions import TemplateAssertionError14 from jinja2.ext import Extension17-from jinja2.lexer import Token, count_newlines18-from jinja2._compat import BytesIO, itervalues, text_type15+from jinja2.lexer import count_newlines16+from jinja2.lexer import Token17 18 importable_object = 2319 22-_gettext_re = re.compile(r'_\((.*?)\)', re.DOTALL)20+_gettext_re = re.compile(r"_\((.*?)\)", re.DOTALL)21 22 23 i18n_templates = {26- 'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'27- '{% block body %}{% endblock %}',28- 'child.html': '{% extends "master.html" %}{% block body %}'29- '{% trans %}watch out{% endtrans %}{% endblock %}',30- 'plural.html': '{% trans user_count %}One user online{% pluralize %}'31- '{{ user_count }} users online{% endtrans %}',32- 'plural2.html': '{% trans user_count=get_user_count() %}{{ user_count }}s'33- '{% pluralize %}{{ user_count }}p{% endtrans %}',34- 'stringformat.html': '{{ _("User: %(num)s")|format(num=user_count) }}'24+ "master.html": '<title>{{ page_title|default(_("missing")) }}</title>'25+ "{% block body %}{% endblock %}",26+ "child.html": '{% extends "master.html" %}{% block body %}'27+ "{% trans %}watch out{% endtrans %}{% endblock %}",28+ "plural.html": "{% trans user_count %}One user online{% pluralize %}"29+ "{{ user_count }} users online{% endtrans %}",30+ "plural2.html": "{% trans user_count=get_user_count() %}{{ user_count }}s"31+ "{% pluralize %}{{ user_count }}p{% endtrans %}",32+ "stringformat.html": '{{ _("User: %(num)s")|format(num=user_count) }}',33 }34 35 newstyle_i18n_templates = {38- 'master.html': '<title>{{ page_title|default(_("missing")) }}</title>'39- '{% block body %}{% endblock %}',40- 'child.html': '{% extends "master.html" %}{% block body %}'41- '{% trans %}watch out{% endtrans %}{% endblock %}',42- 'plural.html': '{% trans user_count %}One user online{% pluralize %}'43- '{{ user_count }} users online{% endtrans %}',44- 'stringformat.html': '{{ _("User: %(num)s", num=user_count) }}',45- 'ngettext.html': '{{ ngettext("%(num)s apple", "%(num)s apples", apples) }}',46- 'ngettext_long.html': '{% trans num=apples %}{{ num }} apple{% pluralize %}'47- '{{ num }} apples{% endtrans %}',48- 'transvars1.html': '{% trans %}User: {{ num }}{% endtrans %}',49- 'transvars2.html': '{% trans num=count %}User: {{ num }}{% endtrans %}',50- 'transvars3.html': '{% trans count=num %}User: {{ count }}{% endtrans %}',51- 'novars.html': '{% trans %}%(hello)s{% endtrans %}',52- 'vars.html': '{% trans %}{{ foo }}%(foo)s{% endtrans %}',53- 'explicitvars.html': '{% trans foo="42" %}%(foo)s{% endtrans %}'36+ "master.html": '<title>{{ page_title|default(_("missing")) }}</title>'37+ "{% block body %}{% endblock %}",38+ "child.html": '{% extends "master.html" %}{% block body %}'39+ "{% trans %}watch out{% endtrans %}{% endblock %}",40+ "plural.html": "{% trans user_count %}One user online{% pluralize %}"41+ "{{ user_count }} users online{% endtrans %}",42+ "stringformat.html": '{{ _("User: %(num)s", num=user_count) }}',43+ "ngettext.html": '{{ ngettext("%(num)s apple", "%(num)s apples", apples) }}',44+ "ngettext_long.html": "{% trans num=apples %}{{ num }} apple{% pluralize %}"45+ "{{ num }} apples{% endtrans %}",46+ "transvars1.html": "{% trans %}User: {{ num }}{% endtrans %}",47+ "transvars2.html": "{% trans num=count %}User: {{ num }}{% endtrans %}",48+ "transvars3.html": "{% trans count=num %}User: {{ count }}{% endtrans %}",49+ "novars.html": "{% trans %}%(hello)s{% endtrans %}",50+ "vars.html": "{% trans %}{{ foo }}%(foo)s{% endtrans %}",51+ "explicitvars.html": '{% trans foo="42" %}%(foo)s{% endtrans %}',52 }53 54 55 languages = {58- 'de': {59- 'missing': u'fehlend',60- 'watch out': u'pass auf',61- 'One user online': u'Ein Benutzer online',62- '%(user_count)s users online': u'%(user_count)s Benutzer online',63- 'User: %(num)s': u'Benutzer: %(num)s',64- 'User: %(count)s': u'Benutzer: %(count)s',65- '%(num)s apple': u'%(num)s Apfel',66- '%(num)s apples': u'%(num)s Äpfel'56+ "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",65 }66 }67 68 69 @contextfunction70 def gettext(context, string):73- language = context.get('LANGUAGE', 'en')71+ language = context.get("LANGUAGE", "en")72 return languages.get(language, {}).get(string, string)73 74 75 @contextfunction76 def ngettext(context, s, p, n):79- language = context.get('LANGUAGE', 'en')77+ language = context.get("LANGUAGE", "en")78 if n != 1:79 return languages.get(language, {}).get(p, p)80 return languages.get(language, {}).get(s, s)81 82 83 i18n_env = Environment(86- loader=DictLoader(i18n_templates),87- extensions=['jinja2.ext.i18n']84+ loader=DictLoader(i18n_templates), extensions=["jinja2.ext.i18n"]85 )89-i18n_env.globals.update({90- '_': gettext,91- 'gettext': gettext,92- 'ngettext': ngettext93-})94-i18n_env_trimmed = Environment(extensions=['jinja2.ext.i18n'])95-i18n_env_trimmed.policies['ext.i18n.trimmed'] = True96-i18n_env_trimmed.globals.update({97- '_': gettext,98- 'gettext': gettext,99- 'ngettext': ngettext100-})86+i18n_env.globals.update({"_": gettext, "gettext": gettext, "ngettext": ngettext})87+i18n_env_trimmed = Environment(extensions=["jinja2.ext.i18n"])88+i18n_env_trimmed.policies["ext.i18n.trimmed"] = True89+i18n_env_trimmed.globals.update(90+ {"_": gettext, "gettext": gettext, "ngettext": ngettext}91+)92 93 newstyle_i18n_env = Environment(103- loader=DictLoader(newstyle_i18n_templates),104- extensions=['jinja2.ext.i18n']94+ loader=DictLoader(newstyle_i18n_templates), extensions=["jinja2.ext.i18n"]95 )96 newstyle_i18n_env.install_gettext_callables(gettext, ngettext, newstyle=True)97 98 99 class ExampleExtension(Extension):110- tags = set(['test'])100+ tags = set(["test"])101 ext_attr = 42102 context_reference_node_cls = nodes.ContextReference103 104 def parse(self, parser):115- return nodes.Output([self.call_method('_dump', [116- nodes.EnvironmentAttribute('sandboxed'),117- self.attr('ext_attr'),118- nodes.ImportedName(__name__ + '.importable_object'),119- self.context_reference_node_cls()120- ])]).set_lineno(next(parser.stream).lineno)105+ return nodes.Output(106+ [107+ self.call_method(108+ "_dump",109+ [110+ nodes.EnvironmentAttribute("sandboxed"),111+ self.attr("ext_attr"),112+ nodes.ImportedName(__name__ + ".importable_object"),113+ self.context_reference_node_cls(),114+ ],115+ )116+ ]117+ ).set_lineno(next(parser.stream).lineno)118 119 def _dump(self, sandboxed, ext_attr, imported_object, context):123- return '%s|%s|%s|%s|%s' % (120+ return "%s|%s|%s|%s|%s" % (121 sandboxed,122 ext_attr,123 imported_object,124 context.blocks,128- context.get('test_var')125+ context.get("test_var"),126 )127 128 129 class DerivedExampleExtension(ExampleExtension):130 context_reference_node_cls = nodes.DerivedContextReference131 132 133 class PreprocessorExtension(Extension):137-134 def preprocess(self, source, name, filename=None):139- return source.replace('[[TEST]]', '({{ foo }})')135+ return source.replace("[[TEST]]", "({{ foo }})")136 137 138 class StreamFilterExtension(Extension):143-139 def filter_stream(self, stream):140 for token in stream:146- if token.type == 'data':141+ if token.type == "data":142 for t in self.interpolate(token):143 yield t144 else:145 yield token5 unmodified lines151 while 1:152 match = _gettext_re.search(token.value, pos)153 if match is None:154 break160- value = token.value[pos:match.start()]155+ value = token.value[pos : match.start()]156 if value:162- yield Token(lineno, 'data', value)157+ yield Token(lineno, "data", value)158 lineno += count_newlines(token.value)164- yield Token(lineno, 'variable_begin', None)165- yield Token(lineno, 'name', 'gettext')166- yield Token(lineno, 'lparen', None)167- yield Token(lineno, 'string', match.group(1))168- yield Token(lineno, 'rparen', None)169- yield Token(lineno, 'variable_end', None)159+ yield Token(lineno, "variable_begin", None)160+ yield Token(lineno, "name", "gettext")161+ yield Token(lineno, "lparen", None)162+ yield Token(lineno, "string", match.group(1))163+ yield Token(lineno, "rparen", None)164+ yield Token(lineno, "variable_end", None)165 pos = match.end()166 if pos < end:172- yield Token(lineno, 'data', token.value[pos:])167+ yield Token(lineno, "data", token.value[pos:])168 169 170 @pytest.mark.ext171 class TestExtensions(object):177-172 def test_extend_late(self):173 env = Environment()180- env.add_extension('jinja2.ext.autoescape')181- t = env.from_string(182- '{% autoescape true %}{{ "<test>" }}{% endautoescape %}')183- assert t.render() == '<test>'174+ env.add_extension("jinja2.ext.autoescape")175+ t = env.from_string('{% autoescape true %}{{ "<test>" }}{% endautoescape %}')176+ assert t.render() == "<test>"177 178 def test_loop_controls(self):186- env = Environment(extensions=['jinja2.ext.loopcontrols'])179+ env = Environment(extensions=["jinja2.ext.loopcontrols"])180 188- tmpl = env.from_string('''181+ tmpl = env.from_string(182+ """183 {%- for item in [1, 2, 3, 4] %}184 {%- if item % 2 == 0 %}{% continue %}{% endif -%}185 {{ item }}192- {%- endfor %}''')193- assert tmpl.render() == '13'186+ {%- endfor %}"""187+ )188+ assert tmpl.render() == "13"189 195- tmpl = env.from_string('''190+ tmpl = env.from_string(191+ """192 {%- for item in [1, 2, 3, 4] %}193 {%- if item > 2 %}{% break %}{% endif -%}194 {{ item }}199- {%- endfor %}''')200- assert tmpl.render() == '12'195+ {%- endfor %}"""196+ )197+ assert tmpl.render() == "12"198 199 def test_do(self):203- env = Environment(extensions=['jinja2.ext.do'])204- tmpl = env.from_string('''200+ env = Environment(extensions=["jinja2.ext.do"])201+ tmpl = env.from_string(202+ """203 {%- set items = [] %}204 {%- for char in "foo" %}205 {%- do items.append(loop.index0 ~ char) %}208- {%- endfor %}{{ items|join(', ') }}''')209- assert tmpl.render() == '0f, 1o, 2o'206+ {%- endfor %}{{ items|join(', ') }}"""207+ )208+ assert tmpl.render() == "0f, 1o, 2o"209 210 def test_extension_nodes(self):211 env = Environment(extensions=[ExampleExtension])213- tmpl = env.from_string('{% test %}')214- assert tmpl.render() == 'False|42|23|{}|None'212+ tmpl = env.from_string("{% test %}")213+ assert tmpl.render() == "False|42|23|{}|None"214 215 def test_contextreference_node_passes_context(self):216 env = Environment(extensions=[ExampleExtension])217 tmpl = env.from_string('{% set test_var="test_content" %}{% test %}')219- assert tmpl.render() == 'False|42|23|{}|test_content'218+ assert tmpl.render() == "False|42|23|{}|test_content"219 220 def test_contextreference_node_can_pass_locals(self):221 env = Environment(extensions=[DerivedExampleExtension])222 tmpl = env.from_string(224- '{% for test_var in ["test_content"] %}{% test %}{% endfor %}')225- assert tmpl.render() == 'False|42|23|{}|test_content'223+ '{% for test_var in ["test_content"] %}{% test %}{% endfor %}'224+ )225+ assert tmpl.render() == "False|42|23|{}|test_content"226 227 def test_identifier(self):228- assert ExampleExtension.identifier == __name__ + '.ExampleExtension'228+ assert ExampleExtension.identifier == __name__ + ".ExampleExtension"229 230 def test_rebinding(self):231 original = Environment(extensions=[ExampleExtension])232 overlay = original.overlay()2 unmodified lines235 assert ext.environment is env236 237 def test_preprocessor_extension(self):238 env = Environment(extensions=[PreprocessorExtension])239- tmpl = env.from_string('{[[TEST]]}')240- assert tmpl.render(foo=42) == '{(42)}'239+ tmpl = env.from_string("{[[TEST]]}")240+ assert tmpl.render(foo=42) == "{(42)}"241 242 def test_streamfilter_extension(self):243 env = Environment(extensions=[StreamFilterExtension])244- env.globals['gettext'] = lambda x: x.upper()245- tmpl = env.from_string('Foo _(bar) Baz')244+ env.globals["gettext"] = lambda x: x.upper()245+ tmpl = env.from_string("Foo _(bar) Baz")246 out = tmpl.render()247- assert out == 'Foo BAR Baz'247+ assert out == "Foo BAR Baz"248 249 def test_extension_ordering(self):250 class T1(Extension):251 priority = 1252 253 class T2(Extension):254 priority = 2255+256 env = Environment(extensions=[T1, T2])257 ext = list(env.iter_extensions())258 assert ext[0].__class__ is T1259 assert ext[1].__class__ is T2260 261 def test_debug(self):261- env = Environment(extensions=['jinja2.ext.debug'])262- t = env.from_string('Hello\n{% debug %}\nGoodbye')262+ env = Environment(extensions=["jinja2.ext.debug"])263+ t = env.from_string("Hello\n{% debug %}\nGoodbye")264 out = t.render()265 266 for value in ("context", "cycler", "filters", "abs", "tests", "!="):267 assert "'{}'".format(value) in out268 269 270 @pytest.mark.ext271 class TestInternationalization(object):271-272 def test_trans(self):273- tmpl = i18n_env.get_template('child.html')274- assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'273+ tmpl = i18n_env.get_template("child.html")274+ assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"275 276 def test_trans_plural(self):277- tmpl = i18n_env.get_template('plural.html')278- assert tmpl.render(LANGUAGE='de', user_count=1) \279- == 'Ein Benutzer online'280- assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'277+ tmpl = i18n_env.get_template("plural.html")278+ assert tmpl.render(LANGUAGE="de", user_count=1) == "Ein Benutzer online"279+ assert tmpl.render(LANGUAGE="de", user_count=2) == "2 Benutzer online"280 281 def test_trans_plural_with_functions(self):283- tmpl = i18n_env.get_template('plural2.html')282+ tmpl = i18n_env.get_template("plural2.html")283 284 def get_user_count():285 get_user_count.called += 1286 return 1287+288 get_user_count.called = 0289- assert tmpl.render(LANGUAGE='de', get_user_count=get_user_count) \290- == '1s'289+ assert tmpl.render(LANGUAGE="de", get_user_count=get_user_count) == "1s"290 assert get_user_count.called == 1291 292 def test_complex_plural(self):293 tmpl = i18n_env.from_string(295- '{% trans foo=42, count=2 %}{{ count }} item{% '296- 'pluralize count %}{{ count }} items{% endtrans %}')297- assert tmpl.render() == '2 items'298- pytest.raises(TemplateAssertionError, i18n_env.from_string,299- '{% trans foo %}...{% pluralize bar %}...{% endtrans %}')294+ "{% trans foo=42, count=2 %}{{ count }} item{% "295+ "pluralize count %}{{ count }} items{% endtrans %}"296+ )297+ assert tmpl.render() == "2 items"298+ pytest.raises(299+ TemplateAssertionError,300+ i18n_env.from_string,301+ "{% trans foo %}...{% pluralize bar %}...{% endtrans %}",302+ )303 304 def test_trans_stringformatting(self):302- tmpl = i18n_env.get_template('stringformat.html')303- assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'305+ tmpl = i18n_env.get_template("stringformat.html")306+ assert tmpl.render(LANGUAGE="de", user_count=5) == "Benutzer: 5"307 308 def test_trimmed(self):309 tmpl = i18n_env.from_string(307- '{%- trans trimmed %} hello\n world {% endtrans -%}')308- assert tmpl.render() == 'hello world'310+ "{%- trans trimmed %} hello\n world {% endtrans -%}"311+ )312+ assert tmpl.render() == "hello world"313 314 def test_trimmed_policy(self):311- s = '{%- trans %} hello\n world {% endtrans -%}'315+ s = "{%- trans %} hello\n world {% endtrans -%}"316 tmpl = i18n_env.from_string(s)317 trimmed_tmpl = i18n_env_trimmed.from_string(s)314- assert tmpl.render() == ' hello\n world '315- assert trimmed_tmpl.render() == 'hello world'318+ assert tmpl.render() == " hello\n world "319+ assert trimmed_tmpl.render() == "hello world"320 321 def test_trimmed_policy_override(self):322 tmpl = i18n_env_trimmed.from_string(319- '{%- trans notrimmed %} hello\n world {% endtrans -%}')320- assert tmpl.render() == ' hello\n world '323+ "{%- trans notrimmed %} hello\n world {% endtrans -%}"324+ )325+ assert tmpl.render() == " hello\n world "326 327 def test_trimmed_vars(self):328 tmpl = i18n_env.from_string(324- '{%- trans trimmed x="world" %} hello\n {{ x }} {% endtrans -%}')325- assert tmpl.render() == 'hello world'329+ '{%- trans trimmed x="world" %} hello\n {{ x }} {% endtrans -%}'330+ )331+ assert tmpl.render() == "hello world"332 333 def test_trimmed_varname_trimmed(self):334 # unlikely variable name, but when used as a variable335 # it should not enable trimming336 tmpl = i18n_env.from_string(331- '{%- trans trimmed = "world" %} hello\n {{ trimmed }} '332- '{% endtrans -%}')333- assert tmpl.render() == ' hello\n world '337+ "{%- trans trimmed = 'world' %} hello\n {{ trimmed }} {% endtrans -%}"338+ )339+ assert tmpl.render() == " hello\n world "340 341 def test_extract(self):342 from jinja2.ext import babel_extract343+337- source = BytesIO('''344+ source = BytesIO(345+ """346 {{ gettext('Hello World') }}347 {% trans %}Hello World{% endtrans %}348 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}341- '''.encode('ascii')) # make python 3 happy342- assert list(babel_extract(source,343- ('gettext', 'ngettext', '_'), [], {})) == [344- (2, 'gettext', u'Hello World', []),345- (3, 'gettext', u'Hello World', []),346- (4, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])349+ """.encode(350+ "ascii"351+ )352+ ) # make python 3 happy353+ 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), []),357 ]358 359 def test_extract_trimmed(self):360 from jinja2.ext import babel_extract361+351- source = BytesIO('''362+ source = BytesIO(363+ """364 {{ gettext(' Hello \n World') }}365 {% trans trimmed %} Hello \n World{% endtrans %}366 {% trans trimmed %}{{ users }} \n user367 {%- pluralize %}{{ users }} \n users{% endtrans %}356- '''.encode('ascii')) # make python 3 happy357- assert list(babel_extract(source,358- ('gettext', 'ngettext', '_'), [], {})) == [359- (2, 'gettext', u' Hello \n World', []),360- (4, 'gettext', u'Hello World', []),361- (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])368+ """.encode(369+ "ascii"370+ )371+ ) # make python 3 happy372+ 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), []),376 ]377 378 def test_extract_trimmed_option(self):379 from jinja2.ext import babel_extract380+366- source = BytesIO('''381+ source = BytesIO(382+ """383 {{ gettext(' Hello \n World') }}384 {% trans %} Hello \n World{% endtrans %}385 {% trans %}{{ users }} \n user386 {%- pluralize %}{{ users }} \n users{% endtrans %}371- '''.encode('ascii')) # make python 3 happy372- opts = {'trimmed': 'true'}373- assert list(babel_extract(source,374- ('gettext', 'ngettext', '_'), [], opts)) == [375- (2, 'gettext', u' Hello \n World', []),376- (4, 'gettext', u'Hello World', []),377- (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None), [])387+ """.encode(388+ "ascii"389+ )390+ ) # make python 3 happy391+ opts = {"trimmed": "true"}392+ 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), []),396 ]397 398 def test_comment_extract(self):399 from jinja2.ext import babel_extract400+382- source = BytesIO('''401+ source = BytesIO(402+ """403 {# trans first #}404 {{ gettext('Hello World') }}405 {% trans %}Hello World{% endtrans %}{# trans second #}406 {#: third #}407 {% trans %}{{ users }} user{% pluralize %}{{ users }} users{% endtrans %}388- '''.encode('utf-8')) # make python 3 happy389- assert list(babel_extract(source,390- ('gettext', 'ngettext', '_'),391- ['trans', ':'], {})) == [392- (3, 'gettext', u'Hello World', ['first']),393- (4, 'gettext', u'Hello World', ['second']),394- (6, 'ngettext', (u'%(users)s user', u'%(users)s users', None),395- ['third'])408+ """.encode(409+ "utf-8"410+ )411+ ) # make python 3 happy412+ assert list(413+ babel_extract(source, ("gettext", "ngettext", "_"), ["trans", ":"], {})414+ ) == [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"]),418 ]419 420 421 @pytest.mark.ext422 class TestScope(object):401-423 def test_basic_scope_behavior(self):424 # This is what the old with statement compiled down to425 class ScopeExt(Extension):405- tags = set(['scope'])426+ tags = set(["scope"])427 428 def parse(self, parser):429 node = nodes.Scope(lineno=next(parser.stream).lineno)430 assignments = []410- while parser.stream.current.type != 'block_end':431+ while parser.stream.current.type != "block_end":432 lineno = parser.stream.current.lineno433 if assignments:413- parser.stream.expect('comma')434+ parser.stream.expect("comma")435 target = parser.parse_assign_target()415- parser.stream.expect('assign')436+ parser.stream.expect("assign")437 expr = parser.parse_expression()438 assignments.append(nodes.Assign(target, expr, lineno=lineno))418- node.body = assignments + \419- list(parser.parse_statements(('name:endscope',),420- drop_needle=True))439+ node.body = assignments + list(440+ parser.parse_statements(("name:endscope",), drop_needle=True)441+ )442 return node443 444 env = Environment(extensions=[ScopeExt])424- tmpl = env.from_string('''\445+ tmpl = env.from_string(446+ """\447 {%- scope a=1, b=2, c=b, d=e, e=5 -%}448 {{ a }}|{{ b }}|{{ c }}|{{ d }}|{{ e }}449 {%- endscope -%}428- ''')429- assert tmpl.render(b=3, e=4) == '1|2|2|4|5'450+ """451+ )452+ assert tmpl.render(b=3, e=4) == "1|2|2|4|5"453 454 455 @pytest.mark.ext456 class TestNewstyleInternationalization(object):434-457 def test_trans(self):436- tmpl = newstyle_i18n_env.get_template('child.html')437- assert tmpl.render(LANGUAGE='de') == '<title>fehlend</title>pass auf'458+ tmpl = newstyle_i18n_env.get_template("child.html")459+ assert tmpl.render(LANGUAGE="de") == "<title>fehlend</title>pass auf"460 461 def test_trans_plural(self):440- tmpl = newstyle_i18n_env.get_template('plural.html')441- assert tmpl.render(LANGUAGE='de', user_count=1) \442- == 'Ein Benutzer online'443- assert tmpl.render(LANGUAGE='de', user_count=2) == '2 Benutzer online'462+ tmpl = newstyle_i18n_env.get_template("plural.html")463+ assert tmpl.render(LANGUAGE="de", user_count=1) == "Ein Benutzer online"464+ assert tmpl.render(LANGUAGE="de", user_count=2) == "2 Benutzer online"465 466 def test_complex_plural(self):467 tmpl = newstyle_i18n_env.from_string(447- '{% trans foo=42, count=2 %}{{ count }} item{% '448- 'pluralize count %}{{ count }} items{% endtrans %}')449- assert tmpl.render() == '2 items'450- pytest.raises(TemplateAssertionError, i18n_env.from_string,451- '{% trans foo %}...{% pluralize bar %}...{% endtrans %}')468+ "{% trans foo=42, count=2 %}{{ count }} item{% "469+ "pluralize count %}{{ count }} items{% endtrans %}"470+ )471+ assert tmpl.render() == "2 items"472+ pytest.raises(473+ TemplateAssertionError,474+ i18n_env.from_string,475+ "{% trans foo %}...{% pluralize bar %}...{% endtrans %}",476+ )477 478 def test_trans_stringformatting(self):454- tmpl = newstyle_i18n_env.get_template('stringformat.html')455- assert tmpl.render(LANGUAGE='de', user_count=5) == 'Benutzer: 5'479+ tmpl = newstyle_i18n_env.get_template("stringformat.html")480+ assert tmpl.render(LANGUAGE="de", user_count=5) == "Benutzer: 5"481 482 def test_newstyle_plural(self):458- tmpl = newstyle_i18n_env.get_template('ngettext.html')459- assert tmpl.render(LANGUAGE='de', apples=1) == '1 Apfel'460- assert tmpl.render(LANGUAGE='de', apples=5) == u'5 Äpfel'483+ tmpl = newstyle_i18n_env.get_template("ngettext.html")484+ assert tmpl.render(LANGUAGE="de", apples=1) == "1 Apfel"485+ assert tmpl.render(LANGUAGE="de", apples=5) == u"5 Äpfel"486 487 def test_autoescape_support(self):463- env = Environment(extensions=['jinja2.ext.autoescape',464- 'jinja2.ext.i18n'])488+ env = Environment(extensions=["jinja2.ext.autoescape", "jinja2.ext.i18n"])489 env.install_gettext_callables(466- lambda x: u'<strong>Wert: %(name)s</strong>',467- lambda s, p, n: s, newstyle=True)468- t = env.from_string('{% autoescape ae %}{{ gettext("foo", name='469- '"<test>") }}{% endautoescape %}')470- assert t.render(ae=True) == '<strong>Wert: <test></strong>'471- assert t.render(ae=False) == '<strong>Wert: <test></strong>'490+ lambda x: u"<strong>Wert: %(name)s</strong>",491+ lambda s, p, n: s,492+ newstyle=True,493+ )494+ t = env.from_string(495+ '{% autoescape ae %}{{ gettext("foo", name='496+ '"<test>") }}{% endautoescape %}'497+ )498+ assert t.render(ae=True) == "<strong>Wert: <test></strong>"499+ assert t.render(ae=False) == "<strong>Wert: <test></strong>"500 501 def test_autoescape_macros(self):474- env = Environment(autoescape=False, extensions=['jinja2.ext.autoescape'])502+ env = Environment(autoescape=False, extensions=["jinja2.ext.autoescape"])503 template = (476- '{% macro m() %}<html>{% endmacro %}'477- '{% autoescape true %}{{ m() }}{% endautoescape %}'504+ "{% macro m() %}<html>{% endmacro %}"505+ "{% autoescape true %}{{ m() }}{% endautoescape %}"506 )479- assert env.from_string(template).render() == '<html>'507+ assert env.from_string(template).render() == "<html>"508 509 def test_num_used_twice(self):482- tmpl = newstyle_i18n_env.get_template('ngettext_long.html')483- assert tmpl.render(apples=5, LANGUAGE='de') == u'5 Äpfel'510+ tmpl = newstyle_i18n_env.get_template("ngettext_long.html")511+ assert tmpl.render(apples=5, LANGUAGE="de") == u"5 Äpfel"512 513 def test_num_called_num(self):486- source = newstyle_i18n_env.compile('''514+ source = newstyle_i18n_env.compile(515+ """516 {% trans num=3 %}{{ num }} apple{% pluralize517 %}{{ num }} apples{% endtrans %}489- ''', raw=True)518+ """,519+ raw=True,520+ )521 # quite hacky, but the only way to properly test that. The idea is522 # that the generated code does not pass num twice (although that523 # would work) for better performance. This only works on the524 # newstyle gettext of course494- assert re.search(r"u?'\%\(num\)s apple', u?'\%\(num\)s "495- r"apples', 3", source) is not None525+ assert (526+ re.search(r"u?'\%\(num\)s apple', u?'\%\(num\)s " r"apples', 3", source)527+ is not None528+ )529 530 def test_trans_vars(self):498- t1 = newstyle_i18n_env.get_template('transvars1.html')499- t2 = newstyle_i18n_env.get_template('transvars2.html')500- t3 = newstyle_i18n_env.get_template('transvars3.html')501- assert t1.render(num=1, LANGUAGE='de') == 'Benutzer: 1'502- assert t2.render(count=23, LANGUAGE='de') == 'Benutzer: 23'503- assert t3.render(num=42, LANGUAGE='de') == 'Benutzer: 42'531+ t1 = newstyle_i18n_env.get_template("transvars1.html")532+ t2 = newstyle_i18n_env.get_template("transvars2.html")533+ t3 = newstyle_i18n_env.get_template("transvars3.html")534+ assert t1.render(num=1, LANGUAGE="de") == "Benutzer: 1"535+ assert t2.render(count=23, LANGUAGE="de") == "Benutzer: 23"536+ assert t3.render(num=42, LANGUAGE="de") == "Benutzer: 42"537 538 def test_novars_vars_escaping(self):506- t = newstyle_i18n_env.get_template('novars.html')507- assert t.render() == '%(hello)s'508- t = newstyle_i18n_env.get_template('vars.html')509- assert t.render(foo='42') == '42%(foo)s'510- t = newstyle_i18n_env.get_template('explicitvars.html')511- assert t.render() == '%(foo)s'539+ t = newstyle_i18n_env.get_template("novars.html")540+ assert t.render() == "%(hello)s"541+ t = newstyle_i18n_env.get_template("vars.html")542+ assert t.render(foo="42") == "42%(foo)s"543+ t = newstyle_i18n_env.get_template("explicitvars.html")544+ assert t.render() == "%(foo)s"545 546 547 @pytest.mark.ext548 class TestAutoEscape(object):516-549 def test_scoped_setting(self):518- env = Environment(extensions=['jinja2.ext.autoescape'],519- autoescape=True)520- tmpl = env.from_string('''550+ env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)551+ tmpl = env.from_string(552+ """553 {{ "<HelloWorld>" }}554 {% autoescape false %}555 {{ "<HelloWorld>" }}556 {% endautoescape %}557 {{ "<HelloWorld>" }}526- ''')527- assert tmpl.render().split() == \528- [u'<HelloWorld>', u'<HelloWorld>', u'<HelloWorld>']558+ """559+ )560+ assert tmpl.render().split() == [561+ u"<HelloWorld>",562+ u"<HelloWorld>",563+ u"<HelloWorld>",564+ ]565 530- env = Environment(extensions=['jinja2.ext.autoescape'],531- autoescape=False)532- tmpl = env.from_string('''566+ env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=False)567+ tmpl = env.from_string(568+ """569 {{ "<HelloWorld>" }}570 {% autoescape true %}571 {{ "<HelloWorld>" }}572 {% endautoescape %}573 {{ "<HelloWorld>" }}538- ''')539- assert tmpl.render().split() == \540- [u'<HelloWorld>', u'<HelloWorld>', u'<HelloWorld>']574+ """575+ )576+ assert tmpl.render().split() == [577+ u"<HelloWorld>",578+ u"<HelloWorld>",579+ u"<HelloWorld>",580+ ]581 582 def test_nonvolatile(self):543- env = Environment(extensions=['jinja2.ext.autoescape'],544- autoescape=True)583+ env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)584 tmpl = env.from_string('{{ {"foo": "<test>"}|xmlattr|escape }}')585 assert tmpl.render() == ' foo="<test>"'547- tmpl = env.from_string('{% autoescape false %}{{ {"foo": "<test>"}'548- '|xmlattr|escape }}{% endautoescape %}')549- assert tmpl.render() == ' foo="&lt;test&gt;"'586+ tmpl = env.from_string(587+ '{% autoescape false %}{{ {"foo": "<test>"}'588+ "|xmlattr|escape }}{% endautoescape %}"589+ )590+ assert tmpl.render() == " foo="&lt;test&gt;""591 592 def test_volatile(self):552- env = Environment(extensions=['jinja2.ext.autoescape'],553- autoescape=True)554- tmpl = env.from_string('{% autoescape foo %}{{ {"foo": "<test>"}'555- '|xmlattr|escape }}{% endautoescape %}')556- assert tmpl.render(foo=False) == ' foo="&lt;test&gt;"'593+ env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)594+ tmpl = env.from_string(595+ '{% autoescape foo %}{{ {"foo": "<test>"}'596+ "|xmlattr|escape }}{% endautoescape %}"597+ )598+ assert tmpl.render(foo=False) == " foo="&lt;test&gt;""599 assert tmpl.render(foo=True) == ' foo="<test>"'600 601 def test_scoping(self):560- env = Environment(extensions=['jinja2.ext.autoescape'])602+ env = Environment(extensions=["jinja2.ext.autoescape"])603 tmpl = env.from_string(604 '{% autoescape true %}{% set x = "<x>" %}{{ x }}'563- '{% endautoescape %}{{ x }}{{ "<y>" }}')564- assert tmpl.render(x=1) == '<x>1<y>'605+ '{% endautoescape %}{{ x }}{{ "<y>" }}'606+ )607+ assert tmpl.render(x=1) == "<x>1<y>"608 609 def test_volatile_scoping(self):567- env = Environment(extensions=['jinja2.ext.autoescape'])568- tmplsource = '''610+ env = Environment(extensions=["jinja2.ext.autoescape"])611+ tmplsource = """612 {% autoescape val %}613 {% macro foo(x) %}614 [{{ x }}]615 {% endmacro %}616 {{ foo().__class__.__name__ }}617 {% endautoescape %}618 {{ '<testing>' }}576- '''619+ """620 tmpl = env.from_string(tmplsource)578- assert tmpl.render(val=True).split()[0] == 'Markup'621+ assert tmpl.render(val=True).split()[0] == "Markup"622 assert tmpl.render(val=False).split()[0] == text_type.__name__623 624 # looking at the source we should see <testing> there in raw625 # (and then escaped as well)583- env = Environment(extensions=['jinja2.ext.autoescape'])626+ env = Environment(extensions=["jinja2.ext.autoescape"])627 pysource = env.compile(tmplsource, raw=True)585- assert '<testing>\\n' in pysource628+ assert "<testing>\\n" in pysource629 587- env = Environment(extensions=['jinja2.ext.autoescape'],588- autoescape=True)630+ env = Environment(extensions=["jinja2.ext.autoescape"], autoescape=True)631 pysource = env.compile(tmplsource, raw=True)590- assert '<testing>\\n' in pysource632+ assert "<testing>\\n" in pysource633 634 def test_overlay_scopes(self):635 class MagicScopeExtension(Extension):594- tags = set(['overlay'])636+ tags = set(["overlay"])637+638 def parse(self, parser):639 node = nodes.OverlayScope(lineno=next(parser.stream).lineno)597- node.body = list(parser.parse_statements(('name:endoverlay',),598- drop_needle=True))599- node.context = self.call_method('get_scope')640+ node.body = list(641+ parser.parse_statements(("name:endoverlay",), drop_needle=True)642+ )643+ node.context = self.call_method("get_scope")644 return node645+646 def get_scope(self):602- return {'x': [1, 2, 3]}647+ return {"x": [1, 2, 3]}648 649 env = Environment(extensions=[MagicScopeExtension])650 606- tmpl = env.from_string('''651+ tmpl = env.from_string(652+ """653 {{- x }}|{% set z = 99 %}654 {%- overlay %}655 {{- y }}|{{ z }}|{% for item in x %}[{{ item }}]{% endfor %}656 {%- endoverlay %}|657 {{- x -}}612- ''')613- assert tmpl.render(x=42, y=23) == '42|23|99|[1][2][3]|42'658+ """659+ )660+ assert tmpl.render(x=42, y=23) == "42|23|99|[1][2][3]|42"modified:tests/test_features.py+15 added-13 removed
1 import sys2+3 import pytest4 4-from jinja2 import Template, Environment, contextfilter5+from jinja2 import contextfilter6+from jinja2 import Environment7+from jinja2 import Template8+from jinja2._compat import text_type9 10 7-@pytest.mark.skipif(sys.version_info < (3, 5),8- reason='Requires 3.5 or later')11+@pytest.mark.skipif(sys.version_info < (3, 5), reason="Requires 3.5 or later")12 def test_generator_stop():13 class X(object):14 def __getattr__(self, name):15 raise StopIteration()16 14- t = Template('a{{ bad.bar() }}b')17+ t = Template("a{{ bad.bar() }}b")18 with pytest.raises(RuntimeError):19 t.render(bad=X())20 21 19-@pytest.mark.skipif(sys.version_info[0] > 2,20- reason='Feature only supported on 2.x')22+@pytest.mark.skipif(sys.version_info[0] > 2, reason="Feature only supported on 2.x")23 def test_ascii_str():24 @contextfilter25 def assert_func(context, value):24- assert type(value) is context['expected_type']26+ assert type(value) is context["expected_type"]27 28 env = Environment()27- env.filters['assert'] = assert_func29+ env.filters["assert"] = assert_func30 29- env.policies['compiler.ascii_str'] = False31+ env.policies["compiler.ascii_str"] = False32 t = env.from_string('{{ "foo"|assert }}')31- t.render(expected_type=unicode)33+ t.render(expected_type=text_type)34 33- env.policies['compiler.ascii_str'] = True35+ env.policies["compiler.ascii_str"] = True36 t = env.from_string('{{ "foo"|assert }}')37 t.render(expected_type=str)38 39 for val in True, False:38- env.policies['compiler.ascii_str'] = val40+ env.policies["compiler.ascii_str"] = val41 t = env.from_string(u'{{ "\N{SNOWMAN}"|assert }}')40- t.render(expected_type=unicode)42+ t.render(expected_type=text_type)modified:tests/test_filters.py+316 added-341 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.filters4- ~~~~~~~~~~~~~~~~~~~~~~~~5-6- Tests for the jinja filters.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import random3+from collections import namedtuple4+5 import pytest13-from jinja2 import Markup, Environment14-from jinja2._compat import text_type, implements_to_string6 7+from jinja2 import Environment8+from jinja2 import Markup9+from jinja2._compat import implements_to_string10+from jinja2._compat import text_type11 12+13 @implements_to_string14 class Magic(object):15 def __init__(self, value):16 self.value = value8 unmodified lines25 self.value1 = value126 self.value2 = value227 28 def __str__(self):33- return u'(%s,%s)' % (text_type(self.value1), text_type(self.value2))29+ return u"(%s,%s)" % (text_type(self.value1), text_type(self.value2))30 31 32 @pytest.mark.filter33 class TestFilter(object):38-34 def test_filter_calling(self, env):40- rv = env.call_filter('sum', [1, 2, 3])35+ rv = env.call_filter("sum", [1, 2, 3])36 assert rv == 637 38 def test_capitalize(self, env):39 tmpl = env.from_string('{{ "foo bar"|capitalize }}')45- assert tmpl.render() == 'Foo bar'40+ assert tmpl.render() == "Foo bar"41 42 def test_center(self, env):43 tmpl = env.from_string('{{ "foo"|center(9) }}')49- assert tmpl.render() == ' foo '44+ assert tmpl.render() == " foo "45 46 def test_default(self, env):47 tmpl = env.from_string(48 "{{ missing|default('no') }}|{{ false|default('no') }}|"49 "{{ false|default('no', true) }}|{{ given|default('no') }}"50 )56- assert tmpl.render(given='yes') == 'no|False|no|yes'51+ assert tmpl.render(given="yes") == "no|False|no|yes"52 58- @pytest.mark.parametrize('args,expect', (59- ('', "[('aa', 0), ('AB', 3), ('b', 1), ('c', 2)]"),60- ('true', "[('AB', 3), ('aa', 0), ('b', 1), ('c', 2)]"),61- ('by="value"', "[('aa', 0), ('b', 1), ('c', 2), ('AB', 3)]"),62- ('reverse=true', "[('c', 2), ('b', 1), ('AB', 3), ('aa', 0)]")63- ))53+ @pytest.mark.parametrize(54+ "args,expect",55+ (56+ ("", "[('aa', 0), ('AB', 3), ('b', 1), ('c', 2)]"),57+ ("true", "[('AB', 3), ('aa', 0), ('b', 1), ('c', 2)]"),58+ ('by="value"', "[('aa', 0), ('b', 1), ('c', 2), ('AB', 3)]"),59+ ("reverse=true", "[('c', 2), ('b', 1), ('AB', 3), ('aa', 0)]"),60+ ),61+ )62 def test_dictsort(self, env, args, expect):65- t = env.from_string('{{{{ foo|dictsort({args}) }}}}'.format(args=args))63+ t = env.from_string("{{{{ foo|dictsort({args}) }}}}".format(args=args))64 out = t.render(foo={"aa": 0, "b": 1, "c": 2, "AB": 3})65 assert out == expect66 67 def test_batch(self, env):70- tmpl = env.from_string("{{ foo|batch(3)|list }}|"71- "{{ foo|batch(3, 'X')|list }}")68+ tmpl = env.from_string("{{ foo|batch(3)|list }}|{{ foo|batch(3, 'X')|list }}")69 out = tmpl.render(foo=list(range(10)))73- assert out == ("[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]|"74- "[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 'X', 'X']]")70+ assert out == (71+ "[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9]]|"72+ "[[0, 1, 2], [3, 4, 5], [6, 7, 8], [9, 'X', 'X']]"73+ )74 75 def test_slice(self, env):77- tmpl = env.from_string('{{ foo|slice(3)|list }}|'78- '{{ foo|slice(3, "X")|list }}')76+ tmpl = env.from_string("{{ foo|slice(3)|list }}|{{ foo|slice(3, 'X')|list }}")77 out = tmpl.render(foo=list(range(10)))80- assert out == ("[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"81- "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]")78+ assert out == (79+ "[[0, 1, 2, 3], [4, 5, 6], [7, 8, 9]]|"80+ "[[0, 1, 2, 3], [4, 5, 6, 'X'], [7, 8, 9, 'X']]"81+ )82 83 def test_escape(self, env):84- tmpl = env.from_string('''{{ '<">&'|escape }}''')84+ tmpl = env.from_string("""{{ '<">&'|escape }}""")85 out = tmpl.render()86- assert out == '<">&'86+ assert out == "<">&"87 88 @pytest.mark.parametrize(89 ("chars", "expect"), [(None, "..stays.."), (".", " ..stays"), (" .", "stays")]90 )2 unmodified lines93 out = tmpl.render(foo=" ..stays..", chars=chars)94 assert out == expect95 96 def test_striptags(self, env):97- tmpl = env.from_string('''{{ foo|striptags }}''')98- out = tmpl.render(foo=' <p>just a small \n <a href="#">'99- 'example</a> link</p>\n<p>to a webpage</p> '100- '<!-- <p>and some commented stuff</p> -->')101- assert out == 'just a small example link to a webpage'97+ tmpl = env.from_string("""{{ foo|striptags }}""")98+ out = tmpl.render(99+ foo=' <p>just a small \n <a href="#">'100+ "example</a> link</p>\n<p>to a webpage</p> "101+ "<!-- <p>and some commented stuff</p> -->"102+ )103+ assert out == "just a small example link to a webpage"104 105 def test_filesizeformat(self, env):106 tmpl = env.from_string(105- '{{ 100|filesizeformat }}|'106- '{{ 1000|filesizeformat }}|'107- '{{ 1000000|filesizeformat }}|'108- '{{ 1000000000|filesizeformat }}|'109- '{{ 1000000000000|filesizeformat }}|'110- '{{ 100|filesizeformat(true) }}|'111- '{{ 1000|filesizeformat(true) }}|'112- '{{ 1000000|filesizeformat(true) }}|'113- '{{ 1000000000|filesizeformat(true) }}|'114- '{{ 1000000000000|filesizeformat(true) }}'107+ "{{ 100|filesizeformat }}|"108+ "{{ 1000|filesizeformat }}|"109+ "{{ 1000000|filesizeformat }}|"110+ "{{ 1000000000|filesizeformat }}|"111+ "{{ 1000000000000|filesizeformat }}|"112+ "{{ 100|filesizeformat(true) }}|"113+ "{{ 1000|filesizeformat(true) }}|"114+ "{{ 1000000|filesizeformat(true) }}|"115+ "{{ 1000000000|filesizeformat(true) }}|"116+ "{{ 1000000000000|filesizeformat(true) }}"117 )118 out = tmpl.render()119 assert out == (118- '100 Bytes|1.0 kB|1.0 MB|1.0 GB|1.0 TB|100 Bytes|'119- '1000 Bytes|976.6 KiB|953.7 MiB|931.3 GiB'120+ "100 Bytes|1.0 kB|1.0 MB|1.0 GB|1.0 TB|100 Bytes|"121+ "1000 Bytes|976.6 KiB|953.7 MiB|931.3 GiB"122 )123 124 def test_filesizeformat_issue59(self, env):125 tmpl = env.from_string(124- '{{ 300|filesizeformat }}|'125- '{{ 3000|filesizeformat }}|'126- '{{ 3000000|filesizeformat }}|'127- '{{ 3000000000|filesizeformat }}|'128- '{{ 3000000000000|filesizeformat }}|'129- '{{ 300|filesizeformat(true) }}|'130- '{{ 3000|filesizeformat(true) }}|'131- '{{ 3000000|filesizeformat(true) }}'126+ "{{ 300|filesizeformat }}|"127+ "{{ 3000|filesizeformat }}|"128+ "{{ 3000000|filesizeformat }}|"129+ "{{ 3000000000|filesizeformat }}|"130+ "{{ 3000000000000|filesizeformat }}|"131+ "{{ 300|filesizeformat(true) }}|"132+ "{{ 3000|filesizeformat(true) }}|"133+ "{{ 3000000|filesizeformat(true) }}"134 )135 out = tmpl.render()136 assert out == (135- '300 Bytes|3.0 kB|3.0 MB|3.0 GB|3.0 TB|300 Bytes|'136- '2.9 KiB|2.9 MiB'137+ "300 Bytes|3.0 kB|3.0 MB|3.0 GB|3.0 TB|300 Bytes|2.9 KiB|2.9 MiB"138 )139 140 def test_first(self, env):140- tmpl = env.from_string('{{ foo|first }}')141+ tmpl = env.from_string("{{ foo|first }}")142 out = tmpl.render(foo=list(range(10)))142- assert out == '0'143+ assert out == "0"144 145 @pytest.mark.parametrize(146 ("value", "expect"), (("42", "42.0"), ("abc", "0.0"), ("32.32", "32.32"),)147 )5 unmodified lines153 t = env.from_string("{{ value|float(default=1.0) }}")154 assert t.render(value="abc") == "1.0"155 156 def test_format(self, env):156- tmpl = env.from_string('''{{ "%s|%s"|format("a", "b") }}''')157+ tmpl = env.from_string("""{{ "%s|%s"|format("a", "b") }}""")158 out = tmpl.render()158- assert out == 'a|b'159+ assert out == "a|b"160 161 @staticmethod162 def _test_indent_multiline_template(env, markup=False):162- text = '\n'.join(['', 'foo bar', '"baz"', ''])163+ text = "\n".join(["", "foo bar", '"baz"', ""])164 if markup:165 text = Markup(text)165- t = env.from_string('{{ foo|indent(2, false, false) }}')166+ t = env.from_string("{{ foo|indent(2, false, false) }}")167 assert t.render(foo=text) == '\n foo bar\n "baz"\n'167- t = env.from_string('{{ foo|indent(2, false, true) }}')168+ t = env.from_string("{{ foo|indent(2, false, true) }}")169 assert t.render(foo=text) == '\n foo bar\n "baz"\n '169- t = env.from_string('{{ foo|indent(2, true, false) }}')170+ t = env.from_string("{{ foo|indent(2, true, false) }}")171 assert t.render(foo=text) == ' \n foo bar\n "baz"\n'171- t = env.from_string('{{ foo|indent(2, true, true) }}')172+ t = env.from_string("{{ foo|indent(2, true, true) }}")173 assert t.render(foo=text) == ' \n foo bar\n "baz"\n '174 175 def test_indent(self, env):176 self._test_indent_multiline_template(env)177 t = env.from_string('{{ "jinja"|indent }}')177- assert t.render() == 'jinja'178+ assert t.render() == "jinja"179 t = env.from_string('{{ "jinja"|indent(first=true) }}')179- assert t.render() == ' jinja'180+ assert t.render() == " jinja"181 t = env.from_string('{{ "jinja"|indent(blank=true) }}')181- assert t.render() == 'jinja'182+ assert t.render() == "jinja"183 184 def test_indent_markup_input(self, env):184- '''185+ """186 Tests cases where the filter input is a Markup type186- '''187+ """188 self._test_indent_multiline_template(env, markup=True)189 189- def test_indentfirst_deprecated(self, env):190- with pytest.warns(DeprecationWarning):191- env.from_string('{{ "jinja"|indent(indentfirst=true) }}').render()192-190 @pytest.mark.parametrize(191 ("value", "expect"),192 (193 ("42", "42"),194 ("abc", "0"),195 ("32.32", "32"),196 ("12345678901234567890", "12345678901234567890"),200- )197+ ),198 )199 def test_int(self, env, value, expect):200 t = env.from_string("{{ '%s'|int }}" % value)201 assert t.render() == expect202 203 @pytest.mark.parametrize(204 ("value", "base", "expect"),208- (209- ("0x4d32", 16, "19762"),210- ("011", 8, "9"),211- ("0x33Z", 16, "0"),212- )205+ (("0x4d32", 16, "19762"), ("011", 8, "9"), ("0x33Z", 16, "0"),),206 )207 def test_int_base(self, env, value, base, expect):208 t = env.from_string("{{ '%s'|int(base=%d) }}" % (value, base))209 assert t.render() == expect12 unmodified lines222 223 def test_join(self, env):224 tmpl = env.from_string('{{ [1, 2, 3]|join("|") }}')225 out = tmpl.render()233- assert out == '1|2|3'226+ assert out == "1|2|3"227 228 env2 = Environment(autoescape=True)236- tmpl = env2.from_string(237- '{{ ["<foo>", "<span>foo</span>"|safe]|join }}')238- assert tmpl.render() == '<foo><span>foo</span>'229+ tmpl = env2.from_string('{{ ["<foo>", "<span>foo</span>"|safe]|join }}')230+ assert tmpl.render() == "<foo><span>foo</span>"231 232 def test_join_attribute(self, env):241- class User(object):242- def __init__(self, username):243- self.username = username244- tmpl = env.from_string('''{{ users|join(', ', 'username') }}''')245- assert tmpl.render(users=map(User, ['foo', 'bar'])) == 'foo, bar'233+ User = namedtuple("User", "username")234+ tmpl = env.from_string("""{{ users|join(', ', 'username') }}""")235+ assert tmpl.render(users=map(User, ["foo", "bar"])) == "foo, bar"236 237 def test_last(self, env):248- tmpl = env.from_string('''{{ foo|last }}''')238+ tmpl = env.from_string("""{{ foo|last }}""")239 out = tmpl.render(foo=list(range(10)))250- assert out == '9'240+ assert out == "9"241 242 def test_length(self, env):253- tmpl = env.from_string('''{{ "hello world"|length }}''')243+ tmpl = env.from_string("""{{ "hello world"|length }}""")244 out = tmpl.render()255- assert out == '11'245+ assert out == "11"246 247 def test_lower(self, env):258- tmpl = env.from_string('''{{ "FOO"|lower }}''')248+ tmpl = env.from_string("""{{ "FOO"|lower }}""")249 out = tmpl.render()260- assert out == 'foo'250+ assert out == "foo"251 252 def test_pprint(self, env):253 from pprint import pformat254+264- tmpl = env.from_string('''{{ data|pprint }}''')255+ tmpl = env.from_string("""{{ data|pprint }}""")256 data = list(range(1000))257 assert tmpl.render(data=data) == pformat(data)258 259 def test_random(self, env, request):260 # restore the random state when the test ends261 state = random.getstate()262 request.addfinalizer(lambda: random.setstate(state))263 # generate the random values from a known seed273- random.seed('jinja')274- expected = [random.choice('1234567890') for _ in range(10)]264+ random.seed("jinja")265+ expected = [random.choice("1234567890") for _ in range(10)]266 267 # check that the random sequence is generated again by a template268 # ensures that filter result is not constant folded278- random.seed('jinja')269+ random.seed("jinja")270 t = env.from_string('{{ "1234567890"|random }}')271 272 for value in expected:273 assert t.render() == value274 275 def test_reverse(self, env):285- tmpl = env.from_string('{{ "foobar"|reverse|join }}|'286- '{{ [1, 2, 3]|reverse|list }}')287- assert tmpl.render() == 'raboof|[3, 2, 1]'276+ tmpl = env.from_string(277+ "{{ 'foobar'|reverse|join }}|{{ [1, 2, 3]|reverse|list }}"278+ )279+ assert tmpl.render() == "raboof|[3, 2, 1]"280 281 def test_string(self, env):282 x = [1, 2, 3, 4, 5]291- tmpl = env.from_string('''{{ obj|string }}''')283+ tmpl = env.from_string("""{{ obj|string }}""")284 assert tmpl.render(obj=x) == text_type(x)285 286 def test_title(self, env):295- tmpl = env.from_string('''{{ "foo bar"|title }}''')287+ tmpl = env.from_string("""{{ "foo bar"|title }}""")288 assert tmpl.render() == "Foo Bar"297- tmpl = env.from_string('''{{ "foo's bar"|title }}''')289+ tmpl = env.from_string("""{{ "foo's bar"|title }}""")290 assert tmpl.render() == "Foo's Bar"299- tmpl = env.from_string('''{{ "foo bar"|title }}''')291+ tmpl = env.from_string("""{{ "foo bar"|title }}""")292 assert tmpl.render() == "Foo Bar"301- tmpl = env.from_string('''{{ "f bar f"|title }}''')293+ tmpl = env.from_string("""{{ "f bar f"|title }}""")294 assert tmpl.render() == "F Bar F"303- tmpl = env.from_string('''{{ "foo-bar"|title }}''')295+ tmpl = env.from_string("""{{ "foo-bar"|title }}""")296 assert tmpl.render() == "Foo-Bar"305- tmpl = env.from_string('''{{ "foo\tbar"|title }}''')297+ tmpl = env.from_string("""{{ "foo\tbar"|title }}""")298 assert tmpl.render() == "Foo\tBar"307- tmpl = env.from_string('''{{ "FOO\tBAR"|title }}''')299+ tmpl = env.from_string("""{{ "FOO\tBAR"|title }}""")300 assert tmpl.render() == "Foo\tBar"309- tmpl = env.from_string('''{{ "foo (bar)"|title }}''')301+ tmpl = env.from_string("""{{ "foo (bar)"|title }}""")302 assert tmpl.render() == "Foo (Bar)"311- tmpl = env.from_string('''{{ "foo {bar}"|title }}''')303+ tmpl = env.from_string("""{{ "foo {bar}"|title }}""")304 assert tmpl.render() == "Foo {Bar}"313- tmpl = env.from_string('''{{ "foo [bar]"|title }}''')305+ tmpl = env.from_string("""{{ "foo [bar]"|title }}""")306 assert tmpl.render() == "Foo [Bar]"315- tmpl = env.from_string('''{{ "foo <bar>"|title }}''')307+ tmpl = env.from_string("""{{ "foo <bar>"|title }}""")308 assert tmpl.render() == "Foo <Bar>"309 310 class Foo:311 def __str__(self):320- return 'foo-bar'312+ return "foo-bar"313 322- tmpl = env.from_string('''{{ data|title }}''')314+ tmpl = env.from_string("""{{ data|title }}""")315 out = tmpl.render(data=Foo())324- assert out == 'Foo-Bar'316+ assert out == "Foo-Bar"317 318 def test_truncate(self, env):319 tmpl = env.from_string(320 '{{ data|truncate(15, true, ">>>") }}|'321 '{{ data|truncate(15, false, ">>>") }}|'330- '{{ smalldata|truncate(15) }}'322+ "{{ smalldata|truncate(15) }}"323 )332- out = tmpl.render(data='foobar baz bar' * 1000,333- smalldata='foobar baz bar')334- msg = 'Current output: %s' % out335- assert out == 'foobar baz b>>>|foobar baz>>>|foobar baz bar', msg324+ 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", msg327 328 def test_truncate_very_short(self, env):329 tmpl = env.from_string(339- '{{ "foo bar baz"|truncate(9) }}|'340- '{{ "foo bar baz"|truncate(9, true) }}'330+ '{{ "foo bar baz"|truncate(9) }}|{{ "foo bar baz"|truncate(9, true) }}'331 )332 out = tmpl.render()343- assert out == 'foo bar baz|foo bar baz', out333+ assert out == "foo bar baz|foo bar baz", out334 335 def test_truncate_end_length(self, env):336 tmpl = env.from_string('{{ "Joel is a slug"|truncate(7, true) }}')337 out = tmpl.render()348- assert out == 'Joel...', 'Current output: %s' % out338+ assert out == "Joel...", "Current output: %s" % out339 340 def test_upper(self, env):341 tmpl = env.from_string('{{ "foo"|upper }}')352- assert tmpl.render() == 'FOO'342+ assert tmpl.render() == "FOO"343 344 def test_urlize(self, env):355- tmpl = env.from_string(356- '{{ "foo http://www.example.com/ bar"|urlize }}')345+ tmpl = env.from_string('{{ "foo http://www.example.com/ bar"|urlize }}')346 assert tmpl.render() == (347 'foo <a href="http://www.example.com/" rel="noopener">'359- 'http://www.example.com/</a> bar'348+ "http://www.example.com/</a> bar"349 )350 351 def test_urlize_rel_policy(self):352 env = Environment()364- env.policies['urlize.rel'] = None365- tmpl = env.from_string(366- '{{ "foo http://www.example.com/ bar"|urlize }}')353+ env.policies["urlize.rel"] = None354+ tmpl = env.from_string('{{ "foo http://www.example.com/ bar"|urlize }}')355 assert tmpl.render() == (368- 'foo <a href="http://www.example.com/">'369- 'http://www.example.com/</a> bar'356+ 'foo <a href="http://www.example.com/">http://www.example.com/</a> bar'357 )358 359 def test_urlize_target_parameter(self, env):360 tmpl = env.from_string(361 '{{ "foo http://www.example.com/ bar"|urlize(target="_blank") }}'362 )376- assert tmpl.render() \377- == 'foo <a href="http://www.example.com/" rel="noopener" target="_blank">'\378- 'http://www.example.com/</a> bar'363+ assert (364+ tmpl.render()365+ == 'foo <a href="http://www.example.com/" rel="noopener" target="_blank">'366+ "http://www.example.com/</a> bar"367+ )368 369 def test_wordcount(self, env):370 tmpl = env.from_string('{{ "foo bar baz"|wordcount }}')382- assert tmpl.render() == '3'371+ assert tmpl.render() == "3"372 373 def test_block(self, env):385- tmpl = env.from_string(386- '{% filter lower|escape %}<HEHE>{% endfilter %}'387- )388- assert tmpl.render() == '<hehe>'374+ tmpl = env.from_string("{% filter lower|escape %}<HEHE>{% endfilter %}")375+ assert tmpl.render() == "<hehe>"376 377 def test_chaining(self, env):391- tmpl = env.from_string(392- '''{{ ['<foo>', '<bar>']|first|upper|escape }}'''393- )394- assert tmpl.render() == '<FOO>'378+ tmpl = env.from_string("""{{ ['<foo>', '<bar>']|first|upper|escape }}""")379+ assert tmpl.render() == "<FOO>"380 381 def test_sum(self, env):397- tmpl = env.from_string('''{{ [1, 2, 3, 4, 5, 6]|sum }}''')398- assert tmpl.render() == '21'382+ tmpl = env.from_string("""{{ [1, 2, 3, 4, 5, 6]|sum }}""")383+ assert tmpl.render() == "21"384 385 def test_sum_attributes(self, env):401- tmpl = env.from_string('''{{ values|sum('value') }}''')402- assert tmpl.render(values=[403- {'value': 23},404- {'value': 1},405- {'value': 18},406- ]) == '42'386+ tmpl = env.from_string("""{{ values|sum('value') }}""")387+ assert tmpl.render(values=[{"value": 23}, {"value": 1}, {"value": 18}]) == "42"388 389 def test_sum_attributes_nested(self, env):409- tmpl = env.from_string('''{{ values|sum('real.value') }}''')410- assert tmpl.render(values=[411- {'real': {'value': 23}},412- {'real': {'value': 1}},413- {'real': {'value': 18}},414- ]) == '42'390+ tmpl = env.from_string("""{{ values|sum('real.value') }}""")391+ assert (392+ tmpl.render(393+ values=[394+ {"real": {"value": 23}},395+ {"real": {"value": 1}},396+ {"real": {"value": 18}},397+ ]398+ )399+ == "42"400+ )401 402 def test_sum_attributes_tuple(self, env):417- tmpl = env.from_string('''{{ values.items()|sum('1') }}''')418- assert tmpl.render(values={419- 'foo': 23,420- 'bar': 1,421- 'baz': 18,422- }) == '42'403+ tmpl = env.from_string("""{{ values.items()|sum('1') }}""")404+ assert tmpl.render(values={"foo": 23, "bar": 1, "baz": 18}) == "42"405 406 def test_abs(self, env):425- tmpl = env.from_string('''{{ -1|abs }}|{{ 1|abs }}''')426- assert tmpl.render() == '1|1', tmpl.render()407+ tmpl = env.from_string("""{{ -1|abs }}|{{ 1|abs }}""")408+ assert tmpl.render() == "1|1", tmpl.render()409 410 def test_round_positive(self, env):429- tmpl = env.from_string('{{ 2.7|round }}|{{ 2.1|round }}|'430- "{{ 2.1234|round(3, 'floor') }}|"431- "{{ 2.1|round(0, 'ceil') }}")432- assert tmpl.render() == '3.0|2.0|2.123|3.0', tmpl.render()411+ tmpl = env.from_string(412+ "{{ 2.7|round }}|{{ 2.1|round }}|"413+ "{{ 2.1234|round(3, 'floor') }}|"414+ "{{ 2.1|round(0, 'ceil') }}"415+ )416+ assert tmpl.render() == "3.0|2.0|2.123|3.0", tmpl.render()417 418 def test_round_negative(self, env):435- tmpl = env.from_string('{{ 21.3|round(-1)}}|'436- "{{ 21.3|round(-1, 'ceil')}}|"437- "{{ 21.3|round(-1, 'floor')}}")438- assert tmpl.render() == '20.0|30.0|20.0', tmpl.render()419+ tmpl = env.from_string(420+ "{{ 21.3|round(-1)}}|"421+ "{{ 21.3|round(-1, 'ceil')}}|"422+ "{{ 21.3|round(-1, 'floor')}}"423+ )424+ assert tmpl.render() == "20.0|30.0|20.0", tmpl.render()425 426 def test_xmlattr(self, env):427 tmpl = env.from_string(428 "{{ {'foo': 42, 'bar': 23, 'fish': none, "443- "'spam': missing, 'blub:blub': '<?>'}|xmlattr }}")429+ "'spam': missing, 'blub:blub': '<?>'}|xmlattr }}"430+ )431 out = tmpl.render().split()432 assert len(out) == 3433 assert 'foo="42"' in out434 assert 'bar="23"' in out435 assert 'blub:blub="<?>"' in out436 437 def test_sort1(self, env):451- tmpl = env.from_string(452- '{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}')453- assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'438+ tmpl = env.from_string("{{ [2, 3, 1]|sort }}|{{ [2, 3, 1]|sort(true) }}")439+ assert tmpl.render() == "[1, 2, 3]|[3, 2, 1]"440 441 def test_sort2(self, env):442 tmpl = env.from_string('{{ "".join(["c", "A", "b", "D"]|sort) }}')457- assert tmpl.render() == 'AbcD'443+ assert tmpl.render() == "AbcD"444 445 def test_sort3(self, env):460- tmpl = env.from_string('''{{ ['foo', 'Bar', 'blah']|sort }}''')446+ tmpl = env.from_string("""{{ ['foo', 'Bar', 'blah']|sort }}""")447 assert tmpl.render() == "['Bar', 'blah', 'foo']"448 449 def test_sort4(self, env):464- tmpl = env.from_string('''{{ items|sort(attribute='value')|join }}''')465- assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == '1234'450+ tmpl = env.from_string("""{{ items|sort(attribute='value')|join }}""")451+ assert tmpl.render(items=map(Magic, [3, 2, 4, 1])) == "1234"452 453 def test_sort5(self, env):468- tmpl = env.from_string('''{{ items|sort(attribute='value.0')|join }}''')469- assert tmpl.render(items=map(Magic, [[3], [2], [4], [1]])) == '[1][2][3][4]'454+ tmpl = env.from_string("""{{ items|sort(attribute='value.0')|join }}""")455+ assert tmpl.render(items=map(Magic, [[3], [2], [4], [1]])) == "[1][2][3][4]"456 457 def test_sort6(self, env):472- tmpl = env.from_string('''{{ items|sort(attribute='value1,value2')|join }}''')473- assert (tmpl.render(items=map(474- lambda x: Magic2(x[0], x[1]), [(3, 1), (2, 2), (2, 1), (2, 5)]))475- == '(2,1)(2,2)(2,5)(3,1)')458+ tmpl = env.from_string("""{{ items|sort(attribute='value1,value2')|join }}""")459+ assert (460+ tmpl.render(461+ items=map(462+ lambda x: Magic2(x[0], x[1]), [(3, 1), (2, 2), (2, 1), (2, 5)]463+ )464+ )465+ == "(2,1)(2,2)(2,5)(3,1)"466+ )467 468 def test_sort7(self, env):478- tmpl = env.from_string('''{{ items|sort(attribute='value2,value1')|join }}''')479- assert (tmpl.render(items=map(lambda x: Magic2(x[0], x[1]), [(3, 1), (2, 2), (2, 1), (2, 5)])) ==480- '(2,1)(3,1)(2,2)(2,5)')469+ tmpl = env.from_string("""{{ items|sort(attribute='value2,value1')|join }}""")470+ assert (471+ tmpl.render(472+ items=map(473+ lambda x: Magic2(x[0], x[1]), [(3, 1), (2, 2), (2, 1), (2, 5)]474+ )475+ )476+ == "(2,1)(3,1)(2,2)(2,5)"477+ )478 479 def test_sort8(self, env):480 tmpl = env.from_string(484- '''{{ items|sort(attribute='value1.0,value2.0')|join }}''')485- assert (tmpl.render(items=map(486- lambda x: Magic2(x[0], x[1]),487- [([3], [1]), ([2], [2]), ([2], [1]), ([2], [5])]))488- == '([2],[1])([2],[2])([2],[5])([3],[1])')481+ """{{ items|sort(attribute='value1.0,value2.0')|join }}"""482+ )483+ assert (484+ tmpl.render(485+ items=map(486+ lambda x: Magic2(x[0], x[1]),487+ [([3], [1]), ([2], [2]), ([2], [1]), ([2], [5])],488+ )489+ )490+ == "([2],[1])([2],[2])([2],[5])([3],[1])"491+ )492 493 def test_unique(self, env):494 t = env.from_string('{{ "".join(["b", "A", "a", "b"]|unique) }}')495 assert t.render() == "bA"3 unmodified lines499 assert t.render() == "bAa"500 501 def test_unique_attribute(self, env):502 t = env.from_string("{{ items|unique(attribute='value')|join }}")500- assert t.render(items=map(Magic, [3, 2, 4, 1, 2])) == '3241'503+ assert t.render(items=map(Magic, [3, 2, 4, 1, 2])) == "3241"504 502- @pytest.mark.parametrize('source,expect', (503- ('{{ ["a", "B"]|min }}', 'a'),504- ('{{ ["a", "B"]|min(case_sensitive=true) }}', 'B'),505- ('{{ []|min }}', ''),506- ('{{ ["a", "B"]|max }}', 'B'),507- ('{{ ["a", "B"]|max(case_sensitive=true) }}', 'a'),508- ('{{ []|max }}', ''),509- ))505+ @pytest.mark.parametrize(506+ "source,expect",507+ (508+ ('{{ ["a", "B"]|min }}', "a"),509+ ('{{ ["a", "B"]|min(case_sensitive=true) }}', "B"),510+ ("{{ []|min }}", ""),511+ ('{{ ["a", "B"]|max }}', "B"),512+ ('{{ ["a", "B"]|max(case_sensitive=true) }}', "a"),513+ ("{{ []|max }}", ""),514+ ),515+ )516 def test_min_max(self, env, source, expect):517 t = env.from_string(source)518 assert t.render() == expect519 514- @pytest.mark.parametrize('name,expect', (515- ('min', '1'),516- ('max', '9'),517- ))520+ @pytest.mark.parametrize("name,expect", (("min", "1"), ("max", "9"),))521 def test_min_max_attribute(self, env, name, expect):519- t = env.from_string('{{ items|' + name + '(attribute="value") }}')522+ t = env.from_string("{{ items|" + name + '(attribute="value") }}')523 assert t.render(items=map(Magic, [5, 1, 9])) == expect524 525 def test_groupby(self, env):523- tmpl = env.from_string('''526+ tmpl = env.from_string(527+ """528 {%- for grouper, list in [{'foo': 1, 'bar': 2},529 {'foo': 2, 'bar': 3},530 {'foo': 1, 'bar': 1},531 {'foo': 3, 'bar': 4}]|groupby('foo') -%}532 {{ grouper }}{% for x in list %}: {{ x.foo }}, {{ x.bar }}{% endfor %}|529- {%- endfor %}''')530- assert tmpl.render().split('|') == [531- "1: 1, 2: 1, 1",532- "2: 2, 3",533- "3: 3, 4",534- ""535- ]533+ {%- endfor %}"""534+ )535+ assert tmpl.render().split("|") == ["1: 1, 2: 1, 1", "2: 2, 3", "3: 3, 4", ""]536 537 def test_groupby_tuple_index(self, env):538- tmpl = env.from_string('''538+ tmpl = env.from_string(539+ """540 {%- for grouper, list in [('a', 1), ('a', 2), ('b', 1)]|groupby(0) -%}541 {{ grouper }}{% for x in list %}:{{ x.1 }}{% endfor %}|541- {%- endfor %}''')542- assert tmpl.render() == 'a:1:2|b:1|'542+ {%- endfor %}"""543+ )544+ assert tmpl.render() == "a:1:2|b:1|"545 546 def test_groupby_multidot(self, env):545- class Date(object):546- def __init__(self, day, month, year):547- self.day = day548- self.month = month549- self.year = year550-551- class Article(object):552- def __init__(self, title, *date):553- self.date = Date(*date)554- self.title = title547+ Date = namedtuple("Date", "day,month,year")548+ Article = namedtuple("Article", "title,date")549 articles = [556- Article('aha', 1, 1, 1970),557- Article('interesting', 2, 1, 1970),558- Article('really?', 3, 1, 1970),559- Article('totally not', 1, 1, 1971)550+ Article("aha", Date(1, 1, 1970)),551+ Article("interesting", Date(2, 1, 1970)),552+ Article("really?", Date(3, 1, 1970)),553+ Article("totally not", Date(1, 1, 1971)),554 ]561- tmpl = env.from_string('''555+ tmpl = env.from_string(556+ """557 {%- for year, list in articles|groupby('date.year') -%}558 {{ year }}{% for x in list %}[{{ x.title }}]{% endfor %}|564- {%- endfor %}''')565- assert tmpl.render(articles=articles).split('|') == [566- '1970[aha][interesting][really?]',567- '1971[totally not]',568- ''559+ {%- endfor %}"""560+ )561+ assert tmpl.render(articles=articles).split("|") == [562+ "1970[aha][interesting][really?]",563+ "1971[totally not]",564+ "",565 ]566 567 def test_filtertag(self, env):572- tmpl = env.from_string("{% filter upper|replace('FOO', 'foo') %}"573- "foobar{% endfilter %}")574- assert tmpl.render() == 'fooBAR'568+ tmpl = env.from_string(569+ "{% filter upper|replace('FOO', 'foo') %}foobar{% endfilter %}"570+ )571+ assert tmpl.render() == "fooBAR"572 573 def test_replace(self, env):574 env = Environment()575 tmpl = env.from_string('{{ string|replace("o", 42) }}')579- assert tmpl.render(string='<foo>') == '<f4242>'576+ assert tmpl.render(string="<foo>") == "<f4242>"577 env = Environment(autoescape=True)578 tmpl = env.from_string('{{ string|replace("o", 42) }}')582- assert tmpl.render(string='<foo>') == '<f4242>'579+ assert tmpl.render(string="<foo>") == "<f4242>"580 tmpl = env.from_string('{{ string|replace("<", 42) }}')584- assert tmpl.render(string='<foo>') == '42foo>'581+ assert tmpl.render(string="<foo>") == "42foo>"582 tmpl = env.from_string('{{ string|replace("o", ">x<") }}')586- assert tmpl.render(string=Markup('foo')) == 'f>x<>x<'583+ assert tmpl.render(string=Markup("foo")) == "f>x<>x<"584 585 def test_forceescape(self, env):589- tmpl = env.from_string('{{ x|forceescape }}')590- assert tmpl.render(x=Markup('<div />')) == u'<div />'586+ tmpl = env.from_string("{{ x|forceescape }}")587+ assert tmpl.render(x=Markup("<div />")) == u"<div />"588 589 def test_safe(self, env):590 env = Environment(autoescape=True)591 tmpl = env.from_string('{{ "<div>foo</div>"|safe }}')595- assert tmpl.render() == '<div>foo</div>'592+ assert tmpl.render() == "<div>foo</div>"593 tmpl = env.from_string('{{ "<div>foo</div>" }}')597- assert tmpl.render() == '<div>foo</div>'594+ assert tmpl.render() == "<div>foo</div>"595 596 @pytest.mark.parametrize(597 ("value", "expect"),598 [599 ("Hello, world!", "Hello%2C%20world%21"),600 (u"Hello, world\u203d", "Hello%2C%20world%E2%80%BD"),601 ({"f": 1}, "f=1"),605- ([('f', 1), ("z", 2)], "f=1&z=2"),602+ ([("f", 1), ("z", 2)], "f=1&z=2"),603 ({u"\u203d": 1}, "%E2%80%BD=1"),604 ({0: 1}, "0=1"),605 ([("a b/c", "a b/c")], "a+b%2Fc=a+b%2Fc"),609- ("a b/c", "a%20b/c")606+ ("a b/c", "a%20b/c"),607 ],608 )609 def test_urlencode(self, value, expect):610 e = Environment(autoescape=True)2 unmodified lines613 614 def test_simple_map(self, env):615 env = Environment()616 tmpl = env.from_string('{{ ["1", "2", "3"]|map("int")|sum }}')620- assert tmpl.render() == '6'617+ assert tmpl.render() == "6"618 619 def test_map_sum(self, env):620 tmpl = env.from_string('{{ [[1,2], [3], [4,5,6]]|map("sum")|list }}')624- assert tmpl.render() == '[3, 3, 15]'621+ assert tmpl.render() == "[3, 3, 15]"622 623 def test_attribute_map(self, env):627- class User(object):628- def __init__(self, name):629- self.name = name624+ User = namedtuple("User", "name")625 env = Environment()626 users = [632- User('john'),633- User('jane'),634- User('mike'),627+ User("john"),628+ User("jane"),629+ User("mike"),630 ]631 tmpl = env.from_string('{{ users|map(attribute="name")|join("|") }}')637- assert tmpl.render(users=users) == 'john|jane|mike'632+ assert tmpl.render(users=users) == "john|jane|mike"633 634 def test_empty_map(self, env):635 env = Environment()636 tmpl = env.from_string('{{ none|map("upper")|list }}')642- assert tmpl.render() == '[]'637+ assert tmpl.render() == "[]"638 639 def test_map_default(self, env):645- class Fullname(object):646- def __init__(self, firstname, lastname):647- self.firstname = firstname648- self.lastname = lastname649-650- class Firstname(object):651- def __init__(self, firstname):652- self.firstname = firstname653-640+ Fullname = namedtuple("Fullname", "firstname,lastname")641+ Firstname = namedtuple("Firstname", "firstname")642 env = Environment()643 tmpl = env.from_string(644 '{{ users|map(attribute="lastname", default="smith")|join(", ") }}'645 )646 users = [647 Fullname("john", "lennon"),648 Fullname("jane", "edwards"),649 Fullname("jon", None),662- Firstname("mike")650+ Firstname("mike"),651 ]652 assert tmpl.render(users=users) == "lennon, edwards, None, smith"653 654 def test_simple_select(self, env):655 env = Environment()656 tmpl = env.from_string('{{ [1, 2, 3, 4, 5]|select("odd")|join("|") }}')669- assert tmpl.render() == '1|3|5'657+ assert tmpl.render() == "1|3|5"658 659 def test_bool_select(self, env):660 env = Environment()673- tmpl = env.from_string(674- '{{ [none, false, 0, 1, 2, 3, 4, 5]|select|join("|") }}'675- )676- assert tmpl.render() == '1|2|3|4|5'661+ tmpl = env.from_string('{{ [none, false, 0, 1, 2, 3, 4, 5]|select|join("|") }}')662+ assert tmpl.render() == "1|2|3|4|5"663 664 def test_simple_reject(self, env):665 env = Environment()666 tmpl = env.from_string('{{ [1, 2, 3, 4, 5]|reject("odd")|join("|") }}')681- assert tmpl.render() == '2|4'667+ assert tmpl.render() == "2|4"668 669 def test_bool_reject(self, env):670 env = Environment()685- tmpl = env.from_string(686- '{{ [none, false, 0, 1, 2, 3, 4, 5]|reject|join("|") }}'687- )688- assert tmpl.render() == 'None|False|0'671+ tmpl = env.from_string('{{ [none, false, 0, 1, 2, 3, 4, 5]|reject|join("|") }}')672+ assert tmpl.render() == "None|False|0"673 674 def test_simple_select_attr(self, env):691- class User(object):692- def __init__(self, name, is_active):693- self.name = name694- self.is_active = is_active675+ User = namedtuple("User", "name,is_active")676 env = Environment()677 users = [697- User('john', True),698- User('jane', True),699- User('mike', False),678+ User("john", True),679+ User("jane", True),680+ User("mike", False),681 ]682 tmpl = env.from_string(702- '{{ users|selectattr("is_active")|'703- 'map(attribute="name")|join("|") }}'683+ '{{ users|selectattr("is_active")|map(attribute="name")|join("|") }}'684 )705- assert tmpl.render(users=users) == 'john|jane'685+ assert tmpl.render(users=users) == "john|jane"686 687 def test_simple_reject_attr(self, env):708- class User(object):709- def __init__(self, name, is_active):710- self.name = name711- self.is_active = is_active688+ User = namedtuple("User", "name,is_active")689 env = Environment()690 users = [714- User('john', True),715- User('jane', True),716- User('mike', False),691+ User("john", True),692+ User("jane", True),693+ User("mike", False),694 ]718- tmpl = env.from_string('{{ users|rejectattr("is_active")|'719- 'map(attribute="name")|join("|") }}')720- assert tmpl.render(users=users) == 'mike'695+ tmpl = env.from_string(696+ '{{ users|rejectattr("is_active")|map(attribute="name")|join("|") }}'697+ )698+ assert tmpl.render(users=users) == "mike"699 700 def test_func_select_attr(self, env):723- class User(object):724- def __init__(self, id, name):725- self.id = id726- self.name = name701+ User = namedtuple("User", "id,name")702 env = Environment()703 users = [729- User(1, 'john'),730- User(2, 'jane'),731- User(3, 'mike'),704+ User(1, "john"),705+ User(2, "jane"),706+ User(3, "mike"),707 ]733- tmpl = env.from_string('{{ users|selectattr("id", "odd")|'734- 'map(attribute="name")|join("|") }}')735- assert tmpl.render(users=users) == 'john|mike'708+ tmpl = env.from_string(709+ '{{ users|selectattr("id", "odd")|map(attribute="name")|join("|") }}'710+ )711+ assert tmpl.render(users=users) == "john|mike"712 713 def test_func_reject_attr(self, env):738- class User(object):739- def __init__(self, id, name):740- self.id = id741- self.name = name714+ User = namedtuple("User", "id,name")715 env = Environment()716 users = [744- User(1, 'john'),745- User(2, 'jane'),746- User(3, 'mike'),717+ User(1, "john"),718+ User(2, "jane"),719+ User(3, "mike"),720 ]748- tmpl = env.from_string('{{ users|rejectattr("id", "odd")|'749- 'map(attribute="name")|join("|") }}')750- assert tmpl.render(users=users) == 'jane'721+ tmpl = env.from_string(722+ '{{ users|rejectattr("id", "odd")|map(attribute="name")|join("|") }}'723+ )724+ assert tmpl.render(users=users) == "jane"725 726 def test_json_dump(self):727 env = Environment(autoescape=True)754- t = env.from_string('{{ x|tojson }}')755- assert t.render(x={'foo': 'bar'}) == '{"foo": "bar"}'756- assert t.render(x='"ba&r\'') == r'"\"ba\u0026r\u0027"'757- assert t.render(x='<bar>') == r'"\u003cbar\u003e"'728+ t = env.from_string("{{ x|tojson }}")729+ assert t.render(x={"foo": "bar"}) == '{"foo": "bar"}'730+ assert t.render(x="\"ba&r'") == r'"\"ba\u0026r\u0027"'731+ assert t.render(x="<bar>") == r'"\u003cbar\u003e"'732 733 def my_dumps(value, **options):760- assert options == {'foo': 'bar'}761- return '42'762- env.policies['json.dumps_function'] = my_dumps763- env.policies['json.dumps_kwargs'] = {'foo': 'bar'}764- assert t.render(x=23) == '42'734+ assert options == {"foo": "bar"}735+ return "42"736 737+ env.policies["json.dumps_function"] = my_dumps738+ env.policies["json.dumps_kwargs"] = {"foo": "bar"}739+ assert t.render(x=23) == "42"740+741 def test_wordwrap(self, env):742 env.newline_sequence = "\n"743 t = env.from_string("{{ s|wordwrap(20) }}")744 result = t.render(s="Hello!\nThis is Jinja saying something.")1 unmodified linemodified:tests/test_idtracking.py+205 added-132 removed
2 unmodified lines3 4 5 def test_basics():6 for_loop = nodes.For(7- nodes.Name('foo', 'store'),8- nodes.Name('seq', 'load'),9- [nodes.Output([nodes.Name('foo', 'load')])],10- [], None, False)11- tmpl = nodes.Template([12- nodes.Assign(13- nodes.Name('foo', 'store'),14- nodes.Name('bar', 'load')),15- for_loop])7+ nodes.Name("foo", "store"),8+ nodes.Name("seq", "load"),9+ [nodes.Output([nodes.Name("foo", "load")])],10+ [],11+ None,12+ False,13+ )14+ tmpl = nodes.Template(15+ [nodes.Assign(nodes.Name("foo", "store"), nodes.Name("bar", "load")), for_loop]16+ )17 18 sym = symbols_for_node(tmpl)19 assert sym.refs == {19- 'foo': 'l_0_foo',20- 'bar': 'l_0_bar',21- 'seq': 'l_0_seq',20+ "foo": "l_0_foo",21+ "bar": "l_0_bar",22+ "seq": "l_0_seq",23 }24 assert sym.loads == {24- 'l_0_foo': ('undefined', None),25- 'l_0_bar': ('resolve', 'bar'),26- 'l_0_seq': ('resolve', 'seq'),25+ "l_0_foo": ("undefined", None),26+ "l_0_bar": ("resolve", "bar"),27+ "l_0_seq": ("resolve", "seq"),28 }29 30 sym = symbols_for_node(for_loop, sym)31 assert sym.refs == {31- 'foo': 'l_1_foo',32+ "foo": "l_1_foo",33 }34 assert sym.loads == {34- 'l_1_foo': ('param', None),35+ "l_1_foo": ("param", None),36 }37 38 39 def test_complex():39- title_block = nodes.Block('title', [40- nodes.Output([nodes.TemplateData(u'Page Title')])41- ], False)40+ title_block = nodes.Block(41+ "title", [nodes.Output([nodes.TemplateData(u"Page Title")])], False42+ )43 43- render_title_macro = nodes.Macro('render_title', [nodes.Name('title', 'param')], [], [44- nodes.Output([45- nodes.TemplateData(u'\n <div class="title">\n <h1>'),46- nodes.Name('title', 'load'),47- nodes.TemplateData(u'</h1>\n <p>'),48- nodes.Name('subtitle', 'load'),49- nodes.TemplateData(u'</p>\n ')]),50- nodes.Assign(51- nodes.Name('subtitle', 'store'), nodes.Const('something else')),52- nodes.Output([53- nodes.TemplateData(u'\n <p>'),54- nodes.Name('subtitle', 'load'),55- nodes.TemplateData(u'</p>\n </div>\n'),56- nodes.If(57- nodes.Name('something', 'load'), [58- nodes.Assign(nodes.Name('title_upper', 'store'),59- nodes.Filter(nodes.Name('title', 'load'),60- 'upper', [], [], None, None)),61- nodes.Output([62- nodes.Name('title_upper', 'load'),63- nodes.Call(nodes.Name('render_title', 'load'), [64- nodes.Const('Aha')], [], None, None)])], [], [])])])44+ render_title_macro = nodes.Macro(45+ "render_title",46+ [nodes.Name("title", "param")],47+ [],48+ [49+ nodes.Output(50+ [51+ nodes.TemplateData(u'\n <div class="title">\n <h1>'),52+ nodes.Name("title", "load"),53+ nodes.TemplateData(u"</h1>\n <p>"),54+ nodes.Name("subtitle", "load"),55+ nodes.TemplateData(u"</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>"),64+ nodes.Name("subtitle", "load"),65+ nodes.TemplateData(u"</p>\n </div>\n"),66+ nodes.If(67+ nodes.Name("something", "load"),68+ [69+ nodes.Assign(70+ nodes.Name("title_upper", "store"),71+ nodes.Filter(72+ nodes.Name("title", "load"),73+ "upper",74+ [],75+ [],76+ None,77+ None,78+ ),79+ ),80+ nodes.Output(81+ [82+ nodes.Name("title_upper", "load"),83+ nodes.Call(84+ nodes.Name("render_title", "load"),85+ [nodes.Const("Aha")],86+ [],87+ None,88+ None,89+ ),90+ ]91+ ),92+ ],93+ [],94+ [],95+ ),96+ ]97+ ),98+ ],99+ )100 101 for_loop = nodes.For(67- nodes.Name('item', 'store'),68- nodes.Name('seq', 'load'), [69- nodes.Output([70- nodes.TemplateData(u'\n <li>'),71- nodes.Name('item', 'load'),72- nodes.TemplateData(u'</li>\n <span>')]),73- nodes.Include(nodes.Const('helper.html'), True, False),74- nodes.Output([75- nodes.TemplateData(u'</span>\n ')])], [], None, False)102+ nodes.Name("item", "store"),103+ nodes.Name("seq", "load"),104+ [105+ nodes.Output(106+ [107+ nodes.TemplateData(u"\n <li>"),108+ nodes.Name("item", "load"),109+ nodes.TemplateData(u"</li>\n <span>"),110+ ]111+ ),112+ nodes.Include(nodes.Const("helper.html"), True, False),113+ nodes.Output([nodes.TemplateData(u"</span>\n ")]),114+ ],115+ [],116+ None,117+ False,118+ )119 77- body_block = nodes.Block('body', [78- nodes.Output([79- nodes.TemplateData(u'\n '),80- nodes.Call(nodes.Name('render_title', 'load'), [81- nodes.Name('item', 'load')], [], None, None),82- nodes.TemplateData(u'\n <ul>\n ')]),83- for_loop,84- nodes.Output([nodes.TemplateData(u'\n </ul>\n')])],85- False)120+ body_block = nodes.Block(121+ "body",122+ [123+ nodes.Output(124+ [125+ nodes.TemplateData(u"\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 "),134+ ]135+ ),136+ for_loop,137+ nodes.Output([nodes.TemplateData(u"\n </ul>\n")]),138+ ],139+ False,140+ )141 142+ tmpl = nodes.Template(87- tmpl = nodes.Template([88- nodes.Extends(nodes.Const('layout.html')),89- title_block,90- render_title_macro,91- body_block,92- ])143+ [144+ nodes.Extends(nodes.Const("layout.html")),145+ title_block,146+ render_title_macro,147+ body_block,148+ ]149+ )150 151 tmpl_sym = symbols_for_node(tmpl)152 assert tmpl_sym.refs == {96- 'render_title': 'l_0_render_title',153+ "render_title": "l_0_render_title",154 }155 assert tmpl_sym.loads == {99- 'l_0_render_title': ('undefined', None),156+ "l_0_render_title": ("undefined", None),157 }101- assert tmpl_sym.stores == set(['render_title'])158+ assert tmpl_sym.stores == set(["render_title"])159 assert tmpl_sym.dump_stores() == {103- 'render_title': 'l_0_render_title',160+ "render_title": "l_0_render_title",161 }162 163 macro_sym = symbols_for_node(render_title_macro, tmpl_sym)164 assert macro_sym.refs == {108- 'subtitle': 'l_1_subtitle',109- 'something': 'l_1_something',110- 'title': 'l_1_title',111- 'title_upper': 'l_1_title_upper',165+ "subtitle": "l_1_subtitle",166+ "something": "l_1_something",167+ "title": "l_1_title",168+ "title_upper": "l_1_title_upper",169 }170 assert macro_sym.loads == {114- 'l_1_subtitle': ('resolve', 'subtitle'),115- 'l_1_something': ('resolve','something'),116- 'l_1_title': ('param', None),117- 'l_1_title_upper': ('resolve', 'title_upper'),171+ "l_1_subtitle": ("resolve", "subtitle"),172+ "l_1_something": ("resolve", "something"),173+ "l_1_title": ("param", None),174+ "l_1_title_upper": ("resolve", "title_upper"),175 }119- assert macro_sym.stores == set(['title', 'title_upper', 'subtitle'])120- assert macro_sym.find_ref('render_title') == 'l_0_render_title'176+ assert macro_sym.stores == set(["title", "title_upper", "subtitle"])177+ assert macro_sym.find_ref("render_title") == "l_0_render_title"178 assert macro_sym.dump_stores() == {122- 'title': 'l_1_title',123- 'title_upper': 'l_1_title_upper',124- 'subtitle': 'l_1_subtitle',125- 'render_title': 'l_0_render_title',179+ "title": "l_1_title",180+ "title_upper": "l_1_title_upper",181+ "subtitle": "l_1_subtitle",182+ "render_title": "l_0_render_title",183 }184 185 body_sym = symbols_for_node(body_block)186 assert body_sym.refs == {130- 'item': 'l_0_item',131- 'seq': 'l_0_seq',132- 'render_title': 'l_0_render_title',187+ "item": "l_0_item",188+ "seq": "l_0_seq",189+ "render_title": "l_0_render_title",190 }191 assert body_sym.loads == {135- 'l_0_item': ('resolve', 'item'),136- 'l_0_seq': ('resolve', 'seq'),137- 'l_0_render_title': ('resolve', 'render_title'),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([])197 198 for_sym = symbols_for_node(for_loop, body_sym)199 assert for_sym.refs == {143- 'item': 'l_1_item',200+ "item": "l_1_item",201 }202 assert for_sym.loads == {146- 'l_1_item': ('param', None),203+ "l_1_item": ("param", None),204 }148- assert for_sym.stores == set(['item'])205+ assert for_sym.stores == set(["item"])206 assert for_sym.dump_stores() == {150- 'item': 'l_1_item',207+ "item": "l_1_item",208 }209 210 211 def test_if_branching_stores():155- tmpl = nodes.Template([156- nodes.If(nodes.Name('expression', 'load'), [157- nodes.Assign(nodes.Name('variable', 'store'),158- nodes.Const(42))], [], [])])212+ tmpl = nodes.Template(213+ [214+ nodes.If(215+ nodes.Name("expression", "load"),216+ [nodes.Assign(nodes.Name("variable", "store"), nodes.Const(42))],217+ [],218+ [],219+ )220+ ]221+ )222 223 sym = symbols_for_node(tmpl)161- assert sym.refs == {162- 'variable': 'l_0_variable',163- 'expression': 'l_0_expression'164- }165- assert sym.stores == set(['variable'])224+ assert sym.refs == {"variable": "l_0_variable", "expression": "l_0_expression"}225+ assert sym.stores == set(["variable"])226 assert sym.loads == {167- 'l_0_variable': ('resolve', 'variable'),168- 'l_0_expression': ('resolve', 'expression')227+ "l_0_variable": ("resolve", "variable"),228+ "l_0_expression": ("resolve", "expression"),229 }230 assert sym.dump_stores() == {171- 'variable': 'l_0_variable',231+ "variable": "l_0_variable",232 }233 234 235 def test_if_branching_stores_undefined():176- tmpl = nodes.Template([177- nodes.Assign(nodes.Name('variable', 'store'), nodes.Const(23)),178- nodes.If(nodes.Name('expression', 'load'), [179- nodes.Assign(nodes.Name('variable', 'store'),180- nodes.Const(42))], [], [])])236+ tmpl = nodes.Template(237+ [238+ nodes.Assign(nodes.Name("variable", "store"), nodes.Const(23)),239+ nodes.If(240+ nodes.Name("expression", "load"),241+ [nodes.Assign(nodes.Name("variable", "store"), nodes.Const(42))],242+ [],243+ [],244+ ),245+ ]246+ )247 248 sym = symbols_for_node(tmpl)183- assert sym.refs == {184- 'variable': 'l_0_variable',185- 'expression': 'l_0_expression'186- }187- assert sym.stores == set(['variable'])249+ assert sym.refs == {"variable": "l_0_variable", "expression": "l_0_expression"}250+ assert sym.stores == set(["variable"])251 assert sym.loads == {189- 'l_0_variable': ('undefined', None),190- 'l_0_expression': ('resolve', 'expression')252+ "l_0_variable": ("undefined", None),253+ "l_0_expression": ("resolve", "expression"),254 }255 assert sym.dump_stores() == {193- 'variable': 'l_0_variable',256+ "variable": "l_0_variable",257 }258 259 260 def test_if_branching_multi_scope():198- for_loop = nodes.For(nodes.Name('item', 'store'), nodes.Name('seq', 'load'), [199- nodes.If(nodes.Name('expression', 'load'), [200- nodes.Assign(nodes.Name('x', 'store'), nodes.Const(42))], [], []),201- nodes.Include(nodes.Const('helper.html'), True, False)202- ], [], None, False)261+ for_loop = nodes.For(262+ nodes.Name("item", "store"),263+ nodes.Name("seq", "load"),264+ [265+ nodes.If(266+ nodes.Name("expression", "load"),267+ [nodes.Assign(nodes.Name("x", "store"), nodes.Const(42))],268+ [],269+ [],270+ ),271+ nodes.Include(nodes.Const("helper.html"), True, False),272+ ],273+ [],274+ None,275+ False,276+ )277 204- tmpl = nodes.Template([205- nodes.Assign(nodes.Name('x', 'store'), nodes.Const(23)),206- for_loop207- ])278+ tmpl = nodes.Template(279+ [nodes.Assign(nodes.Name("x", "store"), nodes.Const(23)), for_loop]280+ )281 282 tmpl_sym = symbols_for_node(tmpl)283 for_sym = symbols_for_node(for_loop, tmpl_sym)211- assert for_sym.stores == set(['item', 'x'])284+ assert for_sym.stores == set(["item", "x"])285 assert for_sym.loads == {213- 'l_1_x': ('alias', 'l_0_x'),214- 'l_1_item': ('param', None),215- 'l_1_expression': ('resolve', 'expression'),286+ "l_1_x": ("alias", "l_0_x"),287+ "l_1_item": ("param", None),288+ "l_1_expression": ("resolve", "expression"),289 }modified:tests/test_imports.py+70 added-67 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.imports4- ~~~~~~~~~~~~~~~~~~~~~~~~5-6- Tests the import features (with includes).7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import pytest3 13-from jinja2 import Environment, DictLoader14-from jinja2.exceptions import TemplateNotFound, TemplatesNotFound, \15- TemplateSyntaxError4+from jinja2 import DictLoader5+from jinja2 import Environment6+from jinja2.exceptions import TemplateNotFound7+from jinja2.exceptions import TemplatesNotFound8+from jinja2.exceptions import TemplateSyntaxError9 10 11 @pytest.fixture12 def test_env():20- env = Environment(loader=DictLoader(dict(21- module='{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}',22- header='[{{ foo }}|{{ 23 }}]',23- o_printer='({{ o }})'24- )))25- env.globals['bar'] = 2313+ env = Environment(14+ loader=DictLoader(15+ dict(16+ module="{% macro test() %}[{{ foo }}|{{ bar }}]{% endmacro %}",17+ header="[{{ foo }}|{{ 23 }}]",18+ o_printer="({{ o }})",19+ )20+ )21+ )22+ env.globals["bar"] = 2323 return env24 25 26 @pytest.mark.imports27 class TestImports(object):31-28 def test_context_imports(self, test_env):29 t = test_env.from_string('{% import "module" as m %}{{ m.test() }}')34- assert t.render(foo=42) == '[|23]'30+ assert t.render(foo=42) == "[|23]"31 t = test_env.from_string(32 '{% import "module" as m without context %}{{ m.test() }}'33 )38- assert t.render(foo=42) == '[|23]'34+ assert t.render(foo=42) == "[|23]"35 t = test_env.from_string(36 '{% import "module" as m with context %}{{ m.test() }}'37 )42- assert t.render(foo=42) == '[42|23]'38+ assert t.render(foo=42) == "[42|23]"39 t = test_env.from_string('{% from "module" import test %}{{ test() }}')44- assert t.render(foo=42) == '[|23]'40+ assert t.render(foo=42) == "[|23]"41 t = test_env.from_string(42 '{% from "module" import test without context %}{{ test() }}'43 )48- assert t.render(foo=42) == '[|23]'44+ assert t.render(foo=42) == "[|23]"45 t = test_env.from_string(46 '{% from "module" import test with context %}{{ test() }}'47 )52- assert t.render(foo=42) == '[42|23]'48+ assert t.render(foo=42) == "[42|23]"49 50 def test_import_needs_name(self, test_env):51 test_env.from_string('{% from "foo" import bar %}')52 test_env.from_string('{% from "foo" import bar, baz %}')24 unmodified lines77 with pytest.raises(TemplateSyntaxError):78 test_env.from_string('{% from "foo" import bar with context, %}')79 80 def test_exports(self, test_env):85- m = test_env.from_string('''81+ m = test_env.from_string(82+ """83 {% macro toplevel() %}...{% endmacro %}84 {% macro __private() %}...{% endmacro %}85 {% set variable = 42 %}86 {% for item in [1] %}87 {% macro notthere() %}{% endmacro %}88 {% endfor %}89+ """92- ''').module93- assert m.toplevel() == '...'94- assert not hasattr(m, '__missing')90+ ).module91+ assert m.toplevel() == "..."92+ assert not hasattr(m, "__missing")93 assert m.variable == 4296- assert not hasattr(m, 'notthere')94+ assert not hasattr(m, "notthere")95 96 97 @pytest.mark.imports98 @pytest.mark.includes99 class TestIncludes(object):102-100 def test_context_include(self, test_env):101 t = test_env.from_string('{% include "header" %}')105- assert t.render(foo=42) == '[42|23]'102+ assert t.render(foo=42) == "[42|23]"103 t = test_env.from_string('{% include "header" with context %}')107- assert t.render(foo=42) == '[42|23]'104+ assert t.render(foo=42) == "[42|23]"105 t = test_env.from_string('{% include "header" without context %}')109- assert t.render(foo=42) == '[|23]'106+ assert t.render(foo=42) == "[|23]"107 108 def test_choice_includes(self, test_env):109 t = test_env.from_string('{% include ["missing", "header"] %}')113- assert t.render(foo=42) == '[42|23]'110+ assert t.render(foo=42) == "[42|23]"111 115- t = test_env.from_string(116- '{% include ["missing", "missing2"] ignore missing %}'117- )118- assert t.render(foo=42) == ''112+ t = test_env.from_string('{% include ["missing", "missing2"] ignore missing %}')113+ assert t.render(foo=42) == ""114 115 t = test_env.from_string('{% include ["missing", "missing2"] %}')116 pytest.raises(TemplateNotFound, t.render)117 with pytest.raises(TemplatesNotFound) as e:118 t.render()119 125- assert e.value.templates == ['missing', 'missing2']126- assert e.value.name == 'missing2'120+ assert e.value.templates == ["missing", "missing2"]121+ assert e.value.name == "missing2"122 123 def test_includes(t, **ctx):129- ctx['foo'] = 42130- assert t.render(ctx) == '[42|23]'124+ ctx["foo"] = 42125+ assert t.render(ctx) == "[42|23]"126 127 t = test_env.from_string('{% include ["missing", "header"] %}')128 test_includes(t)134- t = test_env.from_string('{% include x %}')135- test_includes(t, x=['missing', 'header'])129+ t = test_env.from_string("{% include x %}")130+ test_includes(t, x=["missing", "header"])131 t = test_env.from_string('{% include [x, "header"] %}')137- test_includes(t, x='missing')138- t = test_env.from_string('{% include x %}')139- test_includes(t, x='header')140- t = test_env.from_string('{% include [x] %}')141- test_includes(t, x='header')132+ test_includes(t, x="missing")133+ t = test_env.from_string("{% include x %}")134+ test_includes(t, x="header")135+ t = test_env.from_string("{% include [x] %}")136+ test_includes(t, x="header")137 138 def test_include_ignoring_missing(self, test_env):139 t = test_env.from_string('{% include "missing" %}')140 pytest.raises(TemplateNotFound, t.render)146- for extra in '', 'with context', 'without context':147- t = test_env.from_string('{% include "missing" ignore missing ' +148- extra + ' %}')149- assert t.render() == ''141+ for extra in "", "with context", "without context":142+ t = test_env.from_string(143+ '{% include "missing" ignore missing ' + extra + " %}"144+ )145+ assert t.render() == ""146 147 def test_context_include_with_overrides(self, test_env):152- env = Environment(loader=DictLoader(dict(153- main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",154- item="{{ item }}"155- )))148+ env = Environment(149+ loader=DictLoader(150+ dict(151+ main="{% for item in [1, 2, 3] %}{% include 'item' %}{% endfor %}",152+ item="{{ item }}",153+ )154+ )155+ )156 assert env.get_template("main").render() == "123"157 158 def test_unoptimized_scopes(self, test_env):159- t = test_env.from_string("""159+ t = test_env.from_string(160+ """161 {% macro outer(o) %}162 {% macro inner() %}163 {% include "o_printer" %}164 {% endmacro %}165 {{ inner() }}166 {% endmacro %}167 {{ outer("FOO") }}167- """)168- assert t.render().strip() == '(FOO)'168+ """169+ )170+ assert t.render().strip() == "(FOO)"171 172 def test_import_from_with_context(self):171- env = Environment(loader=DictLoader({172- 'a': '{% macro x() %}{{ foobar }}{% endmacro %}',173- }))174- t = env.from_string('{% set foobar = 42 %}{% from "a" '175- 'import x with context %}{{ x() }}')176- assert t.render() == '42'173+ env = Environment(174+ loader=DictLoader({"a": "{% macro x() %}{{ foobar }}{% endmacro %}"})175+ )176+ t = env.from_string(177+ "{% set foobar = 42 %}{% from 'a' import x with context %}{{ x() }}"178+ )179+ assert t.render() == "42"modified:tests/test_inheritance.py+165 added-124 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.inheritance4- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Tests the template inheritance feature.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import pytest3 13-from jinja2 import Environment, DictLoader, TemplateError4+from jinja2 import DictLoader5+from jinja2 import Environment6 from jinja2 import TemplateRuntimeError7 16-LAYOUTTEMPLATE = '''\8+LAYOUTTEMPLATE = """\9 |{% block block1 %}block 1 from layout{% endblock %}10 |{% block block2 %}block 2 from layout{% endblock %}11 |{% block block3 %}12 {% block block4 %}nested block 4 from layout{% endblock %}21-{% endblock %}|'''13+{% endblock %}|"""14 23-LEVEL1TEMPLATE = '''\15+LEVEL1TEMPLATE = """\16 {% extends "layout" %}25-{% block block1 %}block 1 from level1{% endblock %}'''17+{% block block1 %}block 1 from level1{% endblock %}"""18 27-LEVEL2TEMPLATE = '''\19+LEVEL2TEMPLATE = """\20 {% extends "level1" %}21 {% block block2 %}{% block block5 %}nested block 5 from level2{%30-endblock %}{% endblock %}'''22+endblock %}{% endblock %}"""23 32-LEVEL3TEMPLATE = '''\24+LEVEL3TEMPLATE = """\25 {% extends "level2" %}26 {% block block5 %}block 5 from level3{% endblock %}27 {% block block4 %}block 4 from level3{% endblock %}36-'''28+"""29 38-LEVEL4TEMPLATE = '''\30+LEVEL4TEMPLATE = """\31 {% extends "level3" %}32 {% block block3 %}block 3 from level4{% endblock %}41-'''33+"""34 43-WORKINGTEMPLATE = '''\35+WORKINGTEMPLATE = """\36 {% extends "layout" %}37 {% block block1 %}38 {% if false %}39 {% block block2 %}40 this should workd41 {% endblock %}42 {% endif %}43 {% endblock %}52-'''44+"""45 54-DOUBLEEXTENDS = '''\46+DOUBLEEXTENDS = """\47 {% extends "layout" %}48 {% extends "layout" %}49 {% block block1 %}50 {% if false %}1 unmodified line52 this should workd53 {% endblock %}54 {% endif %}55 {% endblock %}64-'''56+"""57 58 59 @pytest.fixture60 def env():69- return Environment(loader=DictLoader({70- 'layout': LAYOUTTEMPLATE,71- 'level1': LEVEL1TEMPLATE,72- 'level2': LEVEL2TEMPLATE,73- 'level3': LEVEL3TEMPLATE,74- 'level4': LEVEL4TEMPLATE,75- 'working': WORKINGTEMPLATE,76- 'doublee': DOUBLEEXTENDS,77- }), trim_blocks=True)61+ return Environment(62+ loader=DictLoader(63+ {64+ "layout": LAYOUTTEMPLATE,65+ "level1": LEVEL1TEMPLATE,66+ "level2": LEVEL2TEMPLATE,67+ "level3": LEVEL3TEMPLATE,68+ "level4": LEVEL4TEMPLATE,69+ "working": WORKINGTEMPLATE,70+ "doublee": DOUBLEEXTENDS,71+ }72+ ),73+ trim_blocks=True,74+ )75 76 77 @pytest.mark.inheritance78 class TestInheritance(object):82-79 def test_layout(self, env):84- tmpl = env.get_template('layout')85- assert tmpl.render() == ('|block 1 from layout|block 2 from '86- 'layout|nested block 4 from layout|')80+ tmpl = env.get_template("layout")81+ assert tmpl.render() == (82+ "|block 1 from layout|block 2 from layout|nested block 4 from layout|"83+ )84 85 def test_level1(self, env):89- tmpl = env.get_template('level1')90- assert tmpl.render() == ('|block 1 from level1|block 2 from '91- 'layout|nested block 4 from layout|')86+ tmpl = env.get_template("level1")87+ assert tmpl.render() == (88+ "|block 1 from level1|block 2 from layout|nested block 4 from layout|"89+ )90 91 def test_level2(self, env):94- tmpl = env.get_template('level2')95- assert tmpl.render() == ('|block 1 from level1|nested block 5 from '96- 'level2|nested block 4 from layout|')92+ tmpl = env.get_template("level2")93+ assert tmpl.render() == (94+ "|block 1 from level1|nested block 5 from "95+ "level2|nested block 4 from layout|"96+ )97 98 def test_level3(self, env):99- tmpl = env.get_template('level3')100- assert tmpl.render() == ('|block 1 from level1|block 5 from level3|'101- 'block 4 from level3|')99+ tmpl = env.get_template("level3")100+ assert tmpl.render() == (101+ "|block 1 from level1|block 5 from level3|block 4 from level3|"102+ )103 104 def test_level4(self, env):104- tmpl = env.get_template('level4')105- assert tmpl.render() == ('|block 1 from level1|block 5 from '106- 'level3|block 3 from level4|')105+ tmpl = env.get_template("level4")106+ assert tmpl.render() == (107+ "|block 1 from level1|block 5 from level3|block 3 from level4|"108+ )109 110 def test_super(self, env):109- env = Environment(loader=DictLoader({110- 'a': '{% block intro %}INTRO{% endblock %}|'111- 'BEFORE|{% block data %}INNER{% endblock %}|AFTER',112- 'b': '{% extends "a" %}{% block data %}({{ '113- 'super() }}){% endblock %}',114- 'c': '{% extends "b" %}{% block intro %}--{{ '115- 'super() }}--{% endblock %}\n{% block data '116- '%}[{{ super() }}]{% endblock %}'117- }))118- tmpl = env.get_template('c')119- assert tmpl.render() == '--INTRO--|BEFORE|[(INNER)]|AFTER'111+ env = Environment(112+ loader=DictLoader(113+ {114+ "a": "{% block intro %}INTRO{% endblock %}|"115+ "BEFORE|{% block data %}INNER{% endblock %}|AFTER",116+ "b": '{% extends "a" %}{% block data %}({{ '117+ "super() }}){% endblock %}",118+ "c": '{% extends "b" %}{% block intro %}--{{ '119+ "super() }}--{% endblock %}\n{% block data "120+ "%}[{{ super() }}]{% endblock %}",121+ }122+ )123+ )124+ tmpl = env.get_template("c")125+ assert tmpl.render() == "--INTRO--|BEFORE|[(INNER)]|AFTER"126 127 def test_working(self, env):122- tmpl = env.get_template('working')128+ env.get_template("working")129 130 def test_reuse_blocks(self, env):125- tmpl = env.from_string('{{ self.foo() }}|{% block foo %}42'126- '{% endblock %}|{{ self.foo() }}')127- assert tmpl.render() == '42|42|42'131+ tmpl = env.from_string(132+ "{{ self.foo() }}|{% block foo %}42{% endblock %}|{{ self.foo() }}"133+ )134+ assert tmpl.render() == "42|42|42"135 136 def test_preserve_blocks(self, env):130- env = Environment(loader=DictLoader({131- 'a': '{% if false %}{% block x %}A{% endblock %}'132- '{% endif %}{{ self.x() }}',133- 'b': '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}'134- }))135- tmpl = env.get_template('b')136- assert tmpl.render() == 'BA'137+ env = Environment(138+ loader=DictLoader(139+ {140+ "a": "{% if false %}{% block x %}A{% endblock %}"141+ "{% endif %}{{ self.x() }}",142+ "b": '{% extends "a" %}{% block x %}B{{ super() }}{% endblock %}',143+ }144+ )145+ )146+ tmpl = env.get_template("b")147+ assert tmpl.render() == "BA"148 149 def test_dynamic_inheritance(self, env):139- env = Environment(loader=DictLoader({140- 'master1': 'MASTER1{% block x %}{% endblock %}',141- 'master2': 'MASTER2{% block x %}{% endblock %}',142- 'child': '{% extends master %}{% block x %}CHILD{% endblock %}'143- }))144- tmpl = env.get_template('child')150+ env = Environment(151+ loader=DictLoader(152+ {153+ "master1": "MASTER1{% block x %}{% endblock %}",154+ "master2": "MASTER2{% block x %}{% endblock %}",155+ "child": "{% extends master %}{% block x %}CHILD{% endblock %}",156+ }157+ )158+ )159+ tmpl = env.get_template("child")160 for m in range(1, 3):146- assert tmpl.render(master='master%d' % m) == 'MASTER%dCHILD' % m161+ assert tmpl.render(master="master%d" % m) == "MASTER%dCHILD" % m162 163 def test_multi_inheritance(self, env):149- env = Environment(loader=DictLoader({150- 'master1': 'MASTER1{% block x %}{% endblock %}',151- 'master2': 'MASTER2{% block x %}{% endblock %}',152- 'child':153- '''{% if master %}{% extends master %}{% else %}{% extends154- 'master1' %}{% endif %}{% block x %}CHILD{% endblock %}'''155- }))156- tmpl = env.get_template('child')157- assert tmpl.render(master='master2') == 'MASTER2CHILD'158- assert tmpl.render(master='master1') == 'MASTER1CHILD'159- assert tmpl.render() == 'MASTER1CHILD'164+ env = Environment(165+ loader=DictLoader(166+ {167+ "master1": "MASTER1{% block x %}{% endblock %}",168+ "master2": "MASTER2{% block x %}{% endblock %}",169+ "child": """{% if master %}{% extends master %}{% else %}{% extends170+ 'master1' %}{% endif %}{% block x %}CHILD{% endblock %}""",171+ }172+ )173+ )174+ tmpl = env.get_template("child")175+ assert tmpl.render(master="master2") == "MASTER2CHILD"176+ assert tmpl.render(master="master1") == "MASTER1CHILD"177+ assert tmpl.render() == "MASTER1CHILD"178 179 def test_scoped_block(self, env):162- env = Environment(loader=DictLoader({163- 'master.html': '{% for item in seq %}[{% block item scoped %}'164- '{% endblock %}]{% endfor %}'165- }))166- t = env.from_string('{% extends "master.html" %}{% block item %}'167- '{{ item }}{% endblock %}')168- assert t.render(seq=list(range(5))) == '[0][1][2][3][4]'180+ env = Environment(181+ loader=DictLoader(182+ {183+ "master.html": "{% for item in seq %}[{% block item scoped %}"184+ "{% endblock %}]{% endfor %}"185+ }186+ )187+ )188+ t = env.from_string(189+ "{% extends 'master.html' %}{% block item %}{{ item }}{% endblock %}"190+ )191+ assert t.render(seq=list(range(5))) == "[0][1][2][3][4]"192 193 def test_super_in_scoped_block(self, env):171- env = Environment(loader=DictLoader({172- 'master.html': '{% for item in seq %}[{% block item scoped %}'173- '{{ item }}{% endblock %}]{% endfor %}'174- }))175- t = env.from_string('{% extends "master.html" %}{% block item %}'176- '{{ super() }}|{{ item * 2 }}{% endblock %}')177- assert t.render(seq=list(range(5))) == '[0|0][1|2][2|4][3|6][4|8]'194+ env = Environment(195+ loader=DictLoader(196+ {197+ "master.html": "{% for item in seq %}[{% block item scoped %}"198+ "{{ item }}{% endblock %}]{% endfor %}"199+ }200+ )201+ )202+ t = env.from_string(203+ '{% extends "master.html" %}{% block item %}'204+ "{{ super() }}|{{ item * 2 }}{% endblock %}"205+ )206+ assert t.render(seq=list(range(5))) == "[0|0][1|2][2|4][3|6][4|8]"207 208 def test_scoped_block_after_inheritance(self, env):180- env = Environment(loader=DictLoader({181- 'layout.html': '''209+ env = Environment(210+ loader=DictLoader(211+ {212+ "layout.html": """213 {% block useless %}{% endblock %}183- ''',184- 'index.html': '''214+ """,215+ "index.html": """216 {%- extends 'layout.html' %}217 {% from 'helpers.html' import foo with context %}218 {% block useless %}219 {% for x in [1, 2, 3] %}1 unmodified line221 {{ foo(x) }}222 {% endblock %}223 {% endfor %}224 {% endblock %}194- ''',195- 'helpers.html': '''225+ """,226+ "helpers.html": """227 {% macro foo(x) %}{{ the_foo + x }}{% endmacro %}197- '''198- }))199- rv = env.get_template('index.html').render(the_foo=42).split()200- assert rv == ['43', '44', '45']228+ """,229+ }230+ )231+ )232+ rv = env.get_template("index.html").render(the_foo=42).split()233+ assert rv == ["43", "44", "45"]234 235 236 @pytest.mark.inheritance237 class TestBugFix(object):205-238 def test_fixed_macro_scoping_bug(self, env):207- assert Environment(loader=DictLoader({208- 'test.html': '''\239+ assert (240+ Environment(241+ loader=DictLoader(242+ {243+ "test.html": """\244 {% extends 'details.html' %}245 246 {% macro my_macro() %}247 my_macro1 unmodified line249 250 {% block inner_box %}251 {{ my_macro() }}252 {% endblock %}218- ''',219- 'details.html': '''\253+ """,254+ "details.html": """\255 {% extends 'standard.html' %}256 257 {% macro my_macro() %}258 my_macro6 unmodified lines265 inner_box266 {% endblock %}267 {% endblock %}268 {% endblock %}234- ''',235- 'standard.html': '''269+ """,270+ "standard.html": """271 {% block content %} {% endblock %}237- '''238- })).get_template("test.html").render().split() \239- == [u'outer_box', u'my_macro']272+ """,273+ }274+ )275+ )276+ .get_template("test.html")277+ .render()278+ .split()279+ == [u"outer_box", u"my_macro"]280+ )281 282 def test_double_extends(self, env):283 """Ensures that a template with more than 1 {% extends ... %} usage284 raises a ``TemplateError``.285 """286 with pytest.raises(TemplateRuntimeError, match="extended multiple times"):246- env.get_template('doublee').render()287+ env.get_template("doublee").render()modified:tests/test_lexnparse.py+416 added-298 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.lexnparse4- ~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- All the unittests regarding lexing, parsing and syntax.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import pytest3 13-from jinja2 import Environment, Template, TemplateSyntaxError, \14- UndefinedError, nodes15-from jinja2._compat import iteritems, text_type, PY216-from jinja2.lexer import Token, TokenStream, TOKEN_EOF, \17- TOKEN_BLOCK_BEGIN, TOKEN_BLOCK_END4+from jinja2 import Environment5+from jinja2 import nodes6+from jinja2 import Template7+from jinja2 import TemplateSyntaxError8+from jinja2 import UndefinedError9+from jinja2._compat import iteritems10+from jinja2._compat import PY211+from jinja2._compat import text_type12+from jinja2.lexer import Token13+from jinja2.lexer import TOKEN_BLOCK_BEGIN14+from jinja2.lexer import TOKEN_BLOCK_END15+from jinja2.lexer import TOKEN_EOF16+from jinja2.lexer import TokenStream17 18 19 # how does a string look like in jinja syntax?20 if PY2:21+22 def jinja_string_repr(string):23 return repr(string)[1:]24+25+26 else:27 jinja_string_repr = repr28 29 30 @pytest.mark.lexnparse31 @pytest.mark.tokenstream32 class TestTokenStream(object):31- test_tokens = [Token(1, TOKEN_BLOCK_BEGIN, ''),32- Token(2, TOKEN_BLOCK_END, ''),33- ]33+ test_tokens = [34+ Token(1, TOKEN_BLOCK_BEGIN, ""),35+ Token(2, TOKEN_BLOCK_END, ""),36+ ]37 38 def test_simple(self, env):39 ts = TokenStream(self.test_tokens, "foo", "bar")40 assert ts.current.type is TOKEN_BLOCK_BEGIN8 unmodified lines49 assert not bool(ts)50 assert bool(ts.eos)51 52 def test_iter(self, env):50- token_types = [51- t.type for t in TokenStream(self.test_tokens, "foo", "bar")53+ token_types = [t.type for t in TokenStream(self.test_tokens, "foo", "bar")]54+ assert token_types == [55+ "block_begin",56+ "block_end",57 ]53- assert token_types == ['block_begin', 'block_end', ]58 59 60 @pytest.mark.lexnparse61 @pytest.mark.lexer62 class TestLexer(object):59-63 def test_raw1(self, env):64 tmpl = env.from_string(62- '{% raw %}foo{% endraw %}|'63- '{%raw%}{{ bar }}|{% baz %}{% endraw %}')64- assert tmpl.render() == 'foo|{{ bar }}|{% baz %}'65+ "{% raw %}foo{% endraw %}|"66+ "{%raw%}{{ bar }}|{% baz %}{% endraw %}"67+ )68+ assert tmpl.render() == "foo|{{ bar }}|{% baz %}"69 70 def test_raw2(self, env):67- tmpl = env.from_string('1 {%- raw -%} 2 {%- endraw -%} 3')68- assert tmpl.render() == '123'71+ tmpl = env.from_string("1 {%- raw -%} 2 {%- endraw -%} 3")72+ assert tmpl.render() == "123"73 74 def test_raw3(self, env):71- # The second newline after baz exists because it is AFTER the {% raw %} and is ignored.75+ # The second newline after baz exists because it is AFTER the76+ # {% raw %} and is ignored.77 env = Environment(lstrip_blocks=True, trim_blocks=True)78 tmpl = env.from_string("bar\n{% raw %}\n {{baz}}2 spaces\n{% endraw %}\nfoo")74- assert tmpl.render(baz='test') == "bar\n\n {{baz}}2 spaces\nfoo"79+ assert tmpl.render(baz="test") == "bar\n\n {{baz}}2 spaces\nfoo"80 81 def test_raw4(self, env):77- # The trailing dash of the {% raw -%} cleans both the spaces and newlines up to the first character of data.82+ # The trailing dash of the {% raw -%} cleans both the spaces and83+ # newlines up to the first character of data.84 env = Environment(lstrip_blocks=True, trim_blocks=False)79- tmpl = env.from_string("bar\n{%- raw -%}\n\n \n 2 spaces\n space{%- endraw -%}\nfoo")85+ tmpl = env.from_string(86+ "bar\n{%- raw -%}\n\n \n 2 spaces\n space{%- endraw -%}\nfoo"87+ )88 assert tmpl.render() == "bar2 spaces\n spacefoo"89 90 def test_balancing(self, env):83- env = Environment('{%', '%}', '${', '}')84- tmpl = env.from_string('''{% for item in seq85- %}${{'foo': item}|upper}{% endfor %}''')86- assert tmpl.render(seq=list(range(3))) \87- == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"91+ env = Environment("{%", "%}", "${", "}")92+ tmpl = env.from_string(93+ """{% for item in seq94+ %}${{'foo': item}|upper}{% endfor %}"""95+ )96+ assert tmpl.render(seq=list(range(3))) == "{'FOO': 0}{'FOO': 1}{'FOO': 2}"97 98 def test_comments(self, env):90- env = Environment('<!--', '-->', '{', '}')91- tmpl = env.from_string('''\99+ env = Environment("<!--", "-->", "{", "}")100+ tmpl = env.from_string(101+ """\102 <ul>103 <!--- for item in seq -->104 <li>{item}</li>105 <!--- endfor -->96-</ul>''')97- assert tmpl.render(seq=list(range(3))) \98- == ("<ul>\n <li>0</li>\n ""<li>1</li>\n <li>2</li>\n</ul>")106+</ul>"""107+ )108+ assert tmpl.render(seq=list(range(3))) == (109+ "<ul>\n <li>0</li>\n <li>1</li>\n <li>2</li>\n</ul>"110+ )111 112 def test_string_escapes(self, env):101- for char in u'\0', u'\u2668', u'\xe4', u'\t', u'\r', u'\n':102- tmpl = env.from_string('{{ %s }}' % jinja_string_repr(char))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))115 assert tmpl.render() == char104- assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u'\u2668'116+ assert env.from_string('{{ "\N{HOT SPRINGS}" }}').render() == u"\u2668"117 118 def test_bytefallback(self, env):119 from pprint import pformat108- tmpl = env.from_string(u'''{{ 'foo'|pprint }}|{{ 'bär'|pprint }}''')109- assert tmpl.render() == pformat('foo') + '|' + pformat(u'bär')120 121+ tmpl = env.from_string(u"""{{ 'foo'|pprint }}|{{ 'bär'|pprint }}""")122+ assert tmpl.render() == pformat("foo") + "|" + pformat(u"bär")123+124 def test_operators(self, env):125 from jinja2.lexer import operators126+127 for test, expect in iteritems(operators):114- if test in '([{}])':128+ if test in "([{}])":129 continue116- stream = env.lexer.tokenize('{{ %s }}' % test)130+ stream = env.lexer.tokenize("{{ %s }}" % test)131 next(stream)132 assert stream.current.type == expect133 134 def test_normalizing(self, env):121- for seq in '\r', '\r\n', '\n':135+ for seq in "\r", "\r\n", "\n":136 env = Environment(newline_sequence=seq)123- tmpl = env.from_string('1\n2\r\n3\n4\n')137+ tmpl = env.from_string("1\n2\r\n3\n4\n")138 result = tmpl.render()125- assert result.replace(seq, 'X') == '1X2X3X4'139+ assert result.replace(seq, "X") == "1X2X3X4"140 141 def test_trailing_newline(self, env):142 for keep in [True, False]:143 env = Environment(keep_trailing_newline=keep)144 for template, expected in [131- ('', {}),132- ('no\nnewline', {}),133- ('with\nnewline\n', {False: 'with\nnewline'}),134- ('with\nseveral\n\n\n', {False: 'with\nseveral\n\n'}),135- ]:145+ ("", {}),146+ ("no\nnewline", {}),147+ ("with\nnewline\n", {False: "with\nnewline"}),148+ ("with\nseveral\n\n\n", {False: "with\nseveral\n\n"}),149+ ]:150 tmpl = env.from_string(template)151 expect = expected.get(keep, template)152 result = tmpl.render()153 assert result == expect, (keep, template, result, expect)154 155+ @pytest.mark.parametrize(156+ "name,valid2,valid3",141- @pytest.mark.parametrize('name,valid2,valid3', (142- (u'foo', True, True),143- (u'föö', False, True),144- (u'き', False, True),145- (u'_', True, True),146- (u'1a', False, False), # invalid ascii start147- (u'a-', False, False), # invalid ascii continue148- (u'🐍', False, False), # invalid unicode start149- (u'a🐍', False, False), # invalid unicode continue150- # start characters not matched by \w151- (u'\u1885', False, True),152- (u'\u1886', False, True),153- (u'\u2118', False, True),154- (u'\u212e', False, True),155- # continue character not matched by \w156- (u'\xb7', False, False),157- (u'a\xb7', False, True),158- ))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 continue166+ # 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),171+ # continue character not matched by \w172+ (u"\xb7", False, False),173+ (u"a\xb7", False, True),174+ ),175+ )176 def test_name(self, env, name, valid2, valid3):160- t = u'{{ ' + name + u' }}'177+ t = u"{{ " + name + u" }}"178 179 if (valid2 and PY2) or (valid3 and not PY2):180 # valid for version being tested, shouldn't raise181 env.from_string(t)3 unmodified lines185 186 @pytest.mark.lexnparse187 @pytest.mark.parser188 class TestParser(object):172-189 def test_php_syntax(self, env):174- env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->')175- tmpl = env.from_string('''\190+ env = Environment("<?", "?>", "<?=", "?>", "<!--", "-->")191+ tmpl = env.from_string(192+ """\193 <!-- I'm a comment, I'm not interesting -->\194 <? for item in seq -?>195 <?= item ?>179-<?- endfor ?>''')180- assert tmpl.render(seq=list(range(5))) == '01234'196+<?- endfor ?>"""197+ )198+ assert tmpl.render(seq=list(range(5))) == "01234"199 200 def test_erb_syntax(self, env):183- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>')184- tmpl = env.from_string('''\201+ env = Environment("<%", "%>", "<%=", "%>", "<%#", "%>")202+ tmpl = env.from_string(203+ """\204 <%# I'm a comment, I'm not interesting %>\205 <% for item in seq -%>206 <%= item %>188-<%- endfor %>''')189- assert tmpl.render(seq=list(range(5))) == '01234'207+<%- endfor %>"""208+ )209+ assert tmpl.render(seq=list(range(5))) == "01234"210 211 def test_comment_syntax(self, env):192- env = Environment('<!--', '-->', '${', '}', '<!--#', '-->')193- tmpl = env.from_string('''\212+ env = Environment("<!--", "-->", "${", "}", "<!--#", "-->")213+ tmpl = env.from_string(214+ """\215 <!--# I'm a comment, I'm not interesting -->\216 <!-- for item in seq --->217 ${item}197-<!--- endfor -->''')198- assert tmpl.render(seq=list(range(5))) == '01234'218+<!--- endfor -->"""219+ )220+ assert tmpl.render(seq=list(range(5))) == "01234"221 222 def test_balancing(self, env):201- tmpl = env.from_string('''{{{'foo':'bar'}.foo}}''')202- assert tmpl.render() == 'bar'223+ tmpl = env.from_string("""{{{'foo':'bar'}.foo}}""")224+ assert tmpl.render() == "bar"225 226 def test_start_comment(self, env):205- tmpl = env.from_string('''{# foo comment227+ tmpl = env.from_string(228+ """{# foo comment229 and bar comment #}230 {% macro blub() %}foo{% endmacro %}208-{{ blub() }}''')209- assert tmpl.render().strip() == 'foo'231+{{ blub() }}"""232+ )233+ assert tmpl.render().strip() == "foo"234 235 def test_line_syntax(self, env):212- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%')213- tmpl = env.from_string('''\236+ env = Environment("<%", "%>", "${", "}", "<%#", "%>", "%")237+ tmpl = env.from_string(238+ """\239 <%# regular comment %>240 % for item in seq:241 ${item}217-% endfor''')242+% endfor"""243+ )244 assert [245 int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()246 ] == list(range(5))247 222- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##')223- tmpl = env.from_string('''\248+ env = Environment("<%", "%>", "${", "}", "<%#", "%>", "%", "##")249+ tmpl = env.from_string(250+ """\251 <%# regular comment %>252 % for item in seq:253 ${item} ## the rest of the stuff227-% endfor''')254+% endfor"""255+ )256 assert [257 int(x.strip()) for x in tmpl.render(seq=list(range(5))).split()258 ] == list(range(5))259 260 def test_line_syntax_priority(self, env):261 # XXX: why is the whitespace there in front of the newline?234- env = Environment('{%', '%}', '${', '}', '/*', '*/', '##', '#')235- tmpl = env.from_string('''\262+ env = Environment("{%", "%}", "${", "}", "/*", "*/", "##", "#")263+ tmpl = env.from_string(264+ """\265 /* ignore me.266 I'm a multiline comment */267 ## for item in seq:268 * ${item} # this is just extra stuff240-## endfor''')241- assert tmpl.render(seq=[1, 2]).strip() == '* 1\n* 2'242- env = Environment('{%', '%}', '${', '}', '/*', '*/', '#', '##')243- tmpl = env.from_string('''\269+## endfor"""270+ )271+ assert tmpl.render(seq=[1, 2]).strip() == "* 1\n* 2"272+ env = Environment("{%", "%}", "${", "}", "/*", "*/", "#", "##")273+ tmpl = env.from_string(274+ """\275 /* ignore me.276 I'm a multiline comment */277 # for item in seq:278 * ${item} ## this is just extra stuff279 ## extra stuff i just want to ignore249-# endfor''')250- assert tmpl.render(seq=[1, 2]).strip() == '* 1\n\n* 2'280+# endfor"""281+ )282+ assert tmpl.render(seq=[1, 2]).strip() == "* 1\n\n* 2"283 284 def test_error_messages(self, env):285 def assert_error(code, expected):286 with pytest.raises(TemplateSyntaxError, match=expected):287 Template(code)288 257- assert_error('{% for item in seq %}...{% endif %}',258- "Encountered unknown tag 'endif'. Jinja was looking "259- "for the following tags: 'endfor' or 'else'. The "260- "innermost block that needs to be closed is 'for'.")289 assert_error(262- '{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}',290+ "{% for item in seq %}...{% endif %}",291+ "Encountered unknown tag 'endif'. Jinja was looking "292+ "for the following tags: 'endfor' or 'else'. The "293+ "innermost block that needs to be closed is 'for'.",294+ )295+ assert_error(296+ "{% if foo %}{% for item in seq %}...{% endfor %}{% endfor %}",297 "Encountered unknown tag 'endfor'. Jinja was looking for "298 "the following tags: 'elif' or 'else' or 'endif'. The "265- "innermost block that needs to be closed is 'if'.")266- assert_error('{% if foo %}',267- "Unexpected end of template. Jinja was looking for the "268- "following tags: 'elif' or 'else' or 'endif'. The "269- "innermost block that needs to be closed is 'if'.")270- assert_error('{% for item in seq %}',271- "Unexpected end of template. Jinja was looking for the "272- "following tags: 'endfor' or 'else'. The innermost block "273- "that needs to be closed is 'for'.")299+ "innermost block that needs to be closed is 'if'.",300+ )301 assert_error(275- '{% block foo-bar-baz %}',302+ "{% if foo %}",303+ "Unexpected end of template. Jinja was looking for the "304+ "following tags: 'elif' or 'else' or 'endif'. The "305+ "innermost block that needs to be closed is 'if'.",306+ )307+ assert_error(308+ "{% for item in seq %}",309+ "Unexpected end of template. Jinja was looking for the "310+ "following tags: 'endfor' or 'else'. The innermost block "311+ "that needs to be closed is 'for'.",312+ )313+ assert_error(314+ "{% block foo-bar-baz %}",315 "Block names in Jinja have to be valid Python identifiers "277- "and may not contain hyphens, use an underscore instead.")278- assert_error('{% unknown_tag %}',279- "Encountered unknown tag 'unknown_tag'.")316+ "and may not contain hyphens, use an underscore instead.",317+ )318+ assert_error("{% unknown_tag %}", "Encountered unknown tag 'unknown_tag'.")319 320 321 @pytest.mark.lexnparse322 @pytest.mark.syntax323 class TestSyntax(object):285-324 def test_call(self, env):325 env = Environment()288- env.globals['foo'] = lambda a, b, c, e, g: a + b + c + e + g289- tmpl = env.from_string(290- "{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}"291- )292- assert tmpl.render() == 'abdfh'326+ env.globals["foo"] = lambda a, b, c, e, g: a + b + c + e + g327+ tmpl = env.from_string("{{ foo('a', c='d', e='f', *['b'], **{'g': 'h'}) }}")328+ assert tmpl.render() == "abdfh"329 330 def test_slicing(self, env):295- tmpl = env.from_string('{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}')296- assert tmpl.render() == '[1, 2, 3]|[3, 2, 1]'331+ tmpl = env.from_string("{{ [1, 2, 3][:] }}|{{ [1, 2, 3][::-1] }}")332+ assert tmpl.render() == "[1, 2, 3]|[3, 2, 1]"333 334 def test_attr(self, env):335 tmpl = env.from_string("{{ foo.bar }}|{{ foo['bar'] }}")300- assert tmpl.render(foo={'bar': 42}) == '42|42'336+ assert tmpl.render(foo={"bar": 42}) == "42|42"337 338 def test_subscript(self, env):339 tmpl = env.from_string("{{ foo[0] }}|{{ foo[-1] }}")304- assert tmpl.render(foo=[0, 1, 2]) == '0|2'340+ assert tmpl.render(foo=[0, 1, 2]) == "0|2"341 342 def test_tuple(self, env):307- tmpl = env.from_string('{{ () }}|{{ (1,) }}|{{ (1, 2) }}')308- assert tmpl.render() == '()|(1,)|(1, 2)'343+ tmpl = env.from_string("{{ () }}|{{ (1,) }}|{{ (1, 2) }}")344+ assert tmpl.render() == "()|(1,)|(1, 2)"345 346 def test_math(self, env):311- tmpl = env.from_string('{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}')312- assert tmpl.render() == '1.5|8'347+ tmpl = env.from_string("{{ (1 + 1 * 2) - 3 / 2 }}|{{ 2**3 }}")348+ assert tmpl.render() == "1.5|8"349 350 def test_div(self, env):315- tmpl = env.from_string('{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}')316- assert tmpl.render() == '1|1.5|1'351+ tmpl = env.from_string("{{ 3 // 2 }}|{{ 3 / 2 }}|{{ 3 % 2 }}")352+ assert tmpl.render() == "1|1.5|1"353 354 def test_unary(self, env):319- tmpl = env.from_string('{{ +3 }}|{{ -3 }}')320- assert tmpl.render() == '3|-3'355+ tmpl = env.from_string("{{ +3 }}|{{ -3 }}")356+ assert tmpl.render() == "3|-3"357 358 def test_concat(self, env):359 tmpl = env.from_string("{{ [1, 2] ~ 'foo' }}")324- assert tmpl.render() == '[1, 2]foo'360+ assert tmpl.render() == "[1, 2]foo"361 362 @pytest.mark.parametrize(363 ("a", "op", "b"),364 [28 unmodified lines393 t = env.from_string(src)394 assert t.render(a=4, b=2, c=3) == expect395 396 def test_inop(self, env):361- tmpl = env.from_string('{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}')362- assert tmpl.render() == 'True|False'397+ tmpl = env.from_string("{{ 1 in [1, 2, 3] }}|{{ 1 not in [1, 2, 3] }}")398+ assert tmpl.render() == "True|False"399 400 @pytest.mark.parametrize("value", ("[]", "{}", "()"))401 def test_collection_literal(self, env, value):402 t = env.from_string("{{ %s }}" % value)13 unmodified lines416 ("2.5e100", "2.5e+100"),417 ("2.5e+100", "2.5e+100"),418 ("25.6e-10", "2.56e-09"),419 ("1_2.3_4e5_6", "1.234e+57"),384- )420+ ),421 )422 def test_numeric_literal(self, env, value, expect):423 t = env.from_string("{{ %s }}" % value)424 assert t.render() == expect425 426 def test_bool(self, env):391- tmpl = env.from_string('{{ true and false }}|{{ false '392- 'or true }}|{{ not false }}')393- assert tmpl.render() == 'False|True|True'427+ tmpl = env.from_string(428+ "{{ true and false }}|{{ false or true }}|{{ not false }}"429+ )430+ assert tmpl.render() == "False|True|True"431 432 def test_grouping(self, env):433 tmpl = env.from_string(397- '{{ (true and false) or (false and true) and not false }}')398- assert tmpl.render() == 'False'434+ "{{ (true and false) or (false and true) and not false }}"435+ )436+ assert tmpl.render() == "False"437 438 def test_django_attr(self, env):401- tmpl = env.from_string('{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}')402- assert tmpl.render() == '1|1'439+ tmpl = env.from_string("{{ [1, 2, 3].0 }}|{{ [[1]].0.0 }}")440+ assert tmpl.render() == "1|1"441 442 def test_conditional_expression(self, env):405- tmpl = env.from_string('''{{ 0 if true else 1 }}''')406- assert tmpl.render() == '0'443+ tmpl = env.from_string("""{{ 0 if true else 1 }}""")444+ assert tmpl.render() == "0"445 446 def test_short_conditional_expression(self, env):409- tmpl = env.from_string('<{{ 1 if false }}>')410- assert tmpl.render() == '<>'447+ tmpl = env.from_string("<{{ 1 if false }}>")448+ assert tmpl.render() == "<>"449 412- tmpl = env.from_string('<{{ (1 if false).bar }}>')450+ tmpl = env.from_string("<{{ (1 if false).bar }}>")451 pytest.raises(UndefinedError, tmpl.render)452 453 def test_filter_priority(self, env):454 tmpl = env.from_string('{{ "foo"|upper + "bar"|upper }}')417- assert tmpl.render() == 'FOOBAR'455+ assert tmpl.render() == "FOOBAR"456 457 def test_function_calls(self, env):458 tests = [421- (True, '*foo, bar'),422- (True, '*foo, *bar'),423- (True, '**foo, *bar'),424- (True, '**foo, bar'),425- (True, '**foo, **bar'),426- (True, '**foo, bar=42'),427- (False, 'foo, bar'),428- (False, 'foo, bar=42'),429- (False, 'foo, bar=23, *args'),430- (False, 'foo, *args, bar=23'),431- (False, 'a, b=c, *d, **e'),432- (False, '*foo, bar=42'),433- (False, '*foo, **bar'),434- (False, '*foo, bar=42, **baz'),435- (False, 'foo, *args, bar=23, **baz'),459+ (True, "*foo, bar"),460+ (True, "*foo, *bar"),461+ (True, "**foo, *bar"),462+ (True, "**foo, bar"),463+ (True, "**foo, **bar"),464+ (True, "**foo, bar=42"),465+ (False, "foo, bar"),466+ (False, "foo, bar=42"),467+ (False, "foo, bar=23, *args"),468+ (False, "foo, *args, bar=23"),469+ (False, "a, b=c, *d, **e"),470+ (False, "*foo, bar=42"),471+ (False, "*foo, **bar"),472+ (False, "*foo, bar=42, **baz"),473+ (False, "foo, *args, bar=23, **baz"),474 ]475 for should_fail, sig in tests:476 if should_fail:439- pytest.raises(TemplateSyntaxError,440- env.from_string, '{{ foo(%s) }}' % sig)477+ pytest.raises(478+ TemplateSyntaxError, env.from_string, "{{ foo(%s) }}" % sig479+ )480 else:442- env.from_string('foo(%s)' % sig)481+ env.from_string("foo(%s)" % sig)482 483 def test_tuple_expr(self, env):484 for tmpl in [446- '{{ () }}',447- '{{ (1, 2) }}',448- '{{ (1, 2,) }}',449- '{{ 1, }}',450- '{{ 1, 2 }}',451- '{% for foo, bar in seq %}...{% endfor %}',452- '{% for x in foo, bar %}...{% endfor %}',453- '{% for x in foo, %}...{% endfor %}'485+ "{{ () }}",486+ "{{ (1, 2) }}",487+ "{{ (1, 2,) }}",488+ "{{ 1, }}",489+ "{{ 1, 2 }}",490+ "{% for foo, bar in seq %}...{% endfor %}",491+ "{% for x in foo, bar %}...{% endfor %}",492+ "{% for x in foo, %}...{% endfor %}",493 ]:494 assert env.from_string(tmpl)495 496 def test_trailing_comma(self, env):458- tmpl = env.from_string('{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}')459- assert tmpl.render().lower() == '(1, 2)|[1, 2]|{1: 2}'497+ tmpl = env.from_string("{{ (1, 2,) }}|{{ [1, 2,] }}|{{ {1: 2,} }}")498+ assert tmpl.render().lower() == "(1, 2)|[1, 2]|{1: 2}"499 500 def test_block_end_name(self, env):462- env.from_string('{% block foo %}...{% endblock foo %}')463- pytest.raises(TemplateSyntaxError, env.from_string,464- '{% block x %}{% endblock y %}')501+ env.from_string("{% block foo %}...{% endblock foo %}")502+ pytest.raises(503+ TemplateSyntaxError, env.from_string, "{% block x %}{% endblock y %}"504+ )505 506 def test_constant_casing(self, env):507 for const in True, False, None:468- tmpl = env.from_string('{{ %s }}|{{ %s }}|{{ %s }}' % (469- str(const), str(const).lower(), str(const).upper()470- ))471- assert tmpl.render() == '%s|%s|' % (const, const)508+ tmpl = env.from_string(509+ "{{ %s }}|{{ %s }}|{{ %s }}"510+ % (str(const), str(const).lower(), str(const).upper())511+ )512+ assert tmpl.render() == "%s|%s|" % (const, const)513 514 def test_test_chaining(self, env):474- pytest.raises(TemplateSyntaxError, env.from_string,475- '{{ foo is string is sequence }}')476- assert env.from_string(477- '{{ 42 is string or 42 is number }}'478- ).render() == 'True'515+ pytest.raises(516+ TemplateSyntaxError, env.from_string, "{{ foo is string is sequence }}"517+ )518+ assert env.from_string("{{ 42 is string or 42 is number }}").render() == "True"519 520 def test_string_concatenation(self, env):521 tmpl = env.from_string('{{ "foo" "bar" "baz" }}')482- assert tmpl.render() == 'foobarbaz'522+ assert tmpl.render() == "foobarbaz"523 524 def test_notin(self, env):525 bar = range(100)486- tmpl = env.from_string('''{{ not 42 in bar }}''')487- assert tmpl.render(bar=bar) == text_type(not 42 in bar)526+ tmpl = env.from_string("""{{ not 42 in bar }}""")527+ assert tmpl.render(bar=bar) == "False"528 529 def test_operator_precedence(self, env):490- tmpl = env.from_string('''{{ 2 * 3 + 4 % 2 + 1 - 2 }}''')530+ tmpl = env.from_string("""{{ 2 * 3 + 4 % 2 + 1 - 2 }}""")531 assert tmpl.render() == text_type(2 * 3 + 4 % 2 + 1 - 2)532 533 def test_implicit_subscribed_tuple(self, env):534 class Foo(object):535 def __getitem__(self, x):536 return x497- t = env.from_string('{{ foo[1, 2] }}')498- assert t.render(foo=Foo()) == u'(1, 2)'537 538+ t = env.from_string("{{ foo[1, 2] }}")539+ assert t.render(foo=Foo()) == u"(1, 2)"540+541 def test_raw2(self, env):501- tmpl = env.from_string('{% raw %}{{ FOO }} and {% BAR %}{% endraw %}')502- assert tmpl.render() == '{{ FOO }} and {% BAR %}'542+ tmpl = env.from_string("{% raw %}{{ FOO }} and {% BAR %}{% endraw %}")543+ assert tmpl.render() == "{{ FOO }} and {% BAR %}"544 545 def test_const(self, env):546 tmpl = env.from_string(506- '{{ true }}|{{ false }}|{{ none }}|'507- '{{ none is defined }}|{{ missing is defined }}')508- assert tmpl.render() == 'True|False|None|True|False'547+ "{{ true }}|{{ false }}|{{ none }}|"548+ "{{ none is defined }}|{{ missing is defined }}"549+ )550+ assert tmpl.render() == "True|False|None|True|False"551 552 def test_neg_filter_priority(self, env):511- node = env.parse('{{ -1|foo }}')553+ node = env.parse("{{ -1|foo }}")554 assert isinstance(node.body[0].nodes[0], nodes.Filter)555 assert isinstance(node.body[0].nodes[0].node, nodes.Neg)556 557 def test_const_assign(self, env):516- constass1 = '''{% set true = 42 %}'''517- constass2 = '''{% for none in seq %}{% endfor %}'''558+ constass1 = """{% set true = 42 %}"""559+ constass2 = """{% for none in seq %}{% endfor %}"""560 for tmpl in constass1, constass2:561 pytest.raises(TemplateSyntaxError, env.from_string, tmpl)562 563 def test_localset(self, env):522- tmpl = env.from_string('''{% set foo = 0 %}\564+ tmpl = env.from_string(565+ """{% set foo = 0 %}\566 {% for item in [1, 2] %}{% set foo = 1 %}{% endfor %}\524-{{ foo }}''')525- assert tmpl.render() == '0'567+{{ foo }}"""568+ )569+ assert tmpl.render() == "0"570 571 def test_parse_unary(self, env):572 tmpl = env.from_string('{{ -foo["bar"] }}')529- assert tmpl.render(foo={'bar': 42}) == '-42'573+ assert tmpl.render(foo={"bar": 42}) == "-42"574 tmpl = env.from_string('{{ -foo["bar"]|abs }}')531- assert tmpl.render(foo={'bar': 42}) == '42'575+ assert tmpl.render(foo={"bar": 42}) == "42"576 577 578 @pytest.mark.lexnparse579 @pytest.mark.lstripblocks580 class TestLstripBlocks(object):537-581 def test_lstrip(self, env):582 env = Environment(lstrip_blocks=True, trim_blocks=False)540- tmpl = env.from_string(''' {% if True %}\n {% endif %}''')583+ tmpl = env.from_string(""" {% if True %}\n {% endif %}""")584 assert tmpl.render() == "\n"585 586 def test_lstrip_trim(self, env):587 env = Environment(lstrip_blocks=True, trim_blocks=True)545- tmpl = env.from_string(''' {% if True %}\n {% endif %}''')588+ tmpl = env.from_string(""" {% if True %}\n {% endif %}""")589 assert tmpl.render() == ""590 591 def test_no_lstrip(self, env):592 env = Environment(lstrip_blocks=True, trim_blocks=False)550- tmpl = env.from_string(''' {%+ if True %}\n {%+ endif %}''')593+ tmpl = env.from_string(""" {%+ if True %}\n {%+ endif %}""")594 assert tmpl.render() == " \n "595 596 def test_lstrip_blocks_false_with_no_lstrip(self, env):597 # Test that + is a NOP (but does not cause an error) if lstrip_blocks=False598 env = Environment(lstrip_blocks=False, trim_blocks=False)556- tmpl = env.from_string(''' {% if True %}\n {% endif %}''')599+ tmpl = env.from_string(""" {% if True %}\n {% endif %}""")600 assert tmpl.render() == " \n "558- tmpl = env.from_string(''' {%+ if True %}\n {%+ endif %}''')601+ tmpl = env.from_string(""" {%+ if True %}\n {%+ endif %}""")602 assert tmpl.render() == " \n "603 604 def test_lstrip_endline(self, env):605 env = Environment(lstrip_blocks=True, trim_blocks=False)563- tmpl = env.from_string(564- ''' hello{% if True %}\n goodbye{% endif %}''')606+ tmpl = env.from_string(""" hello{% if True %}\n goodbye{% endif %}""")607 assert tmpl.render() == " hello\n goodbye"608 609 def test_lstrip_inline(self, env):610 env = Environment(lstrip_blocks=True, trim_blocks=False)569- tmpl = env.from_string(''' {% if True %}hello {% endif %}''')570- assert tmpl.render() == 'hello '611+ tmpl = env.from_string(""" {% if True %}hello {% endif %}""")612+ assert tmpl.render() == "hello "613 614 def test_lstrip_nested(self, env):615 env = Environment(lstrip_blocks=True, trim_blocks=False)616 tmpl = env.from_string(575- ''' {% if True %}a {% if True %}b {% endif %}c {% endif %}''')576- assert tmpl.render() == 'a b c '617+ """ {% if True %}a {% if True %}b {% endif %}c {% endif %}"""618+ )619+ assert tmpl.render() == "a b c "620 621 def test_lstrip_left_chars(self, env):622 env = Environment(lstrip_blocks=True, trim_blocks=False)580- tmpl = env.from_string(''' abc {% if True %}581- hello{% endif %}''')582- assert tmpl.render() == ' abc \n hello'623+ tmpl = env.from_string(624+ """ abc {% if True %}625+ hello{% endif %}"""626+ )627+ assert tmpl.render() == " abc \n hello"628 629 def test_lstrip_embeded_strings(self, env):630 env = Environment(lstrip_blocks=True, trim_blocks=False)586- tmpl = env.from_string(''' {% set x = " {% str %} " %}{{ x }}''')587- assert tmpl.render() == ' {% str %} '631+ tmpl = env.from_string(""" {% set x = " {% str %} " %}{{ x }}""")632+ assert tmpl.render() == " {% str %} "633 634 def test_lstrip_preserve_leading_newlines(self, env):635 env = Environment(lstrip_blocks=True, trim_blocks=False)591- tmpl = env.from_string('''\n\n\n{% set hello = 1 %}''')592- assert tmpl.render() == '\n\n\n'636+ tmpl = env.from_string("""\n\n\n{% set hello = 1 %}""")637+ assert tmpl.render() == "\n\n\n"638 639 def test_lstrip_comment(self, env):640 env = Environment(lstrip_blocks=True, trim_blocks=False)596- tmpl = env.from_string(''' {# if True #}641+ tmpl = env.from_string(642+ """ {# if True #}643 hello598- {#endif#}''')599- assert tmpl.render() == '\nhello\n'644+ {#endif#}"""645+ )646+ assert tmpl.render() == "\nhello\n"647 648 def test_lstrip_angle_bracket_simple(self, env):602- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',603- lstrip_blocks=True, trim_blocks=True)604- tmpl = env.from_string(''' <% if True %>hello <% endif %>''')605- assert tmpl.render() == 'hello '649+ env = Environment(650+ "<%",651+ "%>",652+ "${",653+ "}",654+ "<%#",655+ "%>",656+ "%",657+ "##",658+ lstrip_blocks=True,659+ trim_blocks=True,660+ )661+ tmpl = env.from_string(""" <% if True %>hello <% endif %>""")662+ assert tmpl.render() == "hello "663 664 def test_lstrip_angle_bracket_comment(self, env):608- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',609- lstrip_blocks=True, trim_blocks=True)610- tmpl = env.from_string(''' <%# if True %>hello <%# endif %>''')611- assert tmpl.render() == 'hello '665+ env = Environment(666+ "<%",667+ "%>",668+ "${",669+ "}",670+ "<%#",671+ "%>",672+ "%",673+ "##",674+ lstrip_blocks=True,675+ trim_blocks=True,676+ )677+ tmpl = env.from_string(""" <%# if True %>hello <%# endif %>""")678+ assert tmpl.render() == "hello "679 680 def test_lstrip_angle_bracket(self, env):614- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',615- lstrip_blocks=True, trim_blocks=True)616- tmpl = env.from_string('''\681+ env = Environment(682+ "<%",683+ "%>",684+ "${",685+ "}",686+ "<%#",687+ "%>",688+ "%",689+ "##",690+ lstrip_blocks=True,691+ trim_blocks=True,692+ )693+ tmpl = env.from_string(694+ """\695 <%# regular comment %>696 <% for item in seq %>697 ${item} ## the rest of the stuff620- <% endfor %>''')621- assert tmpl.render(seq=range(5)) == \622- ''.join('%s\n' % x for x in range(5))698+ <% endfor %>"""699+ )700+ assert tmpl.render(seq=range(5)) == "".join("%s\n" % x for x in range(5))701 702 def test_lstrip_angle_bracket_compact(self, env):625- env = Environment('<%', '%>', '${', '}', '<%#', '%>', '%', '##',626- lstrip_blocks=True, trim_blocks=True)627- tmpl = env.from_string('''\703+ env = Environment(704+ "<%",705+ "%>",706+ "${",707+ "}",708+ "<%#",709+ "%>",710+ "%",711+ "##",712+ lstrip_blocks=True,713+ trim_blocks=True,714+ )715+ tmpl = env.from_string(716+ """\717 <%#regular comment%>718 <%for item in seq%>719 ${item} ## the rest of the stuff631- <%endfor%>''')632- assert tmpl.render(seq=range(5)) == \633- ''.join('%s\n' % x for x in range(5))720+ <%endfor%>"""721+ )722+ assert tmpl.render(seq=range(5)) == "".join("%s\n" % x for x in range(5))723 724 def test_php_syntax_with_manual(self, env):636- env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->',637- lstrip_blocks=True, trim_blocks=True)638- tmpl = env.from_string('''\725+ env = Environment(726+ "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True727+ )728+ tmpl = env.from_string(729+ """\730 <!-- I'm a comment, I'm not interesting -->731 <? for item in seq -?>732 <?= item ?>642- <?- endfor ?>''')643- assert tmpl.render(seq=range(5)) == '01234'733+ <?- endfor ?>"""734+ )735+ assert tmpl.render(seq=range(5)) == "01234"736 737 def test_php_syntax(self, env):646- env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->',647- lstrip_blocks=True, trim_blocks=True)648- tmpl = env.from_string('''\738+ env = Environment(739+ "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True740+ )741+ tmpl = env.from_string(742+ """\743 <!-- I'm a comment, I'm not interesting -->744 <? for item in seq ?>745 <?= item ?>652- <? endfor ?>''')653- assert tmpl.render(seq=range(5)) \654- == ''.join(' %s\n' % x for x in range(5))746+ <? endfor ?>"""747+ )748+ assert tmpl.render(seq=range(5)) == "".join(749+ " %s\n" % x for x in range(5)750+ )751 752 def test_php_syntax_compact(self, env):657- env = Environment('<?', '?>', '<?=', '?>', '<!--', '-->',658- lstrip_blocks=True, trim_blocks=True)659- tmpl = env.from_string('''\753+ env = Environment(754+ "<?", "?>", "<?=", "?>", "<!--", "-->", lstrip_blocks=True, trim_blocks=True755+ )756+ tmpl = env.from_string(757+ """\758 <!-- I'm a comment, I'm not interesting -->759 <?for item in seq?>760 <?=item?>663- <?endfor?>''')664- assert tmpl.render(seq=range(5)) \665- == ''.join(' %s\n' % x for x in range(5))761+ <?endfor?>"""762+ )763+ assert tmpl.render(seq=range(5)) == "".join(764+ " %s\n" % x for x in range(5)765+ )766 767 def test_erb_syntax(self, env):668- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',669- lstrip_blocks=True, trim_blocks=True)768+ env = Environment(769+ "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True770+ )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))675- tmpl = env.from_string('''\776+ tmpl = env.from_string(777+ """\778 <%# I'm a comment, I'm not interesting %>779 <% for item in seq %>780 <%= item %>781 <% endfor %>680-''')681- assert tmpl.render(seq=range(5)) \682- == ''.join(' %s\n' % x for x in range(5))782+"""783+ )784+ assert tmpl.render(seq=range(5)) == "".join(" %s\n" % x for x in range(5))785 786 def test_erb_syntax_with_manual(self, env):685- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',686- lstrip_blocks=True, trim_blocks=True)687- tmpl = env.from_string('''\787+ env = Environment(788+ "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True789+ )790+ tmpl = env.from_string(791+ """\792 <%# I'm a comment, I'm not interesting %>793 <% for item in seq -%>794 <%= item %>691- <%- endfor %>''')692- assert tmpl.render(seq=range(5)) == '01234'795+ <%- endfor %>"""796+ )797+ assert tmpl.render(seq=range(5)) == "01234"798 799 def test_erb_syntax_no_lstrip(self, env):695- env = Environment('<%', '%>', '<%=', '%>', '<%#', '%>',696- lstrip_blocks=True, trim_blocks=True)697- tmpl = env.from_string('''\800+ env = Environment(801+ "<%", "%>", "<%=", "%>", "<%#", "%>", lstrip_blocks=True, trim_blocks=True802+ )803+ tmpl = env.from_string(804+ """\805 <%# I'm a comment, I'm not interesting %>806 <%+ for item in seq -%>807 <%= item %>701- <%- endfor %>''')702- assert tmpl.render(seq=range(5)) == ' 01234'808+ <%- endfor %>"""809+ )810+ assert tmpl.render(seq=range(5)) == " 01234"811 812 def test_comment_syntax(self, env):705- env = Environment('<!--', '-->', '${', '}', '<!--#', '-->',706- lstrip_blocks=True, trim_blocks=True)707- tmpl = env.from_string('''\813+ env = Environment(814+ "<!--",815+ "-->",816+ "${",817+ "}",818+ "<!--#",819+ "-->",820+ lstrip_blocks=True,821+ trim_blocks=True,822+ )823+ tmpl = env.from_string(824+ """\825 <!--# I'm a comment, I'm not interesting -->\826 <!-- for item in seq --->827 ${item}711-<!--- endfor -->''')712- assert tmpl.render(seq=range(5)) == '01234'828+<!--- endfor -->"""829+ )830+ assert tmpl.render(seq=range(5)) == "01234"modified:tests/test_loader.py+132 added-136 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.loader4- ~~~~~~~~~~~~~~~~~~~~~~~5-6- Test the loaders.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import os3 import shutil4 import sys14-import time5 import tempfile6+import time7 import weakref8 9 import pytest10 9 unmodified lines20 @pytest.mark.loaders21 class TestLoaders(object):22 def test_dict_loader(self, dict_loader):23 env = Environment(loader=dict_loader)33- tmpl = env.get_template('justdict.html')34- assert tmpl.render().strip() == 'FOO'35- pytest.raises(TemplateNotFound, env.get_template, 'missing.html')24+ tmpl = env.get_template("justdict.html")25+ assert tmpl.render().strip() == "FOO"26+ pytest.raises(TemplateNotFound, env.get_template, "missing.html")27 28 def test_package_loader(self, package_loader):29 env = Environment(loader=package_loader)39- tmpl = env.get_template('test.html')40- assert tmpl.render().strip() == 'BAR'41- pytest.raises(TemplateNotFound, env.get_template, 'missing.html')30+ tmpl = env.get_template("test.html")31+ assert tmpl.render().strip() == "BAR"32+ pytest.raises(TemplateNotFound, env.get_template, "missing.html")33 34 def test_filesystem_loader_overlapping_names(self, filesystem_loader):35 res = os.path.dirname(filesystem_loader.searchpath[0])36 t2_dir = os.path.join(res, "templates2")5 unmodified lines42 e.get_template("foo/test.html")43 44 def test_choice_loader(self, choice_loader):45 env = Environment(loader=choice_loader)55- tmpl = env.get_template('justdict.html')56- assert tmpl.render().strip() == 'FOO'57- tmpl = env.get_template('test.html')58- assert tmpl.render().strip() == 'BAR'59- pytest.raises(TemplateNotFound, env.get_template, 'missing.html')46+ tmpl = env.get_template("justdict.html")47+ assert tmpl.render().strip() == "FOO"48+ tmpl = env.get_template("test.html")49+ assert tmpl.render().strip() == "BAR"50+ pytest.raises(TemplateNotFound, env.get_template, "missing.html")51 52 def test_function_loader(self, function_loader):53 env = Environment(loader=function_loader)63- tmpl = env.get_template('justfunction.html')64- assert tmpl.render().strip() == 'FOO'65- pytest.raises(TemplateNotFound, env.get_template, 'missing.html')54+ tmpl = env.get_template("justfunction.html")55+ assert tmpl.render().strip() == "FOO"56+ pytest.raises(TemplateNotFound, env.get_template, "missing.html")57 58 def test_prefix_loader(self, prefix_loader):59 env = Environment(loader=prefix_loader)69- tmpl = env.get_template('a/test.html')70- assert tmpl.render().strip() == 'BAR'71- tmpl = env.get_template('b/justdict.html')72- assert tmpl.render().strip() == 'FOO'73- pytest.raises(TemplateNotFound, env.get_template, 'missing')60+ tmpl = env.get_template("a/test.html")61+ assert tmpl.render().strip() == "BAR"62+ tmpl = env.get_template("b/justdict.html")63+ assert tmpl.render().strip() == "FOO"64+ pytest.raises(TemplateNotFound, env.get_template, "missing")65 66 def test_caching(self):67 changed = False68 69 class TestLoader(loaders.BaseLoader):70 def get_source(self, environment, template):80- return u'foo', None, lambda: not changed71+ return u"foo", None, lambda: not changed72+73 env = Environment(loader=TestLoader(), cache_size=-1)82- tmpl = env.get_template('template')83- assert tmpl is env.get_template('template')74+ tmpl = env.get_template("template")75+ assert tmpl is env.get_template("template")76 changed = True85- assert tmpl is not env.get_template('template')77+ assert tmpl is not env.get_template("template")78 changed = False79 80 def test_no_cache(self):89- mapping = {'foo': 'one'}81+ mapping = {"foo": "one"}82 env = Environment(loader=loaders.DictLoader(mapping), cache_size=0)91- assert env.get_template('foo') is not env.get_template('foo')83+ assert env.get_template("foo") is not env.get_template("foo")84 85 def test_limited_size_cache(self):94- mapping = {'one': 'foo', 'two': 'bar', 'three': 'baz'}86+ mapping = {"one": "foo", "two": "bar", "three": "baz"}87 loader = loaders.DictLoader(mapping)88 env = Environment(loader=loader, cache_size=2)97- t1 = env.get_template('one')98- t2 = env.get_template('two')99- assert t2 is env.get_template('two')100- assert t1 is env.get_template('one')101- t3 = env.get_template('three')89+ t1 = env.get_template("one")90+ t2 = env.get_template("two")91+ assert t2 is env.get_template("two")92+ assert t1 is env.get_template("one")93+ env.get_template("three")94 loader_ref = weakref.ref(loader)103- assert (loader_ref, 'one') in env.cache104- assert (loader_ref, 'two') not in env.cache105- assert (loader_ref, 'three') in env.cache95+ assert (loader_ref, "one") in env.cache96+ assert (loader_ref, "two") not in env.cache97+ assert (loader_ref, "three") in env.cache98 99 def test_cache_loader_change(self):108- loader1 = loaders.DictLoader({'foo': 'one'})109- loader2 = loaders.DictLoader({'foo': 'two'})100+ loader1 = loaders.DictLoader({"foo": "one"})101+ loader2 = loaders.DictLoader({"foo": "two"})102 env = Environment(loader=loader1, cache_size=2)111- assert env.get_template('foo').render() == 'one'103+ assert env.get_template("foo").render() == "one"104 env.loader = loader2113- assert env.get_template('foo').render() == 'two'105+ assert env.get_template("foo").render() == "two"106 107 def test_dict_loader_cache_invalidates(self):116- mapping = {'foo': "one"}108+ mapping = {"foo": "one"}109 env = Environment(loader=loaders.DictLoader(mapping))118- assert env.get_template('foo').render() == "one"119- mapping['foo'] = "two"120- assert env.get_template('foo').render() == "two"110+ assert env.get_template("foo").render() == "one"111+ mapping["foo"] = "two"112+ assert env.get_template("foo").render() == "two"113 114 def test_split_template_path(self):123- assert split_template_path('foo/bar') == ['foo', 'bar']124- assert split_template_path('./foo/bar') == ['foo', 'bar']125- pytest.raises(TemplateNotFound, split_template_path, '../foo')115+ assert split_template_path("foo/bar") == ["foo", "bar"]116+ assert split_template_path("./foo/bar") == ["foo", "bar"]117+ pytest.raises(TemplateNotFound, split_template_path, "../foo")118 119 120 @pytest.mark.loaders121 @pytest.mark.filesystemloader122 class TestFileSystemLoader(object):131- searchpath = os.path.dirname(os.path.abspath(__file__)) + '/res/templates'123+ searchpath = os.path.join(124+ os.path.dirname(os.path.abspath(__file__)), "res", "templates"125+ )126 127 @staticmethod128 def _test_common(env):135- tmpl = env.get_template('test.html')136- assert tmpl.render().strip() == 'BAR'137- tmpl = env.get_template('foo/test.html')138- assert tmpl.render().strip() == 'FOO'139- pytest.raises(TemplateNotFound, env.get_template, 'missing.html')129+ tmpl = env.get_template("test.html")130+ assert tmpl.render().strip() == "BAR"131+ tmpl = env.get_template("foo/test.html")132+ assert tmpl.render().strip() == "FOO"133+ pytest.raises(TemplateNotFound, env.get_template, "missing.html")134 135 def test_searchpath_as_str(self):136 filesystem_loader = loaders.FileSystemLoader(self.searchpath)137 138 env = Environment(loader=filesystem_loader)139 self._test_common(env)140 147- @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')141+ @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")142 def test_searchpath_as_pathlib(self):143 import pathlib144+145 searchpath = pathlib.Path(self.searchpath)146 147 filesystem_loader = loaders.FileSystemLoader(searchpath)148 149 env = Environment(loader=filesystem_loader)150 self._test_common(env)151 157- @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')152+ @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")153 def test_searchpath_as_list_including_pathlib(self):154 import pathlib155+156 searchpath = pathlib.Path(self.searchpath)157 162- filesystem_loader = loaders.FileSystemLoader(['/tmp/templates', searchpath])158+ filesystem_loader = loaders.FileSystemLoader(["/tmp/templates", searchpath])159 160 env = Environment(loader=filesystem_loader)161 self._test_common(env)162 163 def test_caches_template_based_on_mtime(self):164 filesystem_loader = loaders.FileSystemLoader(self.searchpath)165 166 env = Environment(loader=filesystem_loader)171- tmpl1 = env.get_template('test.html')172- tmpl2 = env.get_template('test.html')167+ tmpl1 = env.get_template("test.html")168+ tmpl2 = env.get_template("test.html")169 assert tmpl1 is tmpl2170 175- os.utime(176- os.path.join(self.searchpath, "test.html"),177- (time.time(), time.time())178- )179- tmpl3 = env.get_template('test.html')171+ os.utime(os.path.join(self.searchpath, "test.html"), (time.time(), time.time()))172+ tmpl3 = env.get_template("test.html")173 assert tmpl1 is not tmpl3174 182- @pytest.mark.parametrize('encoding, expected_text', [183- ('utf-8', u'tech'),184- ('utf-16', u'整档'),185- ])186- def test_uses_specified_encoding(self, encoding, expected_text):187- filesystem_loader = loaders.FileSystemLoader(self.searchpath, encoding=encoding)188- env = Environment(loader=filesystem_loader)189- tmpl = env.get_template('variable_encoding.txt')190- assert tmpl.render().strip() == expected_text175+ @pytest.mark.parametrize(176+ ("encoding", "expect"),177+ [178+ ("utf-8", u"文字化け"),179+ ("iso-8859-1", u"æ\x96\x87\xe5\xad\x97\xe5\x8c\x96\xe3\x81\x91"),180+ ],181+ )182+ def test_uses_specified_encoding(self, encoding, expect):183+ loader = loaders.FileSystemLoader(self.searchpath, encoding=encoding)184+ e = Environment(loader=loader)185+ t = e.get_template("mojibake.txt")186+ assert t.render() == expect187 188 189 @pytest.mark.loaders190 @pytest.mark.moduleloader191 class TestModuleLoader(object):192 archive = None193 198- def compile_down(self, prefix_loader, zip='deflated', py_compile=False):194+ def compile_down(self, prefix_loader, zip="deflated", py_compile=False):195 log = []196 self.reg_env = Environment(loader=prefix_loader)197 if zip is not None:202- fd, self.archive = tempfile.mkstemp(suffix='.zip')198+ fd, self.archive = tempfile.mkstemp(suffix=".zip")199 os.close(fd)200 else:201 self.archive = tempfile.mkdtemp()206- self.reg_env.compile_templates(self.archive, zip=zip,207- log_function=log.append,208- py_compile=py_compile)202+ self.reg_env.compile_templates(203+ self.archive, zip=zip, log_function=log.append, py_compile=py_compile204+ )205 self.mod_env = Environment(loader=loaders.ModuleLoader(self.archive))210- return ''.join(log)206+ return "".join(log)207 208 def teardown(self):213- if hasattr(self, 'mod_env'):209+ if hasattr(self, "mod_env"):210 if os.path.isfile(self.archive):211 os.remove(self.archive)212 else:213 shutil.rmtree(self.archive)214 self.archive = None215 216 def test_log(self, prefix_loader):217 log = self.compile_down(prefix_loader)222- assert 'Compiled "a/foo/test.html" as ' \223- 'tmpl_a790caf9d669e39ea4d280d597ec891c4ef0404a' in log224- assert 'Finished compiling templates' in log225- assert 'Could not compile "a/syntaxerror.html": ' \226- 'Encountered unknown tag \'endif\'' in log218+ assert (219+ 'Compiled "a/foo/test.html" as '220+ "tmpl_a790caf9d669e39ea4d280d597ec891c4ef0404a" in log221+ )222+ assert "Finished compiling templates" in log223+ assert (224+ 'Could not compile "a/syntaxerror.html": '225+ "Encountered unknown tag 'endif'" in log226+ )227 228 def _test_common(self):229- tmpl1 = self.reg_env.get_template('a/test.html')230- tmpl2 = self.mod_env.get_template('a/test.html')229+ tmpl1 = self.reg_env.get_template("a/test.html")230+ tmpl2 = self.mod_env.get_template("a/test.html")231 assert tmpl1.render() == tmpl2.render()232 233- tmpl1 = self.reg_env.get_template('b/justdict.html')234- tmpl2 = self.mod_env.get_template('b/justdict.html')233+ tmpl1 = self.reg_env.get_template("b/justdict.html")234+ tmpl2 = self.mod_env.get_template("b/justdict.html")235 assert tmpl1.render() == tmpl2.render()236 237 def test_deflated_zip_compile(self, prefix_loader):238- self.compile_down(prefix_loader, zip='deflated')238+ self.compile_down(prefix_loader, zip="deflated")239 self._test_common()240 241 def test_stored_zip_compile(self, prefix_loader):242- self.compile_down(prefix_loader, zip='stored')242+ self.compile_down(prefix_loader, zip="stored")243 self._test_common()244 245 def test_filesystem_compile(self, prefix_loader):246 self.compile_down(prefix_loader, zip=None)247 self._test_common()248 249 def test_weak_references(self, prefix_loader):250 self.compile_down(prefix_loader)251- tmpl = self.mod_env.get_template('a/test.html')252- key = loaders.ModuleLoader.get_template_key('a/test.html')251+ self.mod_env.get_template("a/test.html")252+ key = loaders.ModuleLoader.get_template_key("a/test.html")253 name = self.mod_env.loader.module.__name__254 255 assert hasattr(self.mod_env.loader.module, key)256 assert name in sys.modules257 258 # unset all, ensure the module is gone from sys.modules259- self.mod_env = tmpl = None259+ self.mod_env = None260 261 try:262 import gc263+264 gc.collect()264- except:265+ except BaseException:266 pass267 268 assert name not in sys.modules269 270 # This test only makes sense on non-pypy python 2271 @pytest.mark.skipif(271- not (PY2 and not PYPY),272- reason='This test only makes sense on non-pypy python 2')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 log276- tmpl1 = self.mod_env.get_template('a/test.html')277- mod = self.mod_env.loader.module. \278- tmpl_3c4ddf650c1a73df961a6d3d2ce2752f1b8fd490279- assert mod.__file__.endswith('.pyc')277+ self.mod_env.get_template("a/test.html")278+ mod = self.mod_env.loader.module.tmpl_3c4ddf650c1a73df961a6d3d2ce2752f1b8fd490279+ assert mod.__file__.endswith(".pyc")280 281 def test_choice_loader(self, prefix_loader):282- log = self.compile_down(prefix_loader)282+ self.compile_down(prefix_loader)283+ self.mod_env.loader = loaders.ChoiceLoader(284+ [self.mod_env.loader, loaders.DictLoader({"DICT_SOURCE": "DICT_TEMPLATE"})]285+ )286+ tmpl1 = self.mod_env.get_template("a/test.html")287+ assert tmpl1.render() == "BAR"288+ tmpl2 = self.mod_env.get_template("DICT_SOURCE")289+ assert tmpl2.render() == "DICT_TEMPLATE"290 284- self.mod_env.loader = loaders.ChoiceLoader([285- self.mod_env.loader,286- loaders.DictLoader({'DICT_SOURCE': 'DICT_TEMPLATE'})287- ])288-289- tmpl1 = self.mod_env.get_template('a/test.html')290- assert tmpl1.render() == 'BAR'291- tmpl2 = self.mod_env.get_template('DICT_SOURCE')292- assert tmpl2.render() == 'DICT_TEMPLATE'293-291 def test_prefix_loader(self, prefix_loader):295- log = self.compile_down(prefix_loader)292+ self.compile_down(prefix_loader)293+ self.mod_env.loader = loaders.PrefixLoader(294+ {295+ "MOD": self.mod_env.loader,296+ "DICT": loaders.DictLoader({"test.html": "DICT_TEMPLATE"}),297+ }298+ )299+ tmpl1 = self.mod_env.get_template("MOD/a/test.html")300+ assert tmpl1.render() == "BAR"301+ tmpl2 = self.mod_env.get_template("DICT/test.html")302+ assert tmpl2.render() == "DICT_TEMPLATE"303 297- self.mod_env.loader = loaders.PrefixLoader({298- 'MOD': self.mod_env.loader,299- 'DICT': loaders.DictLoader({'test.html': 'DICT_TEMPLATE'})300- })301-302- tmpl1 = self.mod_env.get_template('MOD/a/test.html')303- assert tmpl1.render() == 'BAR'304- tmpl2 = self.mod_env.get_template('DICT/test.html')305- assert tmpl2.render() == 'DICT_TEMPLATE'306-307- @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')304+ @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")305 def test_path_as_pathlib(self, prefix_loader):306 self.compile_down(prefix_loader)307 308 mod_path = self.mod_env.loader.module.__path__[0]309 310 import pathlib311+312 mod_loader = loaders.ModuleLoader(pathlib.Path(mod_path))313 self.mod_env = Environment(loader=mod_loader)314 315 self._test_common()316 319- @pytest.mark.skipif(PY2, reason='pathlib is not available in Python 2')317+ @pytest.mark.skipif(PY2, reason="pathlib is not available in Python 2")318 def test_supports_pathlib_in_list_of_paths(self, prefix_loader):319 self.compile_down(prefix_loader)320 321 mod_path = self.mod_env.loader.module.__path__[0]322 323 import pathlib326- mod_loader = loaders.ModuleLoader([327- pathlib.Path(mod_path),328- '/tmp/templates'329- ])324+325+ mod_loader = loaders.ModuleLoader([pathlib.Path(mod_path), "/tmp/templates"])326 self.mod_env = Environment(loader=mod_loader)327 328 self._test_common()329 48 unmodified linesmodified:tests/test_nativetypes.py+21 added-18 removed
11 unmodified lines12 return NativeEnvironment()13 14 15 def test_is_defined_native_return(env):16- t = env.from_string('{{ missing is defined }}')16+ t = env.from_string("{{ missing is defined }}")17 assert not t.render()18 19 20 def test_undefined_native_return(env):21- t = env.from_string('{{ missing }}')21+ t = env.from_string("{{ missing }}")22 assert isinstance(t.render(), Undefined)23 24 25 def test_adding_undefined_native_return(env):26- t = env.from_string('{{ 3 + missing }}')26+ t = env.from_string("{{ 3 + missing }}")27 28 with pytest.raises(UndefinedError):29 t.render()30 31 32 def test_cast_int(env):33 t = env.from_string("{{ value|int }}")34- result = t.render(value='3')34+ result = t.render(value="3")35 assert isinstance(result, int)36 assert result == 337 38 39 def test_list_add(env):40 t = env.from_string("{{ a + b }}")41- result = t.render(a=['a', 'b'], b=['c', 'd'])41+ result = t.render(a=["a", "b"], b=["c", "d"])42 assert isinstance(result, list)43- assert result == ['a', 'b', 'c', 'd']43+ assert result == ["a", "b", "c", "d"]44 45 46 def test_multi_expression_add(env):47 t = env.from_string("{{ a }} + {{ b }}")48- result = t.render(a=['a', 'b'], b=['c', 'd'])48+ result = t.render(a=["a", "b"], b=["c", "d"])49 assert not isinstance(result, list)50 assert result == "['a', 'b'] + ['c', 'd']"51 52 53 def test_loops(env):54 t = env.from_string("{% for x in value %}{{ x }}{% endfor %}")55- result = t.render(value=['a', 'b', 'c', 'd'])55+ result = t.render(value=["a", "b", "c", "d"])56 assert isinstance(result, text_type)57- assert result == 'abcd'57+ assert result == "abcd"58 59 60 def test_loops_with_ints(env):61 t = env.from_string("{% for x in value %}{{ x }}{% endfor %}")8 unmodified lines70 assert isinstance(result, int)71 assert result == 172 73 74-@pytest.mark.parametrize(("source", "expect"), (75- ("{{ value }}", True),76- ("{{ value }}", False),77- ("{{ 1 == 1 }}", True),78- ("{{ 2 + 2 == 5 }}", False),79- ("{{ None is none }}", True),80- ("{{ '' == None }}", False),81-))74+@pytest.mark.parametrize(75+ ("source", "expect"),76+ (77+ ("{{ value }}", True),78+ ("{{ value }}", False),79+ ("{{ 1 == 1 }}", True),80+ ("{{ 2 + 2 == 5 }}", False),81+ ("{{ None is none }}", True),82+ ("{{ '' == None }}", False),83+ ),84+)85 def test_booleans(env, source, expect):86 t = env.from_string(source)87 result = t.render(value=expect)88 assert isinstance(result, bool)28 unmodified lines117 118 def test_string_top_level(env):119 t = env.from_string("'Jinja'")120 result = t.render()118- assert result == 'Jinja'121+ assert result == "Jinja"122 123 124 def test_tuple_of_variable_strings(env):125 t = env.from_string("'{{ a }}', 'data', '{{ b }}', b'{{ c }}'")14 unmodified linesmodified:tests/test_regression.py+313 added-235 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.regression4- ~~~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Tests corner cases and bugs.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import sys3+4 import pytest5 14-from jinja2 import Template, Environment, DictLoader, TemplateSyntaxError, \15- TemplateAssertionError, TemplateNotFound, PrefixLoader6+from jinja2 import DictLoader7+from jinja2 import Environment8+from jinja2 import PrefixLoader9+from jinja2 import Template10+from jinja2 import TemplateAssertionError11+from jinja2 import TemplateNotFound12+from jinja2 import TemplateSyntaxError13 from jinja2._compat import text_type14 15 16 @pytest.mark.regression17 class TestCorner(object):21-18 def test_assigned_scoping(self, env):23- t = env.from_string('''19+ t = env.from_string(20+ """21 {%- for item in (1, 2, 3, 4) -%}22 [{{ item }}]23 {%- endfor %}24 {{- item -}}28- ''')29- assert t.render(item=42) == '[1][2][3][4]42'25+ """26+ )27+ assert t.render(item=42) == "[1][2][3][4]42"28 31- t = env.from_string('''29+ t = env.from_string(30+ """31 {%- for item in (1, 2, 3, 4) -%}32 [{{ item }}]33 {%- endfor %}34 {%- set item = 42 %}35 {{- item -}}37- ''')38- assert t.render() == '[1][2][3][4]42'36+ """37+ )38+ assert t.render() == "[1][2][3][4]42"39 40- t = env.from_string('''40+ t = env.from_string(41+ """42 {%- set item = 42 %}43 {%- for item in (1, 2, 3, 4) -%}44 [{{ item }}]45 {%- endfor %}46 {{- item -}}46- ''')47- assert t.render() == '[1][2][3][4]42'47+ """48+ )49+ assert t.render() == "[1][2][3][4]42"50 51 def test_closure_scoping(self, env):50- t = env.from_string('''52+ t = env.from_string(53+ """54 {%- set wrapper = "<FOO>" %}55 {%- for item in (1, 2, 3, 4) %}56 {%- macro wrapper() %}[{{ item }}]{% endmacro %}57 {{- wrapper() }}58 {%- endfor %}59 {{- wrapper -}}57- ''')58- assert t.render() == '[1][2][3][4]<FOO>'60+ """61+ )62+ assert t.render() == "[1][2][3][4]<FOO>"63 60- t = env.from_string('''64+ t = env.from_string(65+ """66 {%- for item in (1, 2, 3, 4) %}67 {%- macro wrapper() %}[{{ item }}]{% endmacro %}68 {{- wrapper() }}69 {%- endfor %}70 {%- set wrapper = "<FOO>" %}71 {{- wrapper -}}67- ''')68- assert t.render() == '[1][2][3][4]<FOO>'72+ """73+ )74+ assert t.render() == "[1][2][3][4]<FOO>"75 70- t = env.from_string('''76+ t = env.from_string(77+ """78 {%- for item in (1, 2, 3, 4) %}79 {%- macro wrapper() %}[{{ item }}]{% endmacro %}80 {{- wrapper() }}81 {%- endfor %}82 {{- wrapper -}}76- ''')77- assert t.render(wrapper=23) == '[1][2][3][4]23'83+ """84+ )85+ assert t.render(wrapper=23) == "[1][2][3][4]23"86 87 88 @pytest.mark.regression89 class TestBug(object):82-90 def test_keyword_folding(self, env):91 env = Environment()85- env.filters['testing'] = lambda value, some: value + some86- assert env.from_string("{{ 'test'|testing(some='stuff') }}") \87- .render() == 'teststuff'92+ env.filters["testing"] = lambda value, some: value + some93+ assert (94+ env.from_string("{{ 'test'|testing(some='stuff') }}").render()95+ == "teststuff"96+ )97 98 def test_extends_output_bugs(self, env):90- env = Environment(loader=DictLoader({91- 'parent.html': '(({% block title %}{% endblock %}))'92- }))99+ env = Environment(100+ loader=DictLoader({"parent.html": "(({% block title %}{% endblock %}))"})101+ )102 103 t = env.from_string(104 '{% if expr %}{% extends "parent.html" %}{% endif %}'96- '[[{% block title %}title{% endblock %}]]'97- '{% for item in [1, 2, 3] %}({{ item }}){% endfor %}'105+ "[[{% block title %}title{% endblock %}]]"106+ "{% for item in [1, 2, 3] %}({{ item }}){% endfor %}"107 )99- assert t.render(expr=False) == '[[title]](1)(2)(3)'100- assert t.render(expr=True) == '((title))'108+ assert t.render(expr=False) == "[[title]](1)(2)(3)"109+ assert t.render(expr=True) == "((title))"110 111 def test_urlize_filter_escaping(self, env):112 tmpl = env.from_string('{{ "http://www.example.org/<foo"|urlize }}')104- assert tmpl.render() == '<a href="http://www.example.org/<foo" rel="noopener">'\105- 'http://www.example.org/<foo</a>'113+ assert (114+ tmpl.render() == '<a href="http://www.example.org/<foo" rel="noopener">'115+ "http://www.example.org/<foo</a>"116+ )117 118 def test_loop_call_loop(self, env):108- tmpl = env.from_string('''119+ tmpl = env.from_string(120+ """121 122 {% macro test() %}123 {{ caller() }}124 {% endmacro %}5 unmodified lines130 {% endfor %}131 {% endcall %}132 {% endfor %}133 122- ''')134+ """135+ )136 124- assert tmpl.render().split() \125- == [text_type(x) for x in range(1, 11)] * 5137+ assert tmpl.render().split() == [text_type(x) for x in range(1, 11)] * 5138 139 def test_weird_inline_comment(self, env):128- env = Environment(line_statement_prefix='%')129- pytest.raises(TemplateSyntaxError, env.from_string,130- '% for item in seq {# missing #}\n...% endfor')140+ env = Environment(line_statement_prefix="%")141+ pytest.raises(142+ TemplateSyntaxError,143+ env.from_string,144+ "% for item in seq {# missing #}\n...% endfor",145+ )146 147 def test_old_macro_loop_scoping_bug(self, env):133- tmpl = env.from_string('{% for i in (1, 2) %}{{ i }}{% endfor %}'134- '{% macro i() %}3{% endmacro %}{{ i() }}')135- assert tmpl.render() == '123'148+ tmpl = env.from_string(149+ "{% for i in (1, 2) %}{{ i }}{% endfor %}"150+ "{% macro i() %}3{% endmacro %}{{ i() }}"151+ )152+ assert tmpl.render() == "123"153 154 def test_partial_conditional_assignments(self, env):138- tmpl = env.from_string('{% if b %}{% set a = 42 %}{% endif %}{{ a }}')139- assert tmpl.render(a=23) == '23'140- assert tmpl.render(b=True) == '42'155+ tmpl = env.from_string("{% if b %}{% set a = 42 %}{% endif %}{{ a }}")156+ assert tmpl.render(a=23) == "23"157+ assert tmpl.render(b=True) == "42"158 159 def test_stacked_locals_scoping_bug(self, env):143- env = Environment(line_statement_prefix='#')144- t = env.from_string('''\160+ env = Environment(line_statement_prefix="#")161+ t = env.from_string(162+ """\163 # for j in [1, 2]:164 # set x = 1165 # for i in [1, 2]:166 # print x10 unmodified lines177 # print 'C'178 # else179 # print 'D'180 # endif181+ """163- ''')164- assert t.render(a=0, b=False, c=42, d=42.0) == '1111C'182+ )183+ assert t.render(a=0, b=False, c=42, d=42.0) == "1111C"184 185 def test_stacked_locals_scoping_bug_twoframe(self, env):167- t = Template('''186+ t = Template(187+ """188 {% set x = 1 %}189 {% for item in foo %}190 {% if item == 1 %}191 {% set x = 2 %}192 {% endif %}193 {% endfor %}194 {{ x }}175- ''')195+ """196+ )197 rv = t.render(foo=[1]).strip()177- assert rv == u'1'198+ assert rv == u"1"199 200 def test_call_with_args(self, env):180- t = Template("""{% macro dump_users(users) -%}201+ t = Template(202+ """{% macro dump_users(users) -%}203 <ul>204 {%- for user in users -%}205 <li><p>{{ user.username|e }}</p>{{ caller(user) }}</li>206 {%- endfor -%}6 unmodified lines213 <dd>{{ user.realname|e }}</dd>214 <dl>Description</dl>215 <dd>{{ user.description }}</dd>216 </dl>195- {% endcall %}""")217+ {% endcall %}"""218+ )219 197- assert [x.strip() for x in t.render(list_of_user=[{198- 'username': 'apo',199- 'realname': 'something else',200- 'description': 'test'201- }]).splitlines()] == [202- u'<ul><li><p>apo</p><dl>',203- u'<dl>Realname</dl>',204- u'<dd>something else</dd>',205- u'<dl>Description</dl>',206- u'<dd>test</dd>',207- u'</dl>',208- u'</li></ul>'220+ assert [221+ x.strip()222+ for x in t.render(223+ list_of_user=[224+ {225+ "username": "apo",226+ "realname": "something else",227+ "description": "test",228+ }229+ ]230+ ).splitlines()231+ ] == [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>",239 ]240 241 def test_empty_if_condition_fails(self, env):212- pytest.raises(TemplateSyntaxError,213- Template, '{% if %}....{% endif %}')214- pytest.raises(TemplateSyntaxError,215- Template, '{% if foo %}...{% elif %}...{% endif %}')216- pytest.raises(TemplateSyntaxError,217- Template, '{% for x in %}..{% endfor %}')242+ pytest.raises(TemplateSyntaxError, Template, "{% if %}....{% endif %}")243+ pytest.raises(244+ TemplateSyntaxError, Template, "{% if foo %}...{% elif %}...{% endif %}"245+ )246+ pytest.raises(TemplateSyntaxError, Template, "{% for x in %}..{% endfor %}")247 219- def test_recursive_loop_bug(self, env):220- tpl1 = Template("""221- {% for p in foo recursive%}222- {{p.bar}}223- {% for f in p.fields recursive%}224- {{f.baz}}248+ def test_recursive_loop_compile(self, env):249+ Template(250+ """251+ {% for p in foo recursive%}252 {{p.bar}}253+ {% for f in p.fields recursive%}254+ {{f.baz}}255+ {{p.bar}}226- {% if f.rec %}227- {{ loop(f.sub) }}228- {% endif %}256+ {% if f.rec %}257+ {{ loop(f.sub) }}258+ {% endif %}259+ {% endfor %}260 {% endfor %}230- {% endfor %}231- """)232-233- tpl2 = Template("""234- {% for p in foo%}235- {{p.bar}}236- {% for f in p.fields recursive%}237- {{f.baz}}261+ """262+ )263+ Template(264+ """265+ {% for p in foo%}266 {{p.bar}}267+ {% for f in p.fields recursive%}268+ {{f.baz}}269+ {{p.bar}}239- {% if f.rec %}240- {{ loop(f.sub) }}241- {% endif %}270+ {% if f.rec %}271+ {{ loop(f.sub) }}272+ {% endif %}273+ {% endfor %}274 {% endfor %}243- {% endfor %}244- """)275+ """276+ )277 278 def test_else_loop_bug(self, env):247- t = Template('''279+ t = Template(280+ """281 {% for x in y %}282 {{ loop.index0 }}283 {% else %}284 {% for i in range(3) %}{{ i }}{% endfor %}285 {% endfor %}286+ """253- ''')254- assert t.render(y=[]).strip() == '012'287+ )288+ assert t.render(y=[]).strip() == "012"289 290 def test_correct_prefix_loader_name(self, env):257- env = Environment(loader=PrefixLoader({258- 'foo': DictLoader({})259- }))291+ env = Environment(loader=PrefixLoader({"foo": DictLoader({})}))292 with pytest.raises(TemplateNotFound) as e:261- env.get_template('foo/bar.html')293+ env.get_template("foo/bar.html")294 263- assert e.value.name == 'foo/bar.html'295+ assert e.value.name == "foo/bar.html"296 297 def test_contextfunction_callable_classes(self, env):298 from jinja2.utils import contextfunction299 300 class CallableClass(object):301 @contextfunction302 def __call__(self, ctx):271- return ctx.resolve('hello')303+ return ctx.resolve("hello")304 305 tpl = Template("""{{ callableclass() }}""")274- output = tpl.render(callableclass=CallableClass(), hello='TEST')275- expected = 'TEST'306+ output = tpl.render(callableclass=CallableClass(), hello="TEST")307+ expected = "TEST"308 309 assert output == expected310 279- @pytest.mark.skipif(sys.version_info[0] > 2,280- reason='This only works on 2.x')311+ @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 = 42284- assert env.getitem(Foo(), 'x') == 42315 316+ assert env.getitem(Foo(), "x") == 42317+318 def test_block_set_with_extends(self):287- env = Environment(loader=DictLoader({288- 'main': '{% block body %}[{{ x }}]{% endblock %}',289- }))319+ env = Environment(320+ loader=DictLoader({"main": "{% block body %}[{{ x }}]{% endblock %}"})321+ )322 t = env.from_string('{% extends "main" %}{% set x %}42{% endset %}')291- assert t.render() == '[42]'323+ assert t.render() == "[42]"324 325 def test_nested_for_else(self, env):294- tmpl = env.from_string('{% for x in y %}{{ loop.index0 }}{% else %}'295- '{% for i in range(3) %}{{ i }}{% endfor %}'296- '{% endfor %}')297- assert tmpl.render() == '012'326+ tmpl = env.from_string(327+ "{% for x in y %}{{ loop.index0 }}{% else %}"328+ "{% for i in range(3) %}{{ i }}{% endfor %}"329+ "{% endfor %}"330+ )331+ assert tmpl.render() == "012"332 333 def test_macro_var_bug(self, env):300- tmpl = env.from_string('''334+ tmpl = env.from_string(335+ """336 {% set i = 1 %}337 {% macro test() %}338 {% for i in range(0, 10) %}{{ i }}{% endfor %}339 {% endmacro %}{{ test() }}305- ''')306- assert tmpl.render().strip() == '0123456789'340+ """341+ )342+ assert tmpl.render().strip() == "0123456789"343 344 def test_macro_var_bug_advanced(self, env):309- tmpl = env.from_string('''345+ tmpl = env.from_string(346+ """347 {% macro outer() %}348 {% set i = 1 %}349 {% macro test() %}350 {% for i in range(0, 10) %}{{ i }}{% endfor %}351 {% endmacro %}{{ test() }}352 {% endmacro %}{{ outer() }}316- ''')317- assert tmpl.render().strip() == '0123456789'353+ """354+ )355+ assert tmpl.render().strip() == "0123456789"356 357 def test_callable_defaults(self):358 env = Environment()321- env.globals['get_int'] = lambda: 42322- t = env.from_string('''359+ env.globals["get_int"] = lambda: 42360+ t = env.from_string(361+ """362 {% macro test(a, b, c=get_int()) -%}363 {{ a + b + c }}364 {%- endmacro %}365 {{ test(1, 2) }}|{{ test(1, 2, 3) }}366+ """327- ''')328- assert t.render().strip() == '45|6'367+ )368+ assert t.render().strip() == "45|6"369 370 def test_macro_escaping(self):371 env = Environment(332- autoescape=lambda x: False, extensions=['jinja2.ext.autoescape'])372+ autoescape=lambda x: False, extensions=["jinja2.ext.autoescape"]373+ )374 template = "{% macro m() %}<html>{% endmacro %}"375 template += "{% autoescape true %}{{ m() }}{% endautoescape %}"376 assert env.from_string(template).render()377 378 def test_macro_scoping(self, env):338- tmpl = env.from_string('''379+ tmpl = env.from_string(380+ """381 {% set n=[1,2,3,4,5] %}382 {% for n in [[1,2,3], [3,4,5], [5,6,7]] %}383 384 {% macro x(l) %}3 unmodified lines388 389 {{ x(n) }}390 391 {% endfor %}350- ''')351- assert list(map(int, tmpl.render().split())) == \352- [3, 2, 1, 5, 4, 3, 7, 6, 5]392+ """393+ )394+ assert list(map(int, tmpl.render().split())) == [3, 2, 1, 5, 4, 3, 7, 6, 5]395 396 def test_scopes_and_blocks(self):355- env = Environment(loader=DictLoader({356- 'a.html': '''397+ env = Environment(398+ loader=DictLoader(399+ {400+ "a.html": """401 {%- set foo = 'bar' -%}402 {% include 'x.html' -%}359- ''',360- 'b.html': '''403+ """,404+ "b.html": """405 {%- set foo = 'bar' -%}406 {% block test %}{% include 'x.html' %}{% endblock -%}363- ''',364- 'c.html': '''407+ """,408+ "c.html": """409 {%- set foo = 'bar' -%}410 {% block test %}{% set foo = foo411 %}{% include 'x.html' %}{% endblock -%}368- ''',369- 'x.html': '''{{ foo }}|{{ test }}'''370- }))412+ """,413+ "x.html": """{{ foo }}|{{ test }}""",414+ }415+ )416+ )417 372- a = env.get_template('a.html')373- b = env.get_template('b.html')374- c = env.get_template('c.html')418+ a = env.get_template("a.html")419+ b = env.get_template("b.html")420+ c = env.get_template("c.html")421 376- assert a.render(test='x').strip() == 'bar|x'377- assert b.render(test='x').strip() == 'bar|x'378- assert c.render(test='x').strip() == 'bar|x'422+ assert a.render(test="x").strip() == "bar|x"423+ assert b.render(test="x").strip() == "bar|x"424+ assert c.render(test="x").strip() == "bar|x"425 426 def test_scopes_and_include(self):381- env = Environment(loader=DictLoader({382- 'include.html': '{{ var }}',383- 'base.html': '{% include "include.html" %}',384- 'child.html': '{% extends "base.html" %}{% set var = 42 %}',385- }))386- t = env.get_template('child.html')387- assert t.render() == '42'427+ env = Environment(428+ loader=DictLoader(429+ {430+ "include.html": "{{ var }}",431+ "base.html": '{% include "include.html" %}',432+ "child.html": '{% extends "base.html" %}{% set var = 42 %}',433+ }434+ )435+ )436+ t = env.get_template("child.html")437+ assert t.render() == "42"438 439 def test_caller_scoping(self, env):390- t = env.from_string('''440+ t = env.from_string(441+ """442 {% macro detail(icon, value) -%}443 {% if value -%}444 <p><span class="fa fa-fw fa-{{ icon }}"></span>445 {%- if caller is undefined -%}9 unmodified lines455 {% call(value, href) detail(icon, value, href) -%}456 <a href="{{ href }}">{{ value }}</a>457 {%- endcall %}458 {%- endmacro %}408- ''')459+ """460+ )461 410- assert t.module.link_detail('circle', 'Index', '/') == (411- '<p><span class="fa fa-fw fa-circle">'412- '</span><a href="/">Index</a></p>')462+ assert t.module.link_detail("circle", "Index", "/") == (463+ '<p><span class="fa fa-fw fa-circle"></span><a href="/">Index</a></p>'464+ )465 466 def test_variable_reuse(self, env):415- t = env.from_string('{% for x in x.y %}{{ x }}{% endfor %}')416- assert t.render(x={'y': [0, 1, 2]}) == '012'467+ t = env.from_string("{% for x in x.y %}{{ x }}{% endfor %}")468+ assert t.render(x={"y": [0, 1, 2]}) == "012"469 418- t = env.from_string('{% for x in x.y %}{{ loop.index0 }}|{{ x }}{% endfor %}')419- assert t.render(x={'y': [0, 1, 2]}) == '0|01|12|2'470+ t = env.from_string("{% for x in x.y %}{{ loop.index0 }}|{{ x }}{% endfor %}")471+ assert t.render(x={"y": [0, 1, 2]}) == "0|01|12|2"472 421- t = env.from_string('{% for x in x.y recursive %}{{ x }}{% endfor %}')422- assert t.render(x={'y': [0, 1, 2]}) == '012'473+ t = env.from_string("{% for x in x.y recursive %}{{ x }}{% endfor %}")474+ assert t.render(x={"y": [0, 1, 2]}) == "012"475 476 def test_double_caller(self, env):425- t = env.from_string('{% macro x(caller=none) %}[{% if caller %}'426- '{{ caller() }}{% endif %}]{% endmacro %}'427- '{{ x() }}{% call x() %}aha!{% endcall %}')428- assert t.render() == '[][aha!]'477+ t = env.from_string(478+ "{% macro x(caller=none) %}[{% if caller %}"479+ "{{ caller() }}{% endif %}]{% endmacro %}"480+ "{{ x() }}{% call x() %}aha!{% endcall %}"481+ )482+ assert t.render() == "[][aha!]"483 484 def test_double_caller_no_default(self, env):485 with pytest.raises(TemplateAssertionError) as exc_info:432- env.from_string('{% macro x(caller) %}[{% if caller %}'433- '{{ caller() }}{% endif %}]{% endmacro %}')434- assert exc_info.match(r'"caller" argument must be omitted or '435- r'be given a default')486+ env.from_string(487+ "{% macro x(caller) %}[{% if caller %}"488+ "{{ caller() }}{% endif %}]{% endmacro %}"489+ )490+ assert exc_info.match(491+ r'"caller" argument must be omitted or ' r"be given a default"492+ )493 437- t = env.from_string('{% macro x(caller=none) %}[{% if caller %}'438- '{{ caller() }}{% endif %}]{% endmacro %}')494+ t = env.from_string(495+ "{% macro x(caller=none) %}[{% if caller %}"496+ "{{ caller() }}{% endif %}]{% endmacro %}"497+ )498 with pytest.raises(TypeError) as exc_info:499 t.module.x(None, caller=lambda: 42)441- assert exc_info.match(r'\'x\' was invoked with two values for the '442- r'special caller argument')500+ assert exc_info.match(501+ r"\'x\' was invoked with two values for the " r"special caller argument"502+ )503 504 def test_macro_blocks(self, env):445- t = env.from_string('{% macro x() %}{% block foo %}x{% '446- 'endblock %}{% endmacro %}{{ x() }}')447- assert t.render() == 'x'505+ t = env.from_string(506+ "{% macro x() %}{% block foo %}x{% endblock %}{% endmacro %}{{ x() }}"507+ )508+ assert t.render() == "x"509 510 def test_scoped_block(self, env):450- t = env.from_string('{% set x = 1 %}{% with x = 2 %}{% block y scoped %}'451- '{{ x }}{% endblock %}{% endwith %}')452- assert t.render() == '2'511+ t = env.from_string(512+ "{% set x = 1 %}{% with x = 2 %}{% block y scoped %}"513+ "{{ x }}{% endblock %}{% endwith %}"514+ )515+ assert t.render() == "2"516 517 def test_recursive_loop_filter(self, env):455- t = env.from_string('''518+ t = env.from_string(519+ """520 <?xml version="1.0" encoding="UTF-8"?>521 <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">522 {%- for page in [site.root] if page.url != this recursive %}523 <url><loc>{{ page.url }}</loc></url>524 {{- loop(page.children) }}525 {%- endfor %}526 </urlset>463- ''')464- sm =t.render(this='/foo', site={'root': {465- 'url': '/',466- 'children': [467- {'url': '/foo'},468- {'url': '/bar'},469- ]470- }})527+ """528+ )529+ sm = t.render(530+ this="/foo",531+ site={"root": {"url": "/", "children": [{"url": "/foo"}, {"url": "/bar"}]}},532+ )533 lines = [x.strip() for x in sm.splitlines() if x.strip()]534 assert lines == [535 '<?xml version="1.0" encoding="UTF-8"?>',536 '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">',475- '<url><loc>/</loc></url>',476- '<url><loc>/bar</loc></url>',477- '</urlset>',537+ "<url><loc>/</loc></url>",538+ "<url><loc>/bar</loc></url>",539+ "</urlset>",540 ]541 542 def test_empty_if(self, env):481- t = env.from_string('{% if foo %}{% else %}42{% endif %}')482- assert t.render(foo=False) == '42'543+ t = env.from_string("{% if foo %}{% else %}42{% endif %}")544+ assert t.render(foo=False) == "42"545 546 def test_subproperty_if(self, env):485- t = env.from_string('{% if object1.subproperty1 is eq object2.subproperty2 %}42{% endif %}')486- assert t.render(object1={'subproperty1': 'value'}, object2={'subproperty2': 'value'}) == '42'547+ t = env.from_string(548+ "{% if object1.subproperty1 is eq object2.subproperty2 %}42{% endif %}"549+ )550+ assert (551+ t.render(552+ object1={"subproperty1": "value"}, object2={"subproperty2": "value"}553+ )554+ == "42"555+ )556 557 def test_set_and_include(self):489- env = Environment(loader=DictLoader({490- 'inc': 'bar',491- 'main': '{% set foo = "foo" %}{{ foo }}{% include "inc" %}'492- }))493- assert env.get_template('main').render() == 'foobar'558+ env = Environment(559+ loader=DictLoader(560+ {561+ "inc": "bar",562+ "main": '{% set foo = "foo" %}{{ foo }}{% include "inc" %}',563+ }564+ )565+ )566+ assert env.get_template("main").render() == "foobar"567 568 def test_loop_include(self):496- env = Environment(loader=DictLoader({497- 'inc': '{{ item }}',498- 'main': '{% for item in [1, 2, 3] %}{% include "inc" %}{% endfor %}',499- }))500- assert env.get_template('main').render() == '123'569+ env = Environment(570+ loader=DictLoader(571+ {572+ "inc": "{{ i }}",573+ "main": '{% for i in [1, 2, 3] %}{% include "inc" %}{% endfor %}',574+ }575+ )576+ )577+ assert env.get_template("main").render() == "123"578 579 def test_grouper_repr(self):580 from jinja2.filters import _GroupTuple581+504- t = _GroupTuple('foo', [1, 2])505- assert t.grouper == 'foo'582+ t = _GroupTuple("foo", [1, 2])583+ assert t.grouper == "foo"584 assert t.list == [1, 2]585 assert repr(t) == "('foo', [1, 2])"586 assert str(t) == "('foo', [1, 2])"587 5 unmodified lines593 594 class MyEnvironment(Environment):595 context_class = MyContext596 519- loader = DictLoader({'base': '{{ foobar }}',520- 'test': '{% extends "base" %}'})597+ loader = DictLoader({"base": "{{ foobar }}", "test": '{% extends "base" %}'})598 env = MyEnvironment(loader=loader)522- assert env.get_template('test').render(foobar='test') == 'test'599+ assert env.get_template("test").render(foobar="test") == "test"600 601 def test_legacy_custom_context(self, env):525- from jinja2.runtime import Context, Undefined, missing602+ from jinja2.runtime import Context, missing603 604 class MyContext(Context):605 def resolve(self, name):529- if name == 'foo':606+ if name == "foo":607 return 42608 return super(MyContext, self).resolve(name)609 533- x = MyContext(env, parent={'bar': 23}, name='foo', blocks={})610+ x = MyContext(env, parent={"bar": 23}, name="foo", blocks={})611 assert x._legacy_resolve_mode535- assert x.resolve_or_missing('foo') == 42536- assert x.resolve_or_missing('bar') == 23537- assert x.resolve_or_missing('baz') is missing612+ assert x.resolve_or_missing("foo") == 42613+ assert x.resolve_or_missing("bar") == 23614+ assert x.resolve_or_missing("baz") is missing615 616 def test_recursive_loop_bug(self, env):540- tmpl = env.from_string('''541- {%- for value in values recursive %}1{% else %}0{% endfor -%}542- ''')543- assert tmpl.render(values=[]) == '0'617+ tmpl = env.from_string(618+ "{%- for value in values recursive %}1{% else %}0{% endfor -%}"619+ )620+ assert tmpl.render(values=[]) == "0"621 622 def test_markup_and_chainable_undefined(self):623 from jinja2 import Markup624 from jinja2.runtime import ChainableUndefined625+548- assert str(Markup(ChainableUndefined())) == ''626+ assert str(Markup(ChainableUndefined())) == ""modified:tests/test_runtime.py+14 added-18 removed
1 unmodified line2 3 from jinja2 import Template4 from jinja2.runtime import LoopContext5 6-6 TEST_IDX_TEMPLATE_STR_1 = (8- "[{% for i in lst|reverse %}"9- + "(len={{ loop.length }}, revindex={{ loop.revindex }}, index={{ loop.index }}, val={{ i }})"10- + "{% endfor %}]"7+ "[{% for i in lst|reverse %}(len={{ loop.length }},"8+ " revindex={{ loop.revindex }}, index={{ loop.index }}, val={{ i }}){% endfor %}]"9 )12-13-10 TEST_IDX0_TEMPLATE_STR_1 = (15- "[{% for i in lst|reverse %}"16- + "(len={{ loop.length }}, revindex0={{ loop.revindex0 }}, index0={{ loop.index0 }}, val={{ i }})"17- + "{% endfor %}]"11+ "[{% for i in lst|reverse %}(len={{ loop.length }},"12+ " revindex0={{ loop.revindex0 }}, index0={{ loop.index0 }}, val={{ i }})"13+ "{% endfor %}]"14 )15 16 17 def test_loop_idx():11 unmodified lines29 30 31 def test_loopcontext0():32 in_lst = []37- l = LoopContext(reversed(in_lst), None)38- assert l.length == len(in_lst)33+ lc = LoopContext(reversed(in_lst), None)34+ assert lc.length == len(in_lst)35 36 37 def test_loopcontext1():38 in_lst = [10]43- l = LoopContext(reversed(in_lst), None)44- assert l.length == len(in_lst)39+ lc = LoopContext(reversed(in_lst), None)40+ assert lc.length == len(in_lst)41 42 43 def test_loopcontext2():44 in_lst = [10, 11]49- l = LoopContext(reversed(in_lst), None)50- assert l.length == len(in_lst)45+ lc = LoopContext(reversed(in_lst), None)46+ assert lc.length == len(in_lst)47 48 49 def test_iterator_not_advanced_early():50 t = Template("{% for _, g in gs %}{{ loop.index }} {{ g|list }}\n{% endfor %}")55- out = t.render(gs=itertools.groupby(56- [(1, "a"), (1, "b"), (2, "c"), (3, "d")], lambda x: x[0]57- ))51+ out = t.render(52+ gs=itertools.groupby([(1, "a"), (1, "b"), (2, "c"), (3, "d")], lambda x: x[0])53+ )54 # groupby groups depend on the current position of the iterator. If55 # it was advanced early, the lists would appear empty.56 assert out == "1 [(1, 'a'), (1, 'b')]\n2 [(2, 'c')]\n3 [(3, 'd')]\n"modified:tests/test_security.py+97 added-84 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.security4- ~~~~~~~~~~~~~~~~~~~~~~~~~5-6- Checks the sandbox and other security features.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import pytest3 4 from jinja2 import Environment14-from jinja2.sandbox import SandboxedEnvironment, \15- ImmutableSandboxedEnvironment, unsafe16-from jinja2 import Markup, escape17-from jinja2.exceptions import SecurityError, TemplateSyntaxError, \18- TemplateRuntimeError19-from jinja2.nodes import EvalContext5+from jinja2 import escape6+from jinja2 import Markup7 from jinja2._compat import text_type8+from jinja2.exceptions import SecurityError9+from jinja2.exceptions import TemplateRuntimeError10+from jinja2.exceptions import TemplateSyntaxError11+from jinja2.nodes import EvalContext12+from jinja2.sandbox import ImmutableSandboxedEnvironment13+from jinja2.sandbox import SandboxedEnvironment14+from jinja2.sandbox import unsafe15 16 17 class PrivateStuff(object):24-18 def bar(self):19 return 2320 21 @unsafe22 def foo(self):23 return 4224 25 def __repr__(self):33- return 'PrivateStuff'26+ return "PrivateStuff"27 28 29 class PublicStuff(object):37- bar = lambda self: 2338- _foo = lambda self: 4230+ def bar(self):31+ return 2332 33+ def _foo(self):34+ return 4235+36 def __repr__(self):41- return 'PublicStuff'37+ return "PublicStuff"38 39 40 @pytest.mark.sandbox41 class TestSandbox(object):46-42 def test_unsafe(self, env):43 env = SandboxedEnvironment()49- pytest.raises(SecurityError, env.from_string("{{ foo.foo() }}").render,50- foo=PrivateStuff())51- assert env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff()) == '23'44+ pytest.raises(45+ SecurityError, env.from_string("{{ foo.foo() }}").render, foo=PrivateStuff()46+ )47+ assert env.from_string("{{ foo.bar() }}").render(foo=PrivateStuff()) == "23"48 53- pytest.raises(SecurityError,54- env.from_string("{{ foo._foo() }}").render,55- foo=PublicStuff())56- assert env.from_string("{{ foo.bar() }}").render(foo=PublicStuff()) == '23'57- assert env.from_string("{{ foo.__class__ }}").render(foo=42) == ''58- assert env.from_string("{{ foo.func_code }}").render(foo=lambda:None) == ''49+ pytest.raises(50+ SecurityError, env.from_string("{{ foo._foo() }}").render, foo=PublicStuff()51+ )52+ assert env.from_string("{{ foo.bar() }}").render(foo=PublicStuff()) == "23"53+ assert env.from_string("{{ foo.__class__ }}").render(foo=42) == ""54+ assert env.from_string("{{ foo.func_code }}").render(foo=lambda: None) == ""55 # security error comes from __class__ already.60- pytest.raises(SecurityError, env.from_string(61- "{{ foo.__class__.__subclasses__() }}").render, foo=42)56+ pytest.raises(57+ SecurityError,58+ env.from_string("{{ foo.__class__.__subclasses__() }}").render,59+ foo=42,60+ )61 62 def test_immutable_environment(self, env):63 env = ImmutableSandboxedEnvironment()65- pytest.raises(SecurityError, env.from_string(66- '{{ [].append(23) }}').render)67- pytest.raises(SecurityError, env.from_string(68- '{{ {1:2}.clear() }}').render)64+ pytest.raises(SecurityError, env.from_string("{{ [].append(23) }}").render)65+ pytest.raises(SecurityError, env.from_string("{{ {1:2}.clear() }}").render)66 67 def test_restricted(self, env):68 env = SandboxedEnvironment()72- pytest.raises(TemplateSyntaxError, env.from_string,73- "{% for item.attribute in seq %}...{% endfor %}")74- pytest.raises(TemplateSyntaxError, env.from_string,75- "{% for foo, bar.baz in seq %}...{% endfor %}")69+ pytest.raises(70+ TemplateSyntaxError,71+ env.from_string,72+ "{% for item.attribute in seq %}...{% endfor %}",73+ )74+ pytest.raises(75+ TemplateSyntaxError,76+ env.from_string,77+ "{% for foo, bar.baz in seq %}...{% endfor %}",78+ )79 80 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>'80- safe = Markup('<em>username</em>')83+ safe = Markup("<em>username</em>")84 assert unsafe + safe == text_type(escape(unsafe)) + text_type(safe)85 86 # string interpolations are safe to use too84- assert Markup('<em>%s</em>') % '<bad user>' == \85- '<em><bad user></em>'86- assert Markup('<em>%(username)s</em>') % {87- 'username': '<bad user>'88- } == '<em><bad user></em>'87+ assert Markup("<em>%s</em>") % "<bad user>" == "<em><bad user></em>"88+ assert (89+ Markup("<em>%(username)s</em>") % {"username": "<bad user>"}90+ == "<em><bad user></em>"91+ )92 93 # an escaped object is markup too91- assert type(Markup('foo') + 'bar') is Markup94+ assert type(Markup("foo") + "bar") is Markup95 96 # and it implements __html__ by returning itself97 x = Markup("foo")98 assert x.__html__() is x99 100 # it also knows how to treat __html__ objects101 class Foo(object):102 def __html__(self):100- return '<em>awesome</em>'103+ return "<em>awesome</em>"104 105 def __unicode__(self):103- return 'awesome'104- assert Markup(Foo()) == '<em>awesome</em>'105- assert Markup('<strong>%s</strong>') % Foo() == \106- '<strong><em>awesome</em></strong>'106+ return "awesome"107 108+ assert Markup(Foo()) == "<em>awesome</em>"109+ assert (110+ Markup("<strong>%s</strong>") % Foo() == "<strong><em>awesome</em></strong>"111+ )112+113 # escaping and unescaping109- assert escape('"<>&\'') == '"<>&''114+ assert escape("\"<>&'") == ""<>&'"115 assert Markup("<em>Foo & Bar</em>").striptags() == "Foo & Bar"116 assert Markup("<test>").unescape() == "<test>"117 118 def test_template_data(self, env):119 env = Environment(autoescape=True)115- t = env.from_string('{% macro say_hello(name) %}'116- '<p>Hello {{ name }}!</p>{% endmacro %}'117- '{{ say_hello("<blink>foo</blink>") }}')118- escaped_out = '<p>Hello <blink>foo</blink>!</p>'120+ t = env.from_string(121+ "{% macro say_hello(name) %}"122+ "<p>Hello {{ name }}!</p>{% endmacro %}"123+ '{{ say_hello("<blink>foo</blink>") }}'124+ )125+ escaped_out = "<p>Hello <blink>foo</blink>!</p>"126 assert t.render() == escaped_out127 assert text_type(t.module) == escaped_out128 assert escape(t.module) == escaped_out122- assert t.module.say_hello('<blink>foo</blink>') == escaped_out123- assert escape(t.module.say_hello(124- EvalContext(env), '<blink>foo</blink>')) == escaped_out125- assert escape(t.module.say_hello(126- '<blink>foo</blink>')) == escaped_out129+ assert t.module.say_hello("<blink>foo</blink>") == escaped_out130+ assert (131+ escape(t.module.say_hello(EvalContext(env), "<blink>foo</blink>"))132+ == escaped_out133+ )134+ assert escape(t.module.say_hello("<blink>foo</blink>")) == escaped_out135 136 def test_attr_filter(self, env):137 env = SandboxedEnvironment()138 tmpl = env.from_string('{{ cls|attr("__subclasses__")() }}')139 pytest.raises(SecurityError, tmpl.render, cls=int)140 141 def test_binary_operator_intercepting(self, env):142 def disable_op(left, right):135- raise TemplateRuntimeError('that operator so does not work')136- for expr, ctx, rv in ('1 + 2', {}, '3'), ('a + 2', {'a': 2}, '4'):143+ raise TemplateRuntimeError("that operator so does not work")144+145+ for expr, ctx, rv in ("1 + 2", {}, "3"), ("a + 2", {"a": 2}, "4"):146 env = SandboxedEnvironment()138- env.binop_table['+'] = disable_op139- t = env.from_string('{{ %s }}' % expr)147+ env.binop_table["+"] = disable_op148+ t = env.from_string("{{ %s }}" % expr)149 assert t.render(ctx) == rv141- env.intercepted_binops = frozenset(['+'])142- t = env.from_string('{{ %s }}' % expr)150+ env.intercepted_binops = frozenset(["+"])151+ t = env.from_string("{{ %s }}" % expr)152 with pytest.raises(TemplateRuntimeError):153 t.render(ctx)154 155 def test_unary_operator_intercepting(self, env):156 def disable_op(arg):148- raise TemplateRuntimeError('that operator so does not work')149- for expr, ctx, rv in ('-1', {}, '-1'), ('-a', {'a': 2}, '-2'):157+ raise TemplateRuntimeError("that operator so does not work")158+159+ for expr, ctx, rv in ("-1", {}, "-1"), ("-a", {"a": 2}, "-2"):160 env = SandboxedEnvironment()151- env.unop_table['-'] = disable_op152- t = env.from_string('{{ %s }}' % expr)161+ env.unop_table["-"] = disable_op162+ t = env.from_string("{{ %s }}" % expr)163 assert t.render(ctx) == rv154- env.intercepted_unops = frozenset(['-'])155- t = env.from_string('{{ %s }}' % expr)164+ env.intercepted_unops = frozenset(["-"])165+ t = env.from_string("{{ %s }}" % expr)166 with pytest.raises(TemplateRuntimeError):167 t.render(ctx)168 169 170 @pytest.mark.sandbox171 class TestStringFormat(object):162-172 def test_basic_format_safety(self):173 env = SandboxedEnvironment()174 t = env.from_string('{{ "a{0.__class__}b".format(42) }}')166- assert t.render() == 'ab'175+ assert t.render() == "ab"176 177 def test_basic_format_all_okay(self):178 env = SandboxedEnvironment()179 t = env.from_string('{{ "a{0.foo}b".format({"foo": 42}) }}')171- assert t.render() == 'a42b'180+ assert t.render() == "a42b"181 182 def test_safe_format_safety(self):183 env = SandboxedEnvironment()184 t = env.from_string('{{ ("a{0.__class__}b{1}"|safe).format(42, "<foo>") }}')176- assert t.render() == 'ab<foo>'185+ assert t.render() == "ab<foo>"186 187 def test_safe_format_all_okay(self):188 env = SandboxedEnvironment()189 t = env.from_string('{{ ("a{0.foo}b{1}"|safe).format({"foo": 42}, "<foo>") }}')181- assert t.render() == 'a42b<foo>'190+ assert t.render() == "a42b<foo>"191 192 193 @pytest.mark.sandbox185-@pytest.mark.skipif(not hasattr(str, 'format_map'), reason='requires str.format_map method')194+@pytest.mark.skipif(195+ not hasattr(str, "format_map"), reason="requires str.format_map method"196+)197 class TestStringFormatMap(object):198 def test_basic_format_safety(self):199 env = SandboxedEnvironment()200 t = env.from_string('{{ "a{x.__class__}b".format_map({"x":42}) }}')190- assert t.render() == 'ab'201+ assert t.render() == "ab"202 203 def test_basic_format_all_okay(self):204 env = SandboxedEnvironment()205 t = env.from_string('{{ "a{x.foo}b".format_map({"x":{"foo": 42}}) }}')195- assert t.render() == 'a42b'206+ assert t.render() == "a42b"207 208 def test_safe_format_all_okay(self):209 env = SandboxedEnvironment()199- t = env.from_string('{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}')200- assert t.render() == 'a42b<foo>'210+ t = env.from_string(211+ '{{ ("a{x.foo}b{y}"|safe).format_map({"x":{"foo": 42}, "y":"<foo>"}) }}'212+ )213+ assert t.render() == "a42b<foo>"modified:tests/test_tests.py+157 added-166 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.tests4- ~~~~~~~~~~~~~~~~~~~~~~5-6- Who tests the tests?7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""2 import pytest3 13-from jinja2 import Markup, Environment4+from jinja2 import Environment5+from jinja2 import Markup6 7+8 class MyDict(dict):9 pass10 11+12 @pytest.mark.test_tests13 class TestTestsCase(object):20-14 def test_defined(self, env):22- tmpl = env.from_string('{{ missing is defined }}|'23- '{{ true is defined }}')24- assert tmpl.render() == 'False|True'15+ tmpl = env.from_string("{{ missing is defined }}|{{ true is defined }}")16+ assert tmpl.render() == "False|True"17 18 def test_even(self, env):27- tmpl = env.from_string('''{{ 1 is even }}|{{ 2 is even }}''')28- assert tmpl.render() == 'False|True'19+ tmpl = env.from_string("""{{ 1 is even }}|{{ 2 is even }}""")20+ assert tmpl.render() == "False|True"21 22 def test_odd(self, env):31- tmpl = env.from_string('''{{ 1 is odd }}|{{ 2 is odd }}''')32- assert tmpl.render() == 'True|False'23+ tmpl = env.from_string("""{{ 1 is odd }}|{{ 2 is odd }}""")24+ assert tmpl.render() == "True|False"25 26 def test_lower(self, env):35- tmpl = env.from_string('''{{ "foo" is lower }}|{{ "FOO" is lower }}''')36- assert tmpl.render() == 'True|False'27+ tmpl = env.from_string("""{{ "foo" is lower }}|{{ "FOO" is lower }}""")28+ assert tmpl.render() == "True|False"29 30 # Test type checks39- @pytest.mark.parametrize('op,expect', (40- ('none is none', True),41- ('false is none', False),42- ('true is none', False),43- ('42 is none', False),44-45- ('none is true', False),46- ('false is true', False),47- ('true is true', True),48- ('0 is true', False),49- ('1 is true', False),50- ('42 is true', False),51-52- ('none is false', False),53- ('false is false', True),54- ('true is false', False),55- ('0 is false', False),56- ('1 is false', False),57- ('42 is false', False),58-59- ('none is boolean', False),60- ('false is boolean', True),61- ('true is boolean', True),62- ('0 is boolean', False),63- ('1 is boolean', False),64- ('42 is boolean', False),65- ('0.0 is boolean', False),66- ('1.0 is boolean', False),67- ('3.14159 is boolean', False),68-69- ('none is integer', False),70- ('false is integer', False),71- ('true is integer', False),72- ('42 is integer', True),73- ('3.14159 is integer', False),74- ('(10 ** 100) is integer', True),75-76- ('none is float', False),77- ('false is float', False),78- ('true is float', False),79- ('42 is float', False),80- ('4.2 is float', True),81- ('(10 ** 100) is float', False),82-83- ('none is number', False),84- ('false is number', True),85- ('true is number', True),86- ('42 is number', True),87- ('3.14159 is number', True),88- ('complex is number', True),89- ('(10 ** 100) is number', True),90-91- ('none is string', False),92- ('false is string', False),93- ('true is string', False),94- ('42 is string', False),95- ('"foo" is string', True),96-97- ('none is sequence', False),98- ('false is sequence', False),99- ('42 is sequence', False),100- ('"foo" is sequence', True),101- ('[] is sequence', True),102- ('[1, 2, 3] is sequence', True),103- ('{} is sequence', True),104-105- ('none is mapping', False),106- ('false is mapping', False),107- ('42 is mapping', False),108- ('"foo" is mapping', False),109- ('[] is mapping', False),110- ('{} is mapping', True),111- ('mydict is mapping', True),112-113- ('none is iterable', False),114- ('false is iterable', False),115- ('42 is iterable', False),116- ('"foo" is iterable', True),117- ('[] is iterable', True),118- ('{} is iterable', True),119- ('range(5) is iterable', True),120-121- ('none is callable', False),122- ('false is callable', False),123- ('42 is callable', False),124- ('"foo" is callable', False),125- ('[] is callable', False),126- ('{} is callable', False),127- ('range is callable', True),128- ))31+ @pytest.mark.parametrize(32+ "op,expect",33+ (34+ ("none is none", True),35+ ("false is none", False),36+ ("true is none", False),37+ ("42 is none", False),38+ ("none is true", False),39+ ("false is true", False),40+ ("true is true", True),41+ ("0 is true", False),42+ ("1 is true", False),43+ ("42 is true", False),44+ ("none is false", False),45+ ("false is false", True),46+ ("true is false", False),47+ ("0 is false", False),48+ ("1 is false", False),49+ ("42 is false", False),50+ ("none is boolean", False),51+ ("false is boolean", True),52+ ("true is boolean", True),53+ ("0 is boolean", False),54+ ("1 is boolean", False),55+ ("42 is boolean", False),56+ ("0.0 is boolean", False),57+ ("1.0 is boolean", False),58+ ("3.14159 is boolean", False),59+ ("none is integer", False),60+ ("false is integer", False),61+ ("true is integer", False),62+ ("42 is integer", True),63+ ("3.14159 is integer", False),64+ ("(10 ** 100) is integer", True),65+ ("none is float", False),66+ ("false is float", False),67+ ("true is float", False),68+ ("42 is float", False),69+ ("4.2 is float", True),70+ ("(10 ** 100) is float", False),71+ ("none is number", False),72+ ("false is number", True),73+ ("true is number", True),74+ ("42 is number", True),75+ ("3.14159 is number", True),76+ ("complex is number", True),77+ ("(10 ** 100) is number", True),78+ ("none is string", False),79+ ("false is string", False),80+ ("true is string", False),81+ ("42 is string", False),82+ ('"foo" is string', True),83+ ("none is sequence", False),84+ ("false is sequence", False),85+ ("42 is sequence", False),86+ ('"foo" is sequence', True),87+ ("[] is sequence", True),88+ ("[1, 2, 3] is sequence", True),89+ ("{} is sequence", True),90+ ("none is mapping", False),91+ ("false is mapping", False),92+ ("42 is mapping", False),93+ ('"foo" is mapping', False),94+ ("[] is mapping", False),95+ ("{} is mapping", True),96+ ("mydict is mapping", True),97+ ("none is iterable", False),98+ ("false is iterable", False),99+ ("42 is iterable", False),100+ ('"foo" is iterable', True),101+ ("[] is iterable", True),102+ ("{} is iterable", True),103+ ("range(5) is iterable", True),104+ ("none is callable", False),105+ ("false is callable", False),106+ ("42 is callable", False),107+ ('"foo" is callable', False),108+ ("[] is callable", False),109+ ("{} is callable", False),110+ ("range is callable", True),111+ ),112+ )113 def test_types(self, env, op, expect):130- t = env.from_string('{{{{ {op} }}}}'.format(op=op))114+ t = env.from_string("{{{{ {op} }}}}".format(op=op))115 assert t.render(mydict=MyDict(), complex=complex(1, 2)) == str(expect)116 133-117 def test_upper(self, env):118 tmpl = env.from_string('{{ "FOO" is upper }}|{{ "foo" is upper }}')136- assert tmpl.render() == 'True|False'119+ assert tmpl.render() == "True|False"120 121 def test_equalto(self, env):122 tmpl = env.from_string(140- '{{ foo is eq 12 }}|'141- '{{ foo is eq 0 }}|'142- '{{ foo is eq (3 * 4) }}|'123+ "{{ foo is eq 12 }}|"124+ "{{ foo is eq 0 }}|"125+ "{{ foo is eq (3 * 4) }}|"126 '{{ bar is eq "baz" }}|'127 '{{ bar is eq "zab" }}|'128 '{{ bar is eq ("ba" + "z") }}|'146- '{{ bar is eq bar }}|'147- '{{ bar is eq foo }}'129+ "{{ bar is eq bar }}|"130+ "{{ bar is eq foo }}"131 )149- assert tmpl.render(foo=12, bar="baz") \150- == 'True|False|True|True|False|True|True|False'132+ assert (133+ tmpl.render(foo=12, bar="baz")134+ == "True|False|True|True|False|True|True|False"135+ )136 152- @pytest.mark.parametrize('op,expect', (153- ('eq 2', True),154- ('eq 3', False),155- ('ne 3', True),156- ('ne 2', False),157- ('lt 3', True),158- ('lt 2', False),159- ('le 2', True),160- ('le 1', False),161- ('gt 1', True),162- ('gt 2', False),163- ('ge 2', True),164- ('ge 3', False),165- ))137+ @pytest.mark.parametrize(138+ "op,expect",139+ (140+ ("eq 2", True),141+ ("eq 3", False),142+ ("ne 3", True),143+ ("ne 2", False),144+ ("lt 3", True),145+ ("lt 2", False),146+ ("le 2", True),147+ ("le 1", False),148+ ("gt 1", True),149+ ("gt 2", False),150+ ("ge 2", True),151+ ("ge 3", False),152+ ),153+ )154 def test_compare_aliases(self, env, op, expect):167- t = env.from_string('{{{{ 2 is {op} }}}}'.format(op=op))155+ t = env.from_string("{{{{ 2 is {op} }}}}".format(op=op))156 assert t.render() == str(expect)157 158 def test_sameas(self, env):171- tmpl = env.from_string('{{ foo is sameas false }}|'172- '{{ 0 is sameas false }}')173- assert tmpl.render(foo=False) == 'True|False'159+ tmpl = env.from_string("{{ foo is sameas false }}|{{ 0 is sameas false }}")160+ assert tmpl.render(foo=False) == "True|False"161 162 def test_no_paren_for_arg1(self, env):176- tmpl = env.from_string('{{ foo is sameas none }}')177- assert tmpl.render(foo=None) == 'True'163+ tmpl = env.from_string("{{ foo is sameas none }}")164+ assert tmpl.render(foo=None) == "True"165 166 def test_escaped(self, env):167 env = Environment(autoescape=True)181- tmpl = env.from_string('{{ x is escaped }}|{{ y is escaped }}')182- assert tmpl.render(x='foo', y=Markup('foo')) == 'False|True'168+ tmpl = env.from_string("{{ x is escaped }}|{{ y is escaped }}")169+ assert tmpl.render(x="foo", y=Markup("foo")) == "False|True"170 171 def test_greaterthan(self, env):185- tmpl = env.from_string('{{ 1 is greaterthan 0 }}|'186- '{{ 0 is greaterthan 1 }}')187- assert tmpl.render() == 'True|False'172+ tmpl = env.from_string("{{ 1 is greaterthan 0 }}|{{ 0 is greaterthan 1 }}")173+ assert tmpl.render() == "True|False"174 175 def test_lessthan(self, env):190- tmpl = env.from_string('{{ 0 is lessthan 1 }}|'191- '{{ 1 is lessthan 0 }}')192- assert tmpl.render() == 'True|False'176+ tmpl = env.from_string("{{ 0 is lessthan 1 }}|{{ 1 is lessthan 0 }}")177+ assert tmpl.render() == "True|False"178 179 def test_multiple_tests(self):180 items = []181+182 def matching(x, y):183 items.append((x, y))184 return False185+186 env = Environment()200- env.tests['matching'] = matching201- tmpl = env.from_string("{{ 'us-west-1' is matching "202- "'(us-east-1|ap-northeast-1)' "203- "or 'stage' is matching '(dev|stage)' }}")204- assert tmpl.render() == 'False'205- assert items == [('us-west-1', '(us-east-1|ap-northeast-1)'),206- ('stage', '(dev|stage)')]187+ env.tests["matching"] = matching188+ tmpl = env.from_string(189+ "{{ 'us-west-1' is matching '(us-east-1|ap-northeast-1)'"190+ " or 'stage' is matching '(dev|stage)' }}"191+ )192+ assert tmpl.render() == "False"193+ assert items == [194+ ("us-west-1", "(us-east-1|ap-northeast-1)"),195+ ("stage", "(dev|stage)"),196+ ]197 198 def test_in(self, env):209- tmpl = env.from_string('{{ "o" is in "foo" }}|'210- '{{ "foo" is in "foo" }}|'211- '{{ "b" is in "foo" }}|'212- '{{ 1 is in ((1, 2)) }}|'213- '{{ 3 is in ((1, 2)) }}|'214- '{{ 1 is in [1, 2] }}|'215- '{{ 3 is in [1, 2] }}|'216- '{{ "foo" is in {"foo": 1}}}|'217- '{{ "baz" is in {"bar": 1}}}')218- assert tmpl.render() \219- == 'True|True|False|True|False|True|False|True|False'199+ tmpl = env.from_string(200+ '{{ "o" is in "foo" }}|'201+ '{{ "foo" is in "foo" }}|'202+ '{{ "b" is in "foo" }}|'203+ "{{ 1 is in ((1, 2)) }}|"204+ "{{ 3 is in ((1, 2)) }}|"205+ "{{ 1 is in [1, 2] }}|"206+ "{{ 3 is in [1, 2] }}|"207+ '{{ "foo" is in {"foo": 1}}}|'208+ '{{ "baz" is in {"bar": 1}}}'209+ )210+ assert tmpl.render() == "True|True|False|True|False|True|False|True|False"modified:tests/test_utils.py+60 added-62 removed
1 # -*- coding: utf-8 -*-2-"""3- jinja2.testsuite.utils4- ~~~~~~~~~~~~~~~~~~~~~~5-6- Tests utilities jinja uses.7-8- :copyright: (c) 2017 by the Jinja Team.9- :license: BSD, see LICENSE for more details.10-"""11-12-from collections import deque13-from copy import copy as shallow_copy2 import pickle3 import random4+from collections import deque5+from copy import copy as shallow_copy6 7 import pytest18-19-from jinja2._compat import string_types, range_type20-from jinja2.utils import LRUCache, object_type_repr, urlize, \21- select_autoescape, generate_lorem_ipsum, missing, consume8 from markupsafe import Markup9 10+from jinja2._compat import range_type11+from jinja2._compat import string_types12+from jinja2.utils import consume13+from jinja2.utils import generate_lorem_ipsum14+from jinja2.utils import LRUCache15+from jinja2.utils import missing16+from jinja2.utils import object_type_repr17+from jinja2.utils import select_autoescape18+from jinja2.utils import urlize19 20+21 @pytest.mark.utils22 @pytest.mark.lrucache23 class TestLRUCache(object):28-24 def test_simple(self):25 d = LRUCache(3)26 d["a"] = 127 d["b"] = 228 d["c"] = 329 d["a"]30 d["d"] = 431 assert len(d) == 337- assert 'a' in d and 'c' in d and 'd' in d and 'b' not in d32+ assert "a" in d and "c" in d and "d" in d and "b" not in d33 34 def test_itervalue_deprecated(self):35 cache = LRUCache(3)36 cache["a"] = 14 unmodified lines41 def test_itervalues(self):42 cache = LRUCache(3)43 cache["b"] = 144 cache["a"] = 250- values = [v for v in cache.itervalues()]45+ values = [v for v in cache.values()]46 assert len(values) == 247 assert 1 in values48 assert 2 in values49 50 def test_itervalues_empty(self):51 cache = LRUCache(2)57- values = [v for v in cache.itervalues()]52+ values = [v for v in cache.values()]53 assert len(values) == 054 55 def test_pickleable(self):56 cache = LRUCache(2)9 unmodified lines66 67 @pytest.mark.parametrize("copy_func", [LRUCache.copy, shallow_copy])68 def test_copy(self, copy_func):69 cache = LRUCache(2)75- cache['a'] = 176- cache['b'] = 270+ cache["a"] = 171+ cache["b"] = 272 copy = copy_func(cache)73 assert copy._queue == cache._queue79- copy['c'] = 374+ copy["c"] = 375 assert copy._queue != cache._queue81- assert 'a' not in copy and 'b' in copy and 'c' in copy76+ assert "a" not in copy and "b" in copy and "c" in copy77 78 def test_clear(self):79 d = LRUCache(3)80 d["a"] = 181 d["b"] = 282 d["c"] = 383 d.clear()89- assert d.__getstate__() == {'capacity': 3, '_mapping': {}, '_queue': deque([])}84+ assert d.__getstate__() == {"capacity": 3, "_mapping": {}, "_queue": deque([])}85 86 def test_repr(self):87 d = LRUCache(3)88 d["a"] = 17 unmodified lines96 d = LRUCache(3)97 d["a"] = 198 d["b"] = 299 d["c"] = 3105- assert d.items() == list(d.iteritems()) == [('c', 3), ('b', 2), ('a', 1)]106- assert d.keys() == list(d.iterkeys()) == ['c', 'b', 'a']107- assert d.values() == list(d.itervalues()) == [3, 2, 1]108- assert list(reversed(d)) == ['a', 'b', 'c']100+ assert d.items() == [("c", 3), ("b", 2), ("a", 1)]101+ assert d.keys() == ["c", "b", "a"]102+ assert d.values() == [3, 2, 1]103+ assert list(reversed(d)) == ["a", "b", "c"]104 105 # Change the cache a little106 d["b"]107 d["a"] = 4113- assert d.items() == list(d.iteritems()) == [('a', 4), ('b', 2), ('c', 3)]114- assert d.keys() == list(d.iterkeys()) == ['a', 'b', 'c']115- assert d.values() == list(d.itervalues()) == [4, 2, 3]116- assert list(reversed(d)) == ['c', 'b', 'a']108+ assert d.items() == [("a", 4), ("b", 2), ("c", 3)]109+ assert d.keys() == ["a", "b", "c"]110+ assert d.values() == [4, 2, 3]111+ assert list(reversed(d)) == ["c", "b", "a"]112 113 def test_setdefault(self):114 d = LRUCache(3)115 assert len(d) == 06 unmodified lines122 123 @pytest.mark.utils124 @pytest.mark.helpers125 class TestHelpers(object):131-126 def test_object_type_repr(self):127 class X(object):128 pass135- assert object_type_repr(42) == 'int object'136- assert object_type_repr([]) == 'list object'137- assert object_type_repr(X()) == 'test_utils.X object'138- assert object_type_repr(None) == 'None'139- assert object_type_repr(Ellipsis) == 'Ellipsis'129 130+ assert object_type_repr(42) == "int object"131+ assert object_type_repr([]) == "list object"132+ assert object_type_repr(X()) == "test_utils.X object"133+ assert object_type_repr(None) == "None"134+ assert object_type_repr(Ellipsis) == "Ellipsis"135+136 def test_autoescape_select(self):137 func = select_autoescape(143- enabled_extensions=('html', '.htm'),144- disabled_extensions=('txt',),145- default_for_string='STRING',146- default='NONE',138+ enabled_extensions=("html", ".htm"),139+ disabled_extensions=("txt",),140+ default_for_string="STRING",141+ default="NONE",142 )143 149- assert func(None) == 'STRING'150- assert func('unknown.foo') == 'NONE'151- assert func('foo.html') == True152- assert func('foo.htm') == True153- assert func('foo.txt') == False154- assert func('FOO.HTML') == True155- assert func('FOO.TXT') == False144+ assert func(None) == "STRING"145+ assert func("unknown.foo") == "NONE"146+ assert func("foo.html")147+ assert func("foo.htm")148+ assert not func("foo.txt")149+ assert func("FOO.HTML")150+ assert not func("FOO.TXT")151 152 153 @pytest.mark.utils154 @pytest.mark.escapeUrlizeTarget155 class TestEscapeUrlizeTarget(object):156 def test_escape_urlize_target(self):157 url = "http://example.org"158 target = "<script>"164- assert urlize(url, target=target) == ('<a href="http://example.org"'165- ' target="<script>">'166- 'http://example.org</a>')159+ assert urlize(url, target=target) == (160+ '<a href="http://example.org"'161+ ' target="<script>">'162+ "http://example.org</a>"163+ )164 165 166 @pytest.mark.utils167 @pytest.mark.loremIpsum7 unmodified lines175 assert isinstance(generate_lorem_ipsum(html=False), string_types)176 177 def test_lorem_ipsum_n(self):178 """Test that the n (number of lines) works as expected."""182- assert generate_lorem_ipsum(n=0, html=False) == u''179+ assert generate_lorem_ipsum(n=0, html=False) == u""180 for n in range_type(1, 50):184- assert generate_lorem_ipsum(n=n, html=False).count('\n') == (n - 1) * 2181+ assert generate_lorem_ipsum(n=n, html=False).count("\n") == (n - 1) * 2182 183 def test_lorem_ipsum_min(self):184 """Test that at least min words are in the output of each line"""185 for _ in range_type(5):189- m = random.randrange(20, 99)190- for _ in range_type(10):191- assert generate_lorem_ipsum(n=1, min=m, html=False).count(' ') >= m - 1186+ m = random.randrange(20, 99)187+ for _ in range_type(10):188+ assert generate_lorem_ipsum(n=1, min=m, html=False).count(" ") >= m - 1189 190 def test_lorem_ipsum_max(self):191 """Test that at least max words are in the output of each line"""192 for _ in range_type(5):196- m = random.randrange(21, 100)197- for _ in range_type(10):198- assert generate_lorem_ipsum(n=1, max=m, html=False).count(' ') < m - 1193+ m = random.randrange(21, 100)194+ for _ in range_type(10):195+ assert generate_lorem_ipsum(n=1, max=m, html=False).count(" ") < m - 1196 197 198 def test_missing():199 """Test the repr of missing."""203- assert repr(missing) == u'missing'200+ assert repr(missing) == u"missing"201 202+203 def test_consume():204 """Test that consume consumes an iterator."""205 x = iter([1, 2, 3, 4, 5])206 consume(x)2 unmodified linesmodified:.azure-pipelines.yml+16 added-11 removed
2 unmodified lines3 - '*.x'4 5 variables:6 vmImage: ubuntu-latest7- python.version: 3.77+ python.version: '3.8'8 TOXENV: py,coverage-ci9- hasTestResults: true9+ hasTestResults: 'true'10 11 strategy:12 matrix:13- Python 3.7 Linux:13+ Python 3.8 Linux:14 vmImage: ubuntu-latest15- Python 3.7 Windows:15+ Python 3.8 Windows:16 vmImage: windows-latest17- Python 3.7 Mac:17+ Python 3.8 Mac:18 vmImage: macos-latest19 PyPy 3 Linux:20 python.version: pypy321+ Python 3.7 Linux:22+ python.version: '3.7'23 Python 3.6 Linux:22- python.version: 3.624+ python.version: '3.6'25 Python 3.5 Linux:24- python.version: 3.526+ python.version: '3.5'27 Python 2.7 Linux:26- python.version: 2.728+ python.version: '2.7'29 Python 2.7 Windows:28- python.version: 2.730+ python.version: '2.7'31 vmImage: windows-latest32 Docs:31- TOXENV: docs-html32- hasTestResults: false33+ TOXENV: docs34+ hasTestResults: 'false'35+ Style:36+ TOXENV: style37+ hasTestResults: 'false'38 39 pool:40 vmImage: $[ variables.vmImage ]41 25 unmodified linesadded:.pre-commit-config.yaml+21 added
1+repos:2+ - repo: https://github.com/asottile/reorder_python_imports3+ rev: v1.9.04+ hooks:5+ - id: reorder-python-imports6+ args: ["--application-directories", "src"]7+ - repo: https://github.com/ambv/black8+ rev: 19.10b09+ hooks:10+ - id: black11+ - repo: https://gitlab.com/pycqa/flake812+ rev: 3.7.913+ hooks:14+ - id: flake815+ additional_dependencies: [flake8-bugbear]16+ - repo: https://github.com/pre-commit/pre-commit-hooks17+ rev: v2.4.018+ hooks:19+ - id: check-byte-order-marker20+ - id: trailing-whitespace21+ - id: end-of-file-fixermodified:setup.cfg+25 added
4 unmodified lines5 universal = true6 7 [tool:pytest]8 testpaths = tests9+filterwarnings =10+ error11+ ignore:the sets module:DeprecationWarning:jinja2.sandbox12 13 [coverage:run]14 branch = True15 source =4 unmodified lines20 source =21 src/jinja222 .tox/*/lib/python*/site-packages/jinja223 .tox/*/site-packages/jinja224+25+[flake8]26+# B = bugbear27+# E = pycodestyle errors28+# F = flake8 pyflakes29+# W = pycodestyle warnings30+# B9 = bugbear opinions31+select = B, E, F, W, B932+ignore =33+ # slice notation whitespace, invalid34+ E20335+ # line length, handled by bugbear B95036+ E50137+ # bare except, handled by bugbear B00138+ E72239+ # bin op line break, invalid40+ W50341+# up to 88 allowed by bugbear B95042+max-line-length = 8043+per-file-ignores =44+ # __init__ module exports names45+ src/jinja2/__init__.py: F401modified:setup.py+4 added-3 removed
5 unmodified lines6 7 with io.open("README.rst", "rt", encoding="utf8") as f:8 readme = f.read()9 10-with io.open("jinja2/__init__.py", "rt", encoding="utf8") as f:10+with io.open("src/jinja2/__init__.py", "rt", encoding="utf8") as f:11 version = re.search(r'__version__ = "(.*?)"', f.read(), re.M).group(1)12 13 setup(14 name="Jinja2",29 unmodified lines44 "Topic :: Internet :: WWW/HTTP :: Dynamic Content",45 "Topic :: Software Development :: Libraries :: Python Modules",46 "Topic :: Text Processing :: Markup :: HTML",47 ],48- packages=find_packages(),49- python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",48+ packages=find_packages("src"),49+ package_dir={"": "src"},50 include_package_data=True,51+ python_requires=">=2.7, !=3.0.*, !=3.1.*, !=3.2.*, !=3.3.*, !=3.4.*",52 install_requires=["MarkupSafe>=0.23"],53 extras_require={"i18n": ["Babel>=0.8"]},54 entry_points={"babel.extractors": ["jinja2 = jinja2.ext:babel_extract[i18n]"]},55 )modified:tox.ini+12 added-10 removed
1 [tox]2 envlist =3- py{37,36,35,27,py3,py}4- docs-html3+ py{38,37,36,35,27,py3,py}4+ style5+ docs6 coverage7 skip_missing_interpreters = true8 9 [testenv]10 deps =11 coverage12 pytest12-commands = coverage run -p -m pytest --tb=short -Werror --basetemp={envtmpdir} {posargs}13+commands = coverage run -p -m pytest --tb=short --basetemp={envtmpdir} {posargs}14 14-[testenv:docs-html]15-deps =16- Sphinx17- Pallets-Sphinx-Themes18- sphinxcontrib-log-cabinet19- sphinx-issues20-commands = sphinx-build -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html15+[testenv:style]16+deps = pre-commit17+skip_install = true18+commands = pre-commit run --all-files --show-diff-on-failure19 20+[testenv:docs]21+deps = -r docs/requirements.txt22+commands = sphinx-build -W -b html -d {envtmpdir}/doctrees docs {envtmpdir}/html23+24 [testenv:coverage]25 deps = coverage26 skip_install = true27 commands =11 unmodified lines