Skip to content
Myr

remove old scripts and examples

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

authored by David Lord · committed by David Lord · parent 143667d · Browse files · 33 files+171 added−2736 removed
This commit

State

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

Diff stats

33 files+171 added−2736 removed

  • other:+171 added−2736 removed

33 files+171 added−2736 removed

added:docs/examples/cache_extension.py+54 added
1from jinja2 import nodes2from jinja2.ext import Extension345class FragmentCacheExtension(Extension):6 # a set of names that trigger the extension.7 tags = {"cache"}89 def __init__(self, environment):10 super(FragmentCacheExtension, self).__init__(environment)1112 # add the defaults to the environment13 environment.extend(fragment_cache_prefix="", fragment_cache=None)1415 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).lineno2122 # now we parse a single expression that is used as cache key.23 args = [parser.parse_expression()]2425 # 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))3132 # 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)3536 # 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)4142 def _cache_support(self, name, timeout, caller):43 """Helper callback."""44 key = self.environment.fragment_cache_prefix + name4546 # 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 rv
added:docs/examples/inline_gettext_extension.py+83 added
1# -*- coding: utf-8 -*-2"""3 Inline Gettext4 ~~~~~~~~~~~~~~56 An example extension for Jinja that supports inline gettext calls.7 Requires the i18n extension to be loaded.89 :copyright: (c) 2009 by the Jinja Team.10 :license: BSD.11"""12import re1314from jinja2.exceptions import TemplateSyntaxError15from jinja2.ext import Extension16from jinja2.lexer import count_newlines17from jinja2.lexer import Token181920_outside_re = re.compile(r"\\?(gettext|_)\(")21_inside_re = re.compile(r"\\?[()]")222324class InlineGettext(Extension):25 """This extension implements support for inline gettext blocks::2627 <h1>_(Welcome)</h1>28 <p>_(This is a paragraph)</p>2930 Requires the i18n extension to be loaded and configured.31 """3233 def filter_stream(self, stream):34 paren_stack = 03536 for token in stream:37 if token.type != "data":38 yield token39 continue4041 pos = 042 lineno = token.lineno4344 while 1:45 if not paren_stack:46 match = _outside_re.search(token.value, pos)47 else:48 match = _inside_re.search(token.value, pos)49 if match is None:50 break51 new_pos = match.start()52 if new_pos > pos:53 preval = token.value[pos:new_pos]54 yield Token(lineno, "data", preval)55 lineno += count_newlines(preval)56 gtok = match.group()57 if gtok[0] == "\\":58 yield Token(lineno, "data", gtok[1:])59 elif not paren_stack:60 yield Token(lineno, "block_begin", None)61 yield Token(lineno, "name", "trans")62 yield Token(lineno, "block_end", None)63 paren_stack = 164 else:65 if gtok == "(" or paren_stack > 1:66 yield Token(lineno, "data", gtok)67 paren_stack += gtok == ")" and -1 or 168 if not paren_stack:69 yield Token(lineno, "block_begin", None)70 yield Token(lineno, "name", "endtrans")71 yield Token(lineno, "block_end", None)72 pos = match.end()7374 if pos < len(token.value):75 yield Token(lineno, "data", token.value[pos:])7677 if paren_stack:78 raise TemplateSyntaxError(79 "unclosed gettext expression",80 token.lineno,81 stream.name,82 stream.filename,83 )
deleted:docs/cache_extension.py-54 removed
1from jinja2 import nodes2from jinja2.ext import Extension345class FragmentCacheExtension(Extension):6 # a set of names that trigger the extension.7 tags = {"cache"}89 def __init__(self, environment):10 super(FragmentCacheExtension, self).__init__(environment)1112 # add the defaults to the environment13 environment.extend(fragment_cache_prefix="", fragment_cache=None)1415 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).lineno2122 # now we parse a single expression that is used as cache key.23 args = [parser.parse_expression()]2425 # 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))3132 # 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)3536 # 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)4142 def _cache_support(self, name, timeout, caller):43 """Helper callback."""44 key = self.environment.fragment_cache_prefix + name4546 # 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 rv
modified:docs/extensions.rst+34 added-6 removed
252 unmodified lines
253errors that are horrible to debug. Always make sure you are using the nodes254you create correctly. The API documentation below shows which nodes exist and255how to use them.256257Example Extension258~~~~~~~~~~~~~~~~~257258Example Extensions259------------------260261Cache262~~~~~263264The following example implements a ``cache`` tag for Jinja by using the265`cachelib`_ library:266263.. literalinclude:: cache_extension.py267.. literalinclude:: examples/cache_extension.py268 :language: python269270And here is how you use it in an environment::271
15 unmodified lines
287 {% endcache %}288289.. _cachelib: https://github.com/pallets/cachelib290291292Inline ``gettext``293~~~~~~~~~~~~~~~~~~294295The following example demonstrates using :meth:`Extension.filter_stream`296to parse calls to the ``_()`` gettext function inline with static data297without needing Jinja blocks.298299.. code-block:: html300301 <h1>_(Welcome)</h1>302 <p>_(This is a paragraph)</p>303304It requires the i18n extension to be loaded and configured.305306.. literalinclude:: examples/inline_gettext_extension.py307 :language: python308309310Extension API288~~~~~~~~~~~~~311-------------312313Extension314~~~~~~~~~315316Extensions always have to extend the :class:`jinja2.ext.Extension` class:317318.. autoclass:: Extension319 :members: preprocess, filter_stream, parse, attr, call_method
7 unmodified lines
327328 If the extension implements custom tags this is a set of tag names329 the extension is listening for.330305Parser API306~~~~~~~~~~331332Parser333~~~~~~334335The parser passed to :meth:`Extension.parse` provides ways to parse336expressions of different types. The following methods may be used by337extensions:338
43 unmodified lines
382characters in strings:383384.. autofunction:: jinja2.lexer.count_newlines385386387AST388~~~389390The AST (Abstract Syntax Tree) is used to represent a template after parsing.
14 unmodified lines
deleted:examples/rwbench/django/_form.html-1 removed
deleted:examples/rwbench/django/_input_field.html-1 removed
deleted:examples/rwbench/django/_textarea.html-1 removed
deleted:examples/rwbench/django/index.html-29 removed
deleted:examples/rwbench/django/layout.html-29 removed
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="">34 <py:def function="input_field(name='', value='', type='text')">5 <input type="$type" value="$value" name="$name" />6 </py:def>78 <py:def function="textarea(name, value='', rows=10, cols=40)">9 <textarea name="$name" rows="$rows" cols="cols">$value</textarea>10 </py:def>1112</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 &copy; 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 %}45{% macro textarea(name, value='', rows=10, cols=40) -%}6 <textarea name="{{ name }}" rows="{{ rows }}" cols="{{ cols }}">{{7 value|e }}</textarea>8{%- endmacro %}910{% 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 &copy; 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>45<%def name="textarea(name, value='', rows=10, cols=40)">6 <textarea name="${name}" rows="${rows}" cols="${cols}">${value|h}</textarea>7</%def>89<%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 &copy; 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-126 removed
1# -*- coding: utf-8 -*-2from os.path import join34from django import template as django_template_module5from django.conf import settings6from django.template import Context as DjangoContext7from django.template import loader as django_loader8from django.template import Node9from django.template import TokenParser10from django.template import Variable11from rwbench import dateformat12from rwbench import ROOT1314settings.configure(15 TEMPLATE_DIRS=(join(ROOT, "django"),),16 TEMPLATE_LOADERS=(17 (18 "django.template.loaders.cached.Loader",19 ("django.template.loaders.filesystem.Loader",),20 ),21 ),22)2324# for django extensions. We monkey patch our extensions in so that25# we don't have to initialize a more complex django setup.26django_extensions = django_template_module.Library()27django_template_module.builtins.append(django_extensions)2829django_extensions.filter(dateformat)303132def var_or_none(x):33 if x is not None:34 return Variable(x)353637# and more django extensions38@django_extensions.tag39def input_field(parser, token):40 p = TokenParser(token.contents)41 args = [p.value()]42 while p.more():43 args.append(p.value())44 return InputFieldNode(*args)454647@django_extensions.tag48def textarea(parser, token):49 p = TokenParser(token.contents)50 args = [p.value()]51 while p.more():52 args.append(p.value())53 return TextareaNode(*args)545556@django_extensions.tag57def form(parser, token):58 p = TokenParser(token.contents)59 args = []60 while p.more():61 args.append(p.value())62 body = parser.parse(("endform",))63 parser.delete_first_token()64 return FormNode(body, *args)656667class InputFieldNode(Node):68 def __init__(self, name, type=None, value=None):69 self.name = var_or_none(name)70 self.type = var_or_none(type)71 self.value = var_or_none(value)7273 def render(self, context):74 name = self.name.resolve(context)75 type = "text"76 value = ""77 if self.type is not None:78 type = self.type.resolve(context)79 if self.value is not None:80 value = self.value.resolve(context)81 tmpl = django_loader.get_template("_input_field.html")82 return tmpl.render(DjangoContext({"name": name, "type": type, "value": value}))838485class TextareaNode(Node):86 def __init__(self, name, rows=None, cols=None, value=None):87 self.name = var_or_none(name)88 self.rows = var_or_none(rows)89 self.cols = var_or_none(cols)90 self.value = var_or_none(value)9192 def render(self, context):93 name = self.name.resolve(context)94 rows = 1095 cols = 4096 value = ""97 if self.rows is not None:98 rows = int(self.rows.resolve(context))99 if self.cols is not None:100 cols = int(self.cols.resolve(context))101 if self.value is not None:102 value = self.value.resolve(context)103 tmpl = django_loader.get_template("_textarea.html")104 return tmpl.render(105 DjangoContext({"name": name, "rows": rows, "cols": cols, "value": value})106 )107108109class FormNode(Node):110 def __init__(self, body, action=None, method=None):111 self.body = body112 self.action = action113 self.method = method114115 def render(self, context):116 body = self.body.render(context)117 action = ""118 method = "post"119 if self.action is not None:120 action = self.action.resolve(context)121 if self.method is not None:122 method = self.method.resolve(context)123 tmpl = django_loader.get_template("_form.html")124 return tmpl.render(125 DjangoContext({"body": body, "action": action, "method": method})126 )
deleted:examples/rwbench/rwbench.py-122 removed
1# -*- coding: utf-8 -*-2"""3 RealWorldish Benchmark4 ~~~~~~~~~~~~~~~~~~~~~~56 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!910 :copyright: (c) 2009 by the Jinja Team.11 :license: BSD.12"""13from __future__ import print_function1415import sys16from datetime import datetime17from os.path import abspath18from os.path import dirname19from os.path import join20from pstats import Stats21from random import choice22from random import randrange23from timeit import Timer2425from djangoext import django_loader26from djangoext import DjangoContext27from genshi.template import TemplateLoader as GenshiTemplateLoader28from mako.lookup import TemplateLookup2930from jinja2 import Environment31from jinja2 import FileSystemLoader32from jinja2.utils import generate_lorem_ipsum3334try:35 from cProfile import Profile36except ImportError:37 from profile import Profile3839ROOT = abspath(dirname(__file__))404142def dateformat(x):43 return x.strftime("%Y-%m-%d")444546jinja_env = Environment(loader=FileSystemLoader(join(ROOT, "jinja")))47jinja_env.filters["dateformat"] = dateformat48mako_lookup = TemplateLookup(directories=[join(ROOT, "mako")])49genshi_loader = GenshiTemplateLoader([join(ROOT, "genshi")])505152class Article(object):53 def __init__(self, id):54 self.id = id55 self.href = "/article/%d" % self.id56 self.title = generate_lorem_ipsum(1, False, 5, 10)57 self.user = choice(users)58 self.body = generate_lorem_ipsum()59 self.pub_date = datetime.utcfromtimestamp(randrange(10 ** 9, 2 * 10 ** 9))60 self.published = True616263class User(object):64 def __init__(self, username):65 self.href = "/user/%s" % username66 self.username = username676869users = map(User, [u"John Doe", u"Jane Doe", u"Peter Somewhat"])70articles = map(Article, range(20))71navigation = [72 ("index", "Index"),73 ("about", "About"),74 ("foo?bar=1", "Foo with Bar"),75 ("foo?bar=2&s=x", "Foo with X"),76 ("blah", "Blub Blah"),77 ("hehe", "Haha"),78] * 57980context = dict(users=users, articles=articles, page_navigation=navigation)8182jinja_template = jinja_env.get_template("index.html")83mako_template = mako_lookup.get_template("index.html")84genshi_template = genshi_loader.load("index.html")858687def test_jinja():88 jinja_template.render(context)899091def test_mako():92 mako_template.render_unicode(**context)939495def test_django():96 # not cached because django is not thread safe and does97 # not cache by itself so it would be unfair to cache it here.98 django_template = django_loader.get_template("index.html")99 django_template.render(DjangoContext(context))100101102def test_genshi():103 genshi_template.generate(**context).render("html", doctype="html")104105106if __name__ == "__main__":107 sys.stdout.write("Realworldish Benchmark:\n")108 for test in "jinja", "mako", "django", "genshi":109 t = Timer(setup="from __main__ import test_%s as bench" % test, stmt="bench()")110 sys.stdout.write(" >> %-20s<running>" % test)111 sys.stdout.flush()112 sys.stdout.write(113 "\r %-20s%.4f seconds\n" % (test, t.timeit(number=200) / 200)114 )115116 if "-p" in sys.argv:117 print("Jinja profile")118 p = Profile()119 p.runcall(test_jinja)120 stats = Stats(p)121 stats.sort_stats("time", "calls")122 stats.print_stats()
deleted:examples/bench.py-499 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"""6import cgi7import sys8from timeit import Timer910from jinja2 import Environment as JinjaEnvironment11from jinja2._compat import text_type1213context = {14 "page_title": "mitsuhiko's benchmark",15 "table": [16 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)17 ],18}1920jinja_template = JinjaEnvironment(21 line_statement_prefix="%", variable_start_string="${", variable_end_string="}"22).from_string(23 """\24<!doctype html>25<html>26 <head>27 <title>${page_title|e}</title>28 </head>29 <body>30 <div class="header">31 <h1>${page_title|e}</h1>32 </div>33 <ul class="navigation">34 % for href, caption in [35 ('index.html', 'Index'),36 ('downloads.html', 'Downloads'),37 ('products.html', 'Products')38 ]39 <li><a href="${href|e}">${caption|e}</a></li>40 % endfor41 </ul>42 <div class="table">43 <table>44 % for row in table45 <tr>46 % for cell in row47 <td>${cell}</td>48 % endfor49 </tr>50 % endfor51 </table>52 </div>53 </body>54</html>\55"""56)575859def test_jinja():60 jinja_template.render(context)616263try:64 from tornado.template import Template65except ImportError:66 test_tornado = None67else:68 tornado_template = Template(69 """\70<!doctype html>71<html>72 <head>73 <title>{{ page_title }}</title>74 </head>75 <body>76 <div class="header">77 <h1>{{ page_title }}</h1>78 </div>79 <ul class="navigation">80 {% for href, caption in [ \81 ('index.html', 'Index'), \82 ('downloads.html', 'Downloads'), \83 ('products.html', 'Products') \84 ] %}85 <li><a href="{{ href }}">{{ caption }}</a></li>86 {% end %}87 </ul>88 <div class="table">89 <table>90 {% for row in table %}91 <tr>92 {% for cell in row %}93 <td>{{ cell }}</td>94 {% end %}95 </tr>96 {% end %}97 </table>98 </div>99 </body>100</html>\101"""102 )103104 def test_tornado():105 tornado_template.generate(**context)106107108try:109 from django.conf import settings110111 settings.configure()112 from django.template import Template as DjangoTemplate, Context as DjangoContext113except ImportError:114 test_django = None115else:116 django_template = DjangoTemplate(117 """\118<!doctype html>119<html>120 <head>121 <title>{{ page_title }}</title>122 </head>123 <body>124 <div class="header">125 <h1>{{ page_title }}</h1>126 </div>127 <ul class="navigation">128 {% for href, caption in navigation %}129 <li><a href="{{ href }}">{{ caption }}</a></li>130 {% endfor %}131 </ul>132 <div class="table">133 <table>134 {% for row in table %}135 <tr>136 {% for cell in row %}137 <td>{{ cell }}</td>138 {% endfor %}139 </tr>140 {% endfor %}141 </table>142 </div>143 </body>144</html>\145"""146 )147148 def test_django():149 c = DjangoContext(context)150 c["navigation"] = [151 ("index.html", "Index"),152 ("downloads.html", "Downloads"),153 ("products.html", "Products"),154 ]155 django_template.render(c)156157158try:159 from mako.template import Template as MakoTemplate160except ImportError:161 test_mako = None162else:163 mako_template = MakoTemplate(164 """\165<!doctype html>166<html>167 <head>168 <title>${page_title|h}</title>169 </head>170 <body>171 <div class="header">172 <h1>${page_title|h}</h1>173 </div>174 <ul class="navigation">175 % for href, caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), \176('products.html', 'Products')]:177 <li><a href="${href|h}">${caption|h}</a></li>178 % endfor179 </ul>180 <div class="table">181 <table>182 % for row in table:183 <tr>184 % for cell in row:185 <td>${cell}</td>186 % endfor187 </tr>188 % endfor189 </table>190 </div>191 </body>192</html>\193"""194 )195196 def test_mako():197 mako_template.render(**context)198199200try:201 from genshi.template import MarkupTemplate as GenshiTemplate202except ImportError:203 test_genshi = None204else:205 genshi_template = GenshiTemplate(206 """\207<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/">208 <head>209 <title>${page_title}</title>210 </head>211 <body>212 <div class="header">213 <h1>${page_title}</h1>214 </div>215 <ul class="navigation">216 <li py:for="href, caption in [217 ('index.html', 'Index'),218 ('downloads.html', 'Downloads'),219 ('products.html', 'Products')]"><a href="${href}">${caption}</a></li>220 </ul>221 <div class="table">222 <table>223 <tr py:for="row in table">224 <td py:for="cell in row">${cell}</td>225 </tr>226 </table>227 </div>228 </body>229</html>\230"""231 )232233 def test_genshi():234 genshi_template.generate(**context).render("html", strip_whitespace=False)235236237try:238 from Cheetah.Template import Template as CheetahTemplate239except ImportError:240 test_cheetah = None241else:242 cheetah_template = CheetahTemplate(243 """\244#import cgi245<!doctype html>246<html>247 <head>248 <title>$cgi.escape($page_title)</title>249 </head>250 <body>251 <div class="header">252 <h1>$cgi.escape($page_title)</h1>253 </div>254 <ul class="navigation">255 #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), \256('products.html', 'Products')]:257 <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li>258 #end for259 </ul>260 <div class="table">261 <table>262 #for $row in $table:263 <tr>264 #for $cell in $row:265 <td>$cell</td>266 #end for267 </tr>268 #end for269 </table>270 </div>271 </body>272</html>\273""",274 searchList=[dict(context)],275 )276277 def test_cheetah():278 text_type(cheetah_template)279280281try:282 import tenjin283except ImportError:284 test_tenjin = None285else:286 tenjin_template = tenjin.Template()287 tenjin_template.convert(288 """\289<!doctype html>290<html>291 <head>292 <title>${page_title}</title>293 </head>294 <body>295 <div class="header">296 <h1>${page_title}</h1>297 </div>298 <ul class="navigation">299<?py for href, caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), \300('products.html', 'Products')]: ?>301 <li><a href="${href}">${caption}</a></li>302<?py #end ?>303 </ul>304 <div class="table">305 <table>306<?py for row in table: ?>307 <tr>308<?py for cell in row: ?>309 <td>#{cell}</td>310<?py #end ?>311 </tr>312<?py #end ?>313 </table>314 </div>315 </body>316</html>\317"""318 )319320 def test_tenjin():321 tenjin_template.render(context, locals())322323324try:325 from spitfire.compiler import util as SpitfireTemplate326 from spitfire.compiler.analyzer import o2_options as spitfire_optimizer327except ImportError:328 test_spitfire = None329else:330 spitfire_template = SpitfireTemplate.load_template(331 """\332<!doctype html>333<html>334 <head>335 <title>$cgi.escape($page_title)</title>336 </head>337 <body>338 <div class="header">339 <h1>$cgi.escape($page_title)</h1>340 </div>341 <ul class="navigation">342 #for $href, $caption in [('index.html', 'Index'), ('downloads.html', 'Downloads'), \343('products.html', 'Products')]344 <li><a href="$cgi.escape($href)">$cgi.escape($caption)</a></li>345 #end for346 </ul>347 <div class="table">348 <table>349 #for $row in $table350 <tr>351 #for $cell in $row352 <td>$cell</td>353 #end for354 </tr>355 #end for356 </table>357 </div>358 </body>359</html>\360""",361 "spitfire_tmpl",362 spitfire_optimizer,363 {"enable_filters": False},364 )365 spitfire_context = dict(context, **{"cgi": cgi})366367 def test_spitfire():368 spitfire_template(search_list=[spitfire_context]).main()369370371try:372 from chameleon.zpt.template import PageTemplate373except ImportError:374 test_chameleon = None375else:376 chameleon_template = PageTemplate(377 """\378<html xmlns:tal="http://xml.zope.org/namespaces/tal">379 <head>380 <title tal:content="page_title">Page Title</title>381 </head>382 <body>383 <div class="header">384 <h1 tal:content="page_title">Page Title</h1>385 </div>386 <ul class="navigation">387 <li tal:repeat="item sections"><a tal:attributes="href item[0]" \388tal:content="item[1]">caption</a></li>389 </ul>390 <div class="table">391 <table>392 <tr tal:repeat="row table">393 <td tal:repeat="cell row" tal:content="row[cell]">cell</td>394 </tr>395 </table>396 </div>397 </body>398</html>\399"""400 )401 chameleon_context = dict(context)402 chameleon_context["sections"] = [403 ("index.html", "Index"),404 ("downloads.html", "Downloads"),405 ("products.html", "Products"),406 ]407408 def test_chameleon():409 chameleon_template.render(**chameleon_context)410411412try:413 from chameleon.zpt.template import PageTemplate414 from chameleon.genshi import language415except ImportError:416 test_chameleon_genshi = None417else:418 chameleon_genshi_template = PageTemplate(419 """\420<html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/">421 <head>422 <title>${page_title}</title>423 </head>424 <body>425 <div class="header">426 <h1>${page_title}</h1>427 </div>428 <ul class="navigation">429 <li py:for="info in sections"><a href="${info[0]}">${info[1]}</a></li>430 </ul>431 <div class="table">432 <table>433 <tr py:for="row in table">434 <td py:for="cell in row">${row[cell]}</td>435 </tr>436 </table>437 </div>438 </body>439</html>\440""",441 parser=language.Parser(),442 )443 chameleon_genshi_context = dict(context)444 chameleon_genshi_context["sections"] = [445 ("index.html", "Index"),446 ("downloads.html", "Downloads"),447 ("products.html", "Products"),448 ]449450 def test_chameleon_genshi():451 chameleon_genshi_template.render(**chameleon_genshi_context)452453454sys.stdout.write(455 "\r"456 + "\n".join(457 (458 "=" * 80,459 "Template Engine BigTable Benchmark".center(80),460 "=" * 80,461 __doc__,462 "-" * 80,463 )464 )465 + "\n"466)467468469for test in (470 "jinja",471 "mako",472 "tornado",473 "tenjin",474 "spitfire",475 "django",476 "genshi",477 "cheetah",478 "chameleon",479 "chameleon_genshi",480):481 if locals()["test_" + test] is None:482 sys.stdout.write(" %-20s*not installed*\n" % test)483 continue484 t = Timer(setup="from __main__ import test_%s as bench" % test, stmt="bench()")485 sys.stdout.write(" >> %-20s<running>" % test)486 sys.stdout.flush()487 sys.stdout.write("\r %-20s%.4f seconds\n" % (test, t.timeit(number=50) / 50))488sys.stdout.write("-" * 80 + "\n")489sys.stdout.write(490 """\491 WARNING: The results of this benchmark are useless to compare the492 performance of template engines and should not be taken seriously in any493 way. It's testing the performance of simple loops and has no real-world494 usefulnes. It only used to check if changes on the Jinja code affect495 performance in a good or bad way and how it roughly compares to others.496"""497 + "=" * 80498 + "\n"499)
deleted:examples/profile.py-54 removed
1from __future__ import print_function23try:4 from cProfile import Profile5except ImportError:6 from profile import Profile7from pstats import Stats8from jinja2 import Environment as JinjaEnvironment910context = {11 "page_title": "mitsuhiko's benchmark",12 "table": [13 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}1617source = """\18% macro testmacro(x)19 <span>${x}</span>20% endmacro21<!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 <div class="table">31 <table>32 % for row in table33 <tr>34 % for cell in row35 <td>${testmacro(cell)}</td>36 % endfor37 </tr>38 % endfor39 </table>40 </div>41 </body>42</html>\43"""44jinja_template = JinjaEnvironment(45 line_statement_prefix="%", variable_start_string="${", variable_end_string="}"46).from_string(source)47print(jinja_template.environment.compile(source, raw=True))484950p = Profile()51p.runcall(lambda: jinja_template.render(context))52stats = Stats(p)53stats.sort_stats("time", "calls")54stats.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" }}!78 {% 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 %}3031 {% with object.value as value %}32 <img src='bar.gif' height='10' width='{% widthratio value 200 100 %}'>33 {% endwith %}3435 <pre>{% debug %}</pre>3637 {% blocktrans with book|title as book_t and author|title as author_t %}38 This is {{ book_t }} by {{ author_t }}39 {% endblocktrans %}4041 {% blocktrans count list|length as counter %}42 There is only one {{ name }} object.43 {% plural %}44 There are {{ counter }} {{ name }} objects.45 {% endblocktrans %}4647 {% 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 %}5253 {% blocktrans %}This string will have {{ value }} inside.{% endblocktrans %}5455 <p>{% trans "This is the title." %}</p>5657 {% 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
1Hello World!
deleted:ext/django2jinja/django2jinja.py-812 removed
1# -*- coding: utf-8 -*-2"""3Django to Jinja4~~~~~~~~~~~~~~~56Helper module that can convert django templates into Jinja templates.78This file is not intended to be used as stand alone application but to9be used as library. To convert templates you basically create your own10writer, add extra conversion logic for your custom template tags,11configure your django environment and run the `convert_templates`12function.1314Here a simple example::1516 # configure django (or use settings.configure)17 import os1819 os.environ["DJANGO_SETTINGS_MODULE"] = "yourapplication.settings"20 from yourapplication.foo.templatetags.bar import MyNode2122 from django2jinja import Writer, convert_templates2324 def write_my_node(writer, node):25 writer.start_variable()26 writer.write("myfunc(")27 for idx, arg in enumerate(node.args):28 if idx:29 writer.write(", ")30 writer.node(arg)31 writer.write(")")32 writer.end_variable()3334 writer = Writer()35 writer.node_handlers[MyNode] = write_my_node36 convert_templates("/path/to/output/folder", writer=writer)3738Here is an example hos to automatically translate your django39variables to jinja2::4041 import re42 # List of tuple (Match pattern, Replace pattern, Exclusion pattern)43 var_re = (44 (re.compile("(u|user)\\.is_authenticated"), "\\1.is_authenticated()", None),45 (re.compile("\\.non_field_errors"), ".non_field_errors()", None),46 (re.compile("\\.label_tag"), ".label_tag()", None),47 (re.compile("\\.as_dl"), ".as_dl()", None),48 (re.compile("\\.as_table"), ".as_table()", None),49 (re.compile("\\.as_widget"), ".as_widget()", None),50 (re.compile("\\.as_hidden"), ".as_hidden()", None),51 (re.compile("\\.get_([0-9_\\w]+)_url"), ".get_\\1_url()", None),52 (re.compile("\\.url"), ".url()", re.compile("(form|calendar).url")),53 (re.compile("\\.get_([0-9_\\w]+)_display"), ".get_\\1_display()", None),54 (re.compile("loop\\.counte"), "loop.index", None),55 (re.compile("loop\\.revcounte"), "loop.revindex", None),56 (57 re.compile("request\\.GET\\.([0-9_\\w]+)"),58 "request.GET.get('\\1', '')",59 None,60 ),61 (re.compile("request\\.get_host"), "request.get_host()", None),62 (re.compile("\\.all(?!_)"), ".all()", None),63 (re.compile("\\.all\\.0"), ".all()[0]", None),64 (re.compile("\\.([0-9])($|\\s+)"), "[\\1]\\2", None),65 (re.compile("\\.items"), ".items()", None),66 )67 writer = Writer(var_re=var_re)6869For details about the writing process have a look at the module code.7071:copyright: (c) 2009 by the Jinja Team.72:license: BSD.73"""74from __future__ import print_function7576import os77import re78import sys7980from django.conf import settings81from django.template import defaulttags as core_tags82from django.template import FilterExpression83from django.template import libraries84from django.template import loader85from django.template import loader_tags86from django.template import TextNode87from django.template import TOKEN_TEXT88from django.template import TOKEN_VAR89from django.template import Variable90from django.template.debug import DebugVariableNode as VariableNode91from django.templatetags import i18n as i18n_tags9293from jinja2 import defaults9495_node_handlers = {}96_resolved_filters = {}97_newline_re = re.compile(r"(?:\r\n|\r|\n)")9899# Django stores an itertools object on the cycle node. Not only is this100# thread unsafe but also a problem for the converter which needs the raw101# string values passed to the constructor to create a jinja loop.cycle()102# call from it.103_old_cycle_init = core_tags.CycleNode.__init__104105106def _fixed_cycle_init(self, cyclevars, variable_name=None):107 self.raw_cycle_vars = map(Variable, cyclevars)108 _old_cycle_init(self, cyclevars, variable_name)109110111core_tags.CycleNode.__init__ = _fixed_cycle_init112113114def node(cls):115 def proxy(f):116 _node_handlers[cls] = f117 return f118119 return proxy120121122def convert_templates(123 output_dir, extensions=(".html", ".txt"), writer=None, callback=None124):125 """Iterates over all templates in the template dirs configured and126 translates them and writes the new templates into the output127 directory.128 """129 if writer is None:130 writer = Writer()131132 def filter_templates(files):133 for filename in files:134 ifilename = filename.lower()135 for extension in extensions:136 if ifilename.endswith(extension):137 yield filename138139 def translate(f, loadname):140 template = loader.get_template(loadname)141 original = writer.stream142 writer.stream = f143 writer.body(template.nodelist)144 writer.stream = original145146 if callback is None:147148 def callback(template):149 print(template)150151 for directory in settings.TEMPLATE_DIRS:152 for dirname, _, files in os.walk(directory):153 dirname = dirname[len(directory) + 1 :]154 for filename in filter_templates(files):155 source = os.path.normpath(os.path.join(dirname, filename))156 target = os.path.join(output_dir, dirname, filename)157 basetarget = os.path.dirname(target)158 if not os.path.exists(basetarget):159 os.makedirs(basetarget)160 callback(source)161 with open(target, "w") as f:162 translate(f, source)163164165class Writer(object):166 """The core writer class."""167168 def __init__(169 self,170 stream=None,171 error_stream=None,172 block_start_string=defaults.BLOCK_START_STRING,173 block_end_string=defaults.BLOCK_END_STRING,174 variable_start_string=defaults.VARIABLE_START_STRING,175 variable_end_string=defaults.VARIABLE_END_STRING,176 comment_start_string=defaults.COMMENT_START_STRING,177 comment_end_string=defaults.COMMENT_END_STRING,178 initial_autoescape=True,179 use_jinja_autoescape=False,180 custom_node_handlers=None,181 var_re=None,182 env=None,183 ):184 if stream is None:185 stream = sys.stdout186 if error_stream is None:187 error_stream = sys.stderr188 self.stream = stream189 self.error_stream = error_stream190 self.block_start_string = block_start_string191 self.block_end_string = block_end_string192 self.variable_start_string = variable_start_string193 self.variable_end_string = variable_end_string194 self.comment_start_string = comment_start_string195 self.comment_end_string = comment_end_string196 self.autoescape = initial_autoescape197 self.spaceless = False198 self.use_jinja_autoescape = use_jinja_autoescape199 self.node_handlers = dict(_node_handlers, **(custom_node_handlers or {}))200 self._loop_depth = 0201 self._filters_warned = set()202 self.var_re = [] if var_re is None else var_re203 self.env = env204205 def enter_loop(self):206 """Increments the loop depth so that write functions know if207 they are in a loop.208 """209 self._loop_depth += 1210211 def leave_loop(self):212 """Reverse of enter_loop."""213 self._loop_depth -= 1214215 @property216 def in_loop(self):217 """True if we are in a loop."""218 return self._loop_depth > 0219220 def write(self, s):221 """Writes stuff to the stream."""222 self.stream.write(s.encode(settings.FILE_CHARSET))223224 def print_expr(self, expr):225 """Open a variable tag, write to the string to the stream and226 close.227 """228 self.start_variable()229 self.write(expr)230 self.end_variable()231232 def _post_open(self):233 if self.spaceless:234 self.write("- ")235 else:236 self.write(" ")237238 def _pre_close(self):239 if self.spaceless:240 self.write(" -")241 else:242 self.write(" ")243244 def start_variable(self):245 """Start a variable."""246 self.write(self.variable_start_string)247 self._post_open()248249 def end_variable(self, always_safe=False):250 """End a variable."""251 if not always_safe and self.autoescape and not self.use_jinja_autoescape:252 self.write("|e")253 self._pre_close()254 self.write(self.variable_end_string)255256 def start_block(self):257 """Starts a block."""258 self.write(self.block_start_string)259 self._post_open()260261 def end_block(self):262 """Ends a block."""263 self._pre_close()264 self.write(self.block_end_string)265266 def tag(self, name):267 """Like `print_expr` just for blocks."""268 self.start_block()269 self.write(name)270 self.end_block()271272 def variable(self, name):273 """Prints a variable. This performs variable name274 transformation.275 """276 self.write(self.translate_variable_name(name))277278 def literal(self, value):279 """Writes a value as literal."""280 value = repr(value)281 if value[:2] in ('u"', "u'"):282 value = value[1:]283 self.write(value)284285 def filters(self, filters, is_block=False):286 """Dumps a list of filters."""287 want_pipe = not is_block288 for filter, args in filters:289 name = self.get_filter_name(filter)290 if name is None:291 self.warn("Could not find filter %s" % name)292 continue293 if (294 name not in defaults.DEFAULT_FILTERS295 and name not in self._filters_warned296 ):297 self._filters_warned.add(name)298 self.warn("Filter %s probably doesn't exist in Jinja" % name)299 if not want_pipe:300 want_pipe = True301 else:302 self.write("|")303 self.write(name)304 if args:305 self.write("(")306 for idx, (is_var, value) in enumerate(args):307 if idx:308 self.write(", ")309 if is_var:310 self.node(value)311 else:312 self.literal(value)313 self.write(")")314315 def get_location(self, origin, position):316 """Returns the location for an origin and position tuple as name317 and lineno.318 """319 if hasattr(origin, "source"):320 source = origin.source321 name = "<unknown source>"322 else:323 source = origin.loader(origin.loadname, origin.dirs)[0]324 name = origin.loadname325 lineno = len(_newline_re.findall(source[: position[0]])) + 1326 return name, lineno327328 def warn(self, message, node=None):329 """Prints a warning to the error stream."""330 if node is not None and hasattr(node, "source"):331 filename, lineno = self.get_location(*node.source)332 message = "[%s:%d] %s" % (filename, lineno, message)333 print(message, file=self.error_stream)334335 def translate_variable_name(self, var):336 """Performs variable name translation."""337 if self.in_loop and var == "forloop" or var.startswith("forloop."):338 var = var[3:]339340 for reg, rep, unless in self.var_re:341 no_unless = unless and unless.search(var) or True342 if reg.search(var) and no_unless:343 var = reg.sub(rep, var)344 break345 return var346347 def get_filter_name(self, filter):348 """Returns the filter name for a filter function or `None` if there349 is no such filter.350 """351 if filter not in _resolved_filters:352 for library in libraries.values():353 for key, value in library.filters.items():354 _resolved_filters[value] = key355 return _resolved_filters.get(filter, None)356357 def node(self, node):358 """Invokes the node handler for a node."""359 for cls, handler in self.node_handlers.items():360 if type(node) is cls or type(node).__name__ == cls:361 handler(self, node)362 break363 else:364 self.warn(365 "Untranslatable node %s.%s found"366 % (node.__module__, node.__class__.__name__),367 node,368 )369370 def body(self, nodes):371 """Calls node() for every node in the iterable passed."""372 for node in nodes:373 self.node(node)374375376@node(TextNode)377def text_node(writer, node):378 writer.write(node.s)379380381@node(Variable)382def variable(writer, node):383 if node.translate:384 writer.warn("i18n system used, make sure to install translations", node)385 writer.write("_(")386 if node.literal is not None:387 writer.literal(node.literal)388 else:389 writer.variable(node.var)390 if node.translate:391 writer.write(")")392393394@node(VariableNode)395def variable_node(writer, node):396 writer.start_variable()397 if (398 node.filter_expression.var.var == "block.super"399 and not node.filter_expression.filters400 ):401 writer.write("super()")402 else:403 writer.node(node.filter_expression)404 writer.end_variable()405406407@node(FilterExpression)408def filter_expression(writer, node):409 writer.node(node.var)410 writer.filters(node.filters)411412413@node(core_tags.CommentNode)414def comment_tag(writer, node):415 pass416417418@node(core_tags.DebugNode)419def debug_tag(writer, node):420 writer.warn(421 "Debug tag detected. Make sure to add a global function "422 "called debug to the namespace.",423 node=node,424 )425 writer.print_expr("debug()")426427428@node(core_tags.ForNode)429def for_loop(writer, node):430 writer.start_block()431 writer.write("for ")432 for idx, var in enumerate(node.loopvars):433 if idx:434 writer.write(", ")435 writer.variable(var)436 writer.write(" in ")437 if node.is_reversed:438 writer.write("(")439 writer.node(node.sequence)440 if node.is_reversed:441 writer.write(")|reverse")442 writer.end_block()443 writer.enter_loop()444 writer.body(node.nodelist_loop)445 writer.leave_loop()446 writer.tag("endfor")447448449@node(core_tags.IfNode)450def if_condition(writer, node):451 writer.start_block()452 writer.write("if ")453 join_with = "and"454 if node.link_type == core_tags.IfNode.LinkTypes.or_:455 join_with = "or"456457 for idx, (ifnot, expr) in enumerate(node.bool_exprs):458 if idx:459 writer.write(" %s " % join_with)460 if ifnot:461 writer.write("not ")462 writer.node(expr)463 writer.end_block()464 writer.body(node.nodelist_true)465 if node.nodelist_false:466 writer.tag("else")467 writer.body(node.nodelist_false)468 writer.tag("endif")469470471@node(core_tags.IfEqualNode)472def if_equal(writer, node):473 writer.start_block()474 writer.write("if ")475 writer.node(node.var1)476 if node.negate:477 writer.write(" != ")478 else:479 writer.write(" == ")480 writer.node(node.var2)481 writer.end_block()482 writer.body(node.nodelist_true)483 if node.nodelist_false:484 writer.tag("else")485 writer.body(node.nodelist_false)486 writer.tag("endif")487488489@node(loader_tags.BlockNode)490def block(writer, node):491 writer.tag("block " + node.name.replace("-", "_").rstrip("_"))492 node = node493 while node.parent is not None:494 node = node.parent495 writer.body(node.nodelist)496 writer.tag("endblock")497498499@node(loader_tags.ExtendsNode)500def extends(writer, node):501 writer.start_block()502 writer.write("extends ")503 if node.parent_name_expr:504 writer.node(node.parent_name_expr)505 else:506 writer.literal(node.parent_name)507 writer.end_block()508 writer.body(node.nodelist)509510511@node(loader_tags.ConstantIncludeNode)512@node(loader_tags.IncludeNode)513def include(writer, node):514 writer.start_block()515 writer.write("include ")516 if hasattr(node, "template"):517 writer.literal(node.template.name)518 else:519 writer.node(node.template_name)520 writer.end_block()521522523@node(core_tags.CycleNode)524def cycle(writer, node):525 if not writer.in_loop:526 writer.warn("Untranslatable free cycle (cycle outside loop)", node=node)527 return528 if node.variable_name is not None:529 writer.start_block()530 writer.write("set %s = " % node.variable_name)531 else:532 writer.start_variable()533 writer.write("loop.cycle(")534 for idx, var in enumerate(node.raw_cycle_vars):535 if idx:536 writer.write(", ")537 writer.node(var)538 writer.write(")")539 if node.variable_name is not None:540 writer.end_block()541 else:542 writer.end_variable()543544545@node(core_tags.FilterNode)546def filter(writer, node):547 writer.start_block()548 writer.write("filter ")549 writer.filters(node.filter_expr.filters, True)550 writer.end_block()551 writer.body(node.nodelist)552 writer.tag("endfilter")553554555@node(core_tags.AutoEscapeControlNode)556def autoescape_control(writer, node):557 original = writer.autoescape558 writer.autoescape = node.setting559 writer.body(node.nodelist)560 writer.autoescape = original561562563@node(core_tags.SpacelessNode)564def spaceless(writer, node):565 original = writer.spaceless566 writer.spaceless = True567 writer.warn("entering spaceless mode with different semantics", node)568 # do the initial stripping569 nodelist = list(node.nodelist)570 if nodelist:571 if isinstance(nodelist[0], TextNode):572 nodelist[0] = TextNode(nodelist[0].s.lstrip())573 if isinstance(nodelist[-1], TextNode):574 nodelist[-1] = TextNode(nodelist[-1].s.rstrip())575 writer.body(nodelist)576 writer.spaceless = original577578579@node(core_tags.TemplateTagNode)580def template_tag(writer, node):581 tag = {582 "openblock": writer.block_start_string,583 "closeblock": writer.block_end_string,584 "openvariable": writer.variable_start_string,585 "closevariable": writer.variable_end_string,586 "opencomment": writer.comment_start_string,587 "closecomment": writer.comment_end_string,588 "openbrace": "{",589 "closebrace": "}",590 }.get(node.tagtype)591 if tag:592 writer.start_variable()593 writer.literal(tag)594 writer.end_variable()595596597@node(core_tags.URLNode)598def url_tag(writer, node):599 writer.warn("url node used. make sure to provide a proper url() function", node)600 if node.asvar:601 writer.start_block()602 writer.write("set %s = " % node.asvar)603 else:604 writer.start_variable()605 writer.write("url(")606 writer.literal(node.view_name)607 for arg in node.args:608 writer.write(", ")609 writer.node(arg)610 for key, arg in node.kwargs.items():611 writer.write(", %s=" % key)612 writer.node(arg)613 writer.write(")")614 if node.asvar:615 writer.end_block()616 else:617 writer.end_variable()618619620@node(core_tags.WidthRatioNode)621def width_ratio(writer, node):622 writer.warn(623 "widthratio expanded into formula. You may want to provide "624 "a helper function for this calculation",625 node,626 )627 writer.start_variable()628 writer.write("(")629 writer.node(node.val_expr)630 writer.write(" / ")631 writer.node(node.max_expr)632 writer.write(" * ")633 writer.write(str(int(node.max_width)))634 writer.write(")|round|int")635 writer.end_variable(always_safe=True)636637638@node(core_tags.WithNode)639def with_block(writer, node):640 writer.warn(641 "with block expanded into set statement. This could cause "642 "variables following that block to be overridden.",643 node,644 )645 writer.start_block()646 writer.write("set %s = " % node.name)647 writer.node(node.var)648 writer.end_block()649 writer.body(node.nodelist)650651652@node(core_tags.RegroupNode)653def regroup(writer, node):654 if node.expression.var.literal:655 writer.warn(656 "literal in groupby filter used. Behavior in that "657 "situation is undefined and translation is skipped.",658 node,659 )660 return661 elif node.expression.filters:662 writer.warn(663 "filters in groupby filter used. Behavior in that "664 "situation is undefined which is most likely a bug "665 "in your code. Filters were ignored.",666 node,667 )668 writer.start_block()669 writer.write("set %s = " % node.var_name)670 writer.node(node.target)671 writer.write("|groupby(")672 writer.literal(node.expression.var.var)673 writer.write(")")674 writer.end_block()675676677@node(core_tags.LoadNode)678def warn_load(writer, node):679 writer.warn("load statement used which was ignored on conversion", node)680681682@node(i18n_tags.GetAvailableLanguagesNode)683def get_available_languages(writer, node):684 writer.warn("make sure to provide a get_available_languages function", node)685 writer.tag(686 "set %s = get_available_languages()"687 % writer.translate_variable_name(node.variable)688 )689690691@node(i18n_tags.GetCurrentLanguageNode)692def get_current_language(writer, node):693 writer.warn("make sure to provide a get_current_language function", node)694 writer.tag(695 "set %s = get_current_language()"696 % writer.translate_variable_name(node.variable)697 )698699700@node(i18n_tags.GetCurrentLanguageBidiNode)701def get_current_language_bidi(writer, node):702 writer.warn("make sure to provide a get_current_language_bidi function", node)703 writer.tag(704 "set %s = get_current_language_bidi()"705 % writer.translate_variable_name(node.variable)706 )707708709@node(i18n_tags.TranslateNode)710def simple_gettext(writer, node):711 writer.warn("i18n system used, make sure to install translations", node)712 writer.start_variable()713 writer.write("_(")714 writer.node(node.value)715 writer.write(")")716 writer.end_variable()717718719@node(i18n_tags.BlockTranslateNode)720def translate_block(writer, node):721 first_var = []722 variables = set()723724 def touch_var(name):725 variables.add(name)726 if not first_var:727 first_var.append(name)728729 def dump_token_list(tokens):730 for token in tokens:731 if token.token_type == TOKEN_TEXT:732 writer.write(token.contents)733 elif token.token_type == TOKEN_VAR:734 writer.print_expr(token.contents)735 touch_var(token.contents)736737 writer.warn("i18n system used, make sure to install translations", node)738 writer.start_block()739 writer.write("trans")740 idx = -1741 for idx, (key, var) in enumerate(node.extra_context.items()):742 if idx:743 writer.write(",")744 writer.write(" %s=" % key)745 touch_var(key)746 writer.node(var.filter_expression)747748 if node.plural and node.countervar and node.counter:749 plural_var = node.countervar750 if plural_var not in variables:751 if idx > -1:752 writer.write(",")753 touch_var(plural_var)754 writer.write(" %s=" % plural_var)755 writer.node(node.counter)756757 writer.end_block()758 dump_token_list(node.singular)759 if node.plural and node.countervar and node.counter:760 writer.start_block()761 writer.write("pluralize")762 if node.countervar != first_var[0]:763 writer.write(" " + node.countervar)764 writer.end_block()765 dump_token_list(node.plural)766 writer.tag("endtrans")767768769@node("SimpleNode")770def simple_tag(writer, node):771 """Check if the simple tag exist as a filter in """772 name = node.tag_name773 if (774 writer.env775 and name not in writer.env.filters776 and name not in writer._filters_warned777 ):778 writer._filters_warned.add(name)779 writer.warn("Filter %s probably doesn't exist in Jinja" % name)780781 if not node.vars_to_resolve:782 # No argument, pass the request783 writer.start_variable()784 writer.write("request|")785 writer.write(name)786 writer.end_variable()787 return788789 first_var = node.vars_to_resolve[0]790 args = node.vars_to_resolve[1:]791 writer.start_variable()792793 # Copied from Writer.filters()794 writer.node(first_var)795796 writer.write("|")797 writer.write(name)798 if args:799 writer.write("(")800 for idx, var in enumerate(args):801 if idx:802 writer.write(", ")803 if var.var:804 writer.node(var)805 else:806 writer.literal(var.literal)807 writer.write(")")808 writer.end_variable()809810811# get rid of node now, it shouldn't be used normally812del node
deleted:ext/django2jinja/example.py-7 removed
1from django.conf import settings2from django2jinja import convert_templates3from django2jinja import Writer45settings.configure(TEMPLATE_DIRS=["templates"], TEMPLATE_DEBUG=True)6writer = Writer(use_jinja_autoescape=True)7convert_templates("converted", writer=writer)
deleted:ext/djangojinja2.py-91 removed
1# -*- coding: utf-8 -*-2"""3 djangojinja24 ~~~~~~~~~~~~56 Adds support for Jinja to Django.78 Configuration variables:910 ======================= =============================================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 ======================= =============================================1718 :copyright: (c) 2009 by the Jinja Team.19 :license: BSD.20"""21from itertools import chain2223from django.conf import settings24from django.http import HttpResponse25from django.template import TemplateDoesNotExist26from django.template.context import get_standard_processors2728from jinja2 import Environment29from jinja2 import FileSystemLoader30from jinja2 import TemplateNotFound313233# the environment is unconfigured until the first template is loaded.34_jinja_env = None353637def get_env():38 """Get the Jinja env and initialize it if necessary."""39 global _jinja_env40 if _jinja_env is None:41 _jinja_env = create_env()42 return _jinja_env434445def create_env():46 """Create a new Jinja environment."""47 searchpath = list(settings.JINJA2_TEMPLATE_DIRS)48 return Environment(49 loader=FileSystemLoader(searchpath),50 auto_reload=settings.TEMPLATE_DEBUG,51 cache_size=getattr(settings, "JINJA2_CACHE_SIZE", 400),52 extensions=getattr(settings, "JINJA2_EXTENSIONS", ()),53 )545556def get_template(template_name, globals=None):57 """Load a template."""58 try:59 return get_env().get_template(template_name, globals=globals)60 except TemplateNotFound as e:61 raise TemplateDoesNotExist(str(e))626364def select_template(templates, globals=None):65 """Try to load one of the given templates."""66 env = get_env()67 for template in templates:68 try:69 return env.get_template(template, globals=globals)70 except TemplateNotFound:71 continue72 raise TemplateDoesNotExist(", ".join(templates))737475def render_to_string(template_name, context=None, request=None, processors=None):76 """Render a template into a string."""77 context = dict(context or {})78 if request is not None:79 context["request"] = request80 for processor in chain(get_standard_processors(), processors or ()):81 context.update(processor(request))82 return get_template(template_name).render(context)838485def render_to_response(86 template_name, context=None, request=None, processors=None, mimetype=None87):88 """Render a template into a response object."""89 return HttpResponse(90 render_to_string(template_name, context, request, processors), mimetype=mimetype91 )
deleted:ext/inlinegettext.py-83 removed
1# -*- coding: utf-8 -*-2"""3 Inline Gettext4 ~~~~~~~~~~~~~~56 An example extension for Jinja that supports inline gettext calls.7 Requires the i18n extension to be loaded.89 :copyright: (c) 2009 by the Jinja Team.10 :license: BSD.11"""12import re1314from jinja2.exceptions import TemplateSyntaxError15from jinja2.ext import Extension16from jinja2.lexer import count_newlines17from jinja2.lexer import Token181920_outside_re = re.compile(r"\\?(gettext|_)\(")21_inside_re = re.compile(r"\\?[()]")222324class InlineGettext(Extension):25 """This extension implements support for inline gettext blocks::2627 <h1>_(Welcome)</h1>28 <p>_(This is a paragraph)</p>2930 Requires the i18n extension to be loaded and configured.31 """3233 def filter_stream(self, stream):34 paren_stack = 03536 for token in stream:37 if token.type != "data":38 yield token39 continue4041 pos = 042 lineno = token.lineno4344 while 1:45 if not paren_stack:46 match = _outside_re.search(token.value, pos)47 else:48 match = _inside_re.search(token.value, pos)49 if match is None:50 break51 new_pos = match.start()52 if new_pos > pos:53 preval = token.value[pos:new_pos]54 yield Token(lineno, "data", preval)55 lineno += count_newlines(preval)56 gtok = match.group()57 if gtok[0] == "\\":58 yield Token(lineno, "data", gtok[1:])59 elif not paren_stack:60 yield Token(lineno, "block_begin", None)61 yield Token(lineno, "name", "trans")62 yield Token(lineno, "block_end", None)63 paren_stack = 164 else:65 if gtok == "(" or paren_stack > 1:66 yield Token(lineno, "data", gtok)67 paren_stack += gtok == ")" and -1 or 168 if not paren_stack:69 yield Token(lineno, "block_begin", None)70 yield Token(lineno, "name", "endtrans")71 yield Token(lineno, "block_end", None)72 pos = match.end()7374 if pos < len(token.value):75 yield Token(lineno, "data", token.value[pos:])7677 if paren_stack:78 raise TemplateSyntaxError(79 "unclosed gettext expression",80 token.lineno,81 stream.name,82 stream.filename,83 )
deleted:scripts/jinja2-debug.py-50 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""4 Jinja Debug Interface5 ~~~~~~~~~~~~~~~~~~~~~67 Helper script for internal Jinja debugging. Requires Werkzeug.89 :copyright: Copyright 2010 by Armin Ronacher.10 :license: BSD.11"""12from __future__ import print_function1314import sys1516from werkzeug import script1718import jinja21920env = jinja2.Environment(21 extensions=[22 "jinja2.ext.i18n",23 "jinja2.ext.do",24 "jinja2.ext.loopcontrols",25 "jinja2.ext.with_",26 "jinja2.ext.autoescape",27 ],28 autoescape=True,29)303132def shell_init_func():33 def _compile(x):34 print(env.compile(x, raw=True))3536 result = {"e": env, "c": _compile, "t": env.from_string, "p": env.parse}37 for key in jinja2.__all__:38 result[key] = getattr(jinja2, key)39 return result404142def action_compile():43 print(env.compile(sys.stdin.read(), raw=True))444546action_shell = script.make_shell(shell_init_func)474849if __name__ == "__main__":50 script.run()
deleted:scripts/make-release.py-178 removed
1#!/usr/bin/env python2# -*- coding: utf-8 -*-3"""4 make-release5 ~~~~~~~~~~~~67 Helper script that performs a release. Does pretty much everything8 automatically for us.910 :copyright: (c) 2011 by Armin Ronacher.11 :license: BSD, see LICENSE for more details.12"""13from __future__ import print_function1415import os16import re17import sys18from datetime import date19from datetime import datetime20from subprocess import PIPE21from subprocess import Popen2223_date_strip_re = re.compile(r"(?<=\d)(st|nd|rd|th)")242526def parse_changelog():27 with open("CHANGES.rst") as f:28 lineiter = iter(f)29 for line in lineiter:30 match = re.search(r"^Version\s+(.*)", line.strip())3132 if match is None:33 continue3435 version = match.group(1).strip()3637 if next(lineiter).count("-") != len(match.group(0)):38 continue3940 while 1:41 change_info = next(lineiter).strip()4243 if change_info:44 break4546 match = re.search(47 r"(?:codename (.*),\s*)?released on (\w+\s+\d+\w+\s+\d+)(?i)",48 change_info,49 )5051 if match is None:52 continue5354 codename, datestr = match.groups()55 return version, parse_date(datestr), codename565758def bump_version(version):59 try:60 parts = [int(i) for i in version.split(".")]61 except ValueError:62 fail("Current version is not numeric")6364 parts[-1] += 165 return ".".join(map(str, parts))666768def parse_date(string):69 string = _date_strip_re.sub("", string)70 return datetime.strptime(string, "%B %d %Y")717273def set_filename_version(filename, version_number, pattern):74 changed = []7576 def inject_version(match):77 before, old, after = match.groups()78 changed.append(True)79 return before + version_number + after8081 with open(filename) as f:82 contents = re.sub(83 r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern, inject_version, f.read()84 )8586 if not changed:87 fail("Could not find %s in %s", pattern, filename)8889 with open(filename, "w") as f:90 f.write(contents)919293def set_init_version(version):94 info("Setting __init__.py version to %s", version)95 set_filename_version("jinja2/__init__.py", version, "__version__")969798def set_setup_version(version):99 info("Setting setup.py version to %s", version)100 set_filename_version("setup.py", version, "version")101102103def build_and_upload():104 cmd = [sys.executable, "setup.py", "sdist", "bdist_wheel"]105 Popen(cmd).wait()106107108def fail(message, *args):109 print("Error:", message % args, file=sys.stderr)110 sys.exit(1)111112113def info(message, *args):114 print(message % args, file=sys.stderr)115116117def get_git_tags():118 return set(Popen(["git", "tag"], stdout=PIPE).communicate()[0].splitlines())119120121def git_is_clean():122 return Popen(["git", "diff", "--quiet"]).wait() == 0123124125def make_git_commit(message, *args):126 message = message % args127 Popen(["git", "commit", "-am", message]).wait()128129130def make_git_tag(tag):131 info('Tagging "%s"', tag)132 Popen(["git", "tag", tag]).wait()133134135def main():136 os.chdir(os.path.join(os.path.dirname(__file__), ".."))137138 rv = parse_changelog()139140 if rv is None:141 fail("Could not parse changelog")142143 version, release_date, codename = rv144 dev_version = bump_version(version) + ".dev"145146 info(147 "Releasing %s (codename %s, release date %s)",148 version,149 codename,150 release_date.strftime("%d/%m/%Y"),151 )152 tags = get_git_tags()153154 if version in tags:155 fail('Version "%s" is already tagged', version)156157 if release_date.date() != date.today():158 fail("Release date is not today (%s != %s)", release_date.date(), date.today())159160 if not git_is_clean():161 fail("You have uncommitted changes in git")162163 try:164 __import__("wheel")165 except ImportError:166 fail("You need to install the wheel package.")167168 set_init_version(version)169 set_setup_version(version)170 make_git_commit("Bump version number to %s", version)171 make_git_tag(version)172 build_and_upload()173 set_init_version(dev_version)174 set_setup_version(dev_version)175176177if __name__ == "__main__":178 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]1011# Specify a configuration file.12#rcfile=1314# Profiled execution.15profile=no1617# Add <file or directory> to the black list. It should be a base name, not a18# path. You may set this option multiple times.19ignore=.svn2021# Pickle collected data for later comparisons.22persistent=yes2324# Set the cache size for astng objects.25cache-size=5002627# List of plugins (as comma separated values of python modules names) to load,28# usually to register additional checkers.29load-plugins=303132[MESSAGES CONTROL]3334# Enable only checker(s) with the given id(s). This option conflict with the35# disable-checker option36#enable-checker=3738# Enable all checker(s) except those with the given id(s). This option conflict39# with the disable-checker option40#disable-checker=4142# Enable all messages in the listed categories.43#enable-msg-cat=4445# Disable all messages in the listed categories.46#disable-msg-cat=4748# Enable the message(s) with the given id(s).49#enable-msg=5051# Disable the message(s) with the given id(s).52disable-msg=C0323,W0142,C0301,C0103,C0111,E0213,C0302,C0203,W0703,R0201535455[REPORTS]5657# set the output format. Available formats are text, parseable, colorized and58# html59output-format=colorized6061# Include message's id in output62include-ids=yes6364# 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]".67files-output=no6869# Tells whether to display a full report or only the messages70reports=yes7172# 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).77evaluation=10.0 - ((float(5 * error + warning + refactor + convention) / statement) * 10)7879# Add a comment according to your evaluation note. This is used by the global80# evaluation report (R0004).81comment=no8283# Enable the report(s) with the given id(s).84#enable-report=8586# Disable the report(s) with the given id(s).87#disable-report=888990# checks for91# * unused variables / imports92# * undefined variables93# * redefinition of variable from builtins or from an outer scope94# * use of variable before assignment95#96[VARIABLES]9798# Tells whether we should check for unused import in __init__ files.99init-import=no100101# A regular expression matching names used for dummy variables (i.e. not used).102dummy-variables-rgx=_|dummy103104# List of additional names supposed to be defined in builtins. Remember that105# you should avoid to define new builtins when possible.106additional-builtins=107108109# try to find bugs in the code using type inference110#111[TYPECHECK]112113# Tells whether missing members accessed in mixin class should be ignored. A114# mixin class is detected if its name ends with "mixin" (case insensitive).115ignore-mixin-members=yes116117# When zope mode is activated, consider the acquired-members option to ignore118# access to some undefined attributes.119zope=no120121# 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)123acquired-members=REQUEST,acl_users,aq_parent124125126# 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]137138# Required attributes for module, separated by a comma139required-attributes=140141# Regular expression which should only match functions or classes name which do142# not require a docstring143no-docstring-rgx=__.*__144145# Regular expression which should only match correct module names146module-rgx=(([a-z_][a-z0-9_]*)|([A-Z][a-zA-Z0-9]+))$147148# Regular expression which should only match correct module level names149const-rgx=(([A-Z_][A-Z1-9_]*)|(__.*__))$150151# Regular expression which should only match correct class names152class-rgx=[A-Z_][a-zA-Z0-9]+$153154# Regular expression which should only match correct function names155function-rgx=[a-z_][a-z0-9_]*$156157# Regular expression which should only match correct method names158method-rgx=[a-z_][a-z0-9_]*$159160# Regular expression which should only match correct instance attribute names161attr-rgx=[a-z_][a-z0-9_]*$162163# Regular expression which should only match correct argument names164argument-rgx=[a-z_][a-z0-9_]*$165166# Regular expression which should only match correct variable names167variable-rgx=[a-z_][a-z0-9_]*$168169# Regular expression which should only match correct list comprehension /170# generator expression variable names171inlinevar-rgx=[A-Za-z_][A-Za-z0-9_]*$172173# Good variable names which should always be accepted, separated by a comma174good-names=i,j,k,ex,Run,_175176# Bad variable names which should always be refused, separated by a comma177bad-names=foo,bar,baz,toto,tutu,tata178179# List of builtins function names that should not be used, separated by a comma180bad-functions=apply,input181182183# checks for sign of poor/misdesign:184# * number of methods, attributes, local variables...185# * size, complexity of functions, methods186#187[DESIGN]188189# Maximum number of arguments for function / method190max-args=12191192# Maximum number of locals for function / method body193max-locals=30194195# Maximum number of return / yield for function / method body196max-returns=12197198# Maximum number of branch for function / method body199max-branchs=30200201# Maximum number of statements in function / method body202max-statements=60203204# Maximum number of parents for a class (see R0901).205max-parents=7206207# Maximum number of attributes for a class (see R0902).208max-attributes=20209210# Minimum number of public methods for a class (see R0903).211min-public-methods=0212213# Maximum number of public methods for a class (see R0904).214max-public-methods=20215216217# checks for218# * external modules dependencies219# * relative / wildcard imports220# * cyclic imports221# * uses of deprecated modules222#223[IMPORTS]224225# Deprecated modules which should not be used, separated by a comma226deprecated-modules=regsub,string,TERMIOS,Bastion,rexec227228# Create a graph of every (i.e. internal and external) dependencies in the229# given file (report R0402 must not be disabled)230import-graph=231232# Create a graph of external dependencies in the given file (report R0402 must233# not be disabled)234ext-import-graph=235236# Create a graph of internal dependencies in the given file (report R0402 must237# not be disabled)238int-import-graph=239240241# 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]250251# 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.253ignore-iface-methods=isImplementedBy,deferred,extends,names,namesAndDescriptions,queryDescriptionFor,getBases,getDescriptionFor,getDoc,getName,getTaggedValue,getTaggedValueTags,isEqualOrExtendedBy,setTaggedValue,isImplementedByInstancesOf,adaptWith,is_implemented_by254255# List of method names used to declare (i.e. assign) instance attributes.256defining-attr-methods=__init__,__new__,setUp257258259# 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]264265# Minimum lines number of a similarity.266min-similarity-lines=10267268# Ignore comments when computing similarities.269ignore-comments=yes270271# Ignore docstrings when computing similarities.272ignore-docstrings=yes273274275# 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]280281# List of note tags to take in consideration, separated by a comma.282notes=FIXME,XXX,TODO283284285# checks for :286# * unauthorized constructions287# * strict indentation288# * line length289# * use of <> instead of !=290#291[FORMAT]292293# Maximum number of characters on a single line.294max-line-length=90295296# Maximum number of lines in a module297max-module-lines=1000298299# String used as indentation unit. This is usually " " (4 spaces) or "\t" (1300# tab).301indent-string=' '
modified:src/jinja2/ext.py-4 removed
109 unmodified lines
110 """It's passed a :class:`~jinja2.lexer.TokenStream` that can be used111 to filter tokens returned. This method has to return an iterable of112 :class:`~jinja2.lexer.Token`\\s, but it doesn't have to return a113 :class:`~jinja2.lexer.TokenStream`.114115 In the `ext` folder of the Jinja source distribution there is a file116 called `inlinegettext.py` which implements a filter that utilizes this117 method.114 """115 return stream116117 def parse(self, parser):
600 unmodified lines