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
Provenance
- Commit
e492255- Tree
5c32f9e- Author
David Lord <davidism@gmail.com>- Committer
David Lord <davidism@gmail.com>- Parent
143667d
33 files changed+171 added−2736 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+83 added
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+14+from jinja2.exceptions import TemplateSyntaxError15+from jinja2.ext import Extension16+from jinja2.lexer import count_newlines17+from jinja2.lexer import Token18+19+20+_outside_re = re.compile(r"\\?(gettext|_)\(")21+_inside_re = re.compile(r"\\?[()]")22+23+24+class InlineGettext(Extension):25+ """This extension implements support for inline gettext blocks::26+27+ <h1>_(Welcome)</h1>28+ <p>_(This is a paragraph)</p>29+30+ Requires the i18n extension to be loaded and configured.31+ """32+33+ def filter_stream(self, stream):34+ paren_stack = 035+36+ for token in stream:37+ if token.type != "data":38+ yield token39+ continue40+41+ pos = 042+ lineno = token.lineno43+44+ 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()73+74+ if pos < len(token.value):75+ yield Token(lineno, "data", token.value[pos:])76+77+ 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
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 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 linesdeleted: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
1234567891011121314151617181920212223242526272829{% extends "layout.html" %}{% block page_title %}Index Page{% endblock %}{% block body %} {% for article in articles %} {% if article.published %} <div class="article"> <h2><a href="{{ article.href }}">{{ article.title }}</a></h2> <p class="meta">written by <a href="{{ article.user.href }}">{{ article.user.username }}</a> on {{ article.pub_date|dateformat }}</p> <div class="text">{{ article.body|safe }}</div> </div> {% endif %} {% endfor %} {% form %} <dl> <dt>Name</dt> <dd>{% input_field 'name' %}</dd> <dt>E-Mail</dt> <dd>{% input_field 'email' %}</dd> <dt>URL</dt> <dd>{% input_field 'url' %}</dd> <dt>Comment</dt> <dd>{% textarea 'comment' %}</dd> <dt>Captcha</dt> <dd>{% input_field 'captcha' %}</dd> </dl> {% input_field '' 'submit' 'Submit' %} {% input_field 'cancel' 'submit' 'Cancel' %} {% endform %}{% endblock %}deleted:examples/rwbench/django/layout.html-29 removed
1234567891011121314151617181920212223242526272829<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html><head> <title>{% block page_title %}{% endblock %} | RealWorld Benchmark</title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body> <div class="contents"> <div class="header"> <h1>RealWorld Benchmark</h1> <blockquote><p> A less stupid benchmark for Mako and Jinja to get an impression how code changes affect runtime performance. </p></blockquote> </div> <ul class="navigation"> {% for href, caption in page_navigation %} <li><a href="{{ href }}">{{ caption }}</a></li> {% endfor %} </ul> <div class="body"> {% block body %}{% endblock %} </div> <div class="footer"> © Copyright 2008 by I don't know who. </div> </div></body></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-126 removed
1-# -*- coding: utf-8 -*-2-from os.path import join3-4-from django import template as django_template_module5-from django.conf import settings6-from django.template import Context as DjangoContext7-from django.template import loader as django_loader8-from django.template import Node9-from django.template import TokenParser10-from django.template import Variable11-from rwbench import dateformat12-from rwbench import ROOT13-14-settings.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-)23-24-# for django extensions. We monkey patch our extensions in so that25-# we don't have to initialize a more complex django setup.26-django_extensions = django_template_module.Library()27-django_template_module.builtins.append(django_extensions)28-29-django_extensions.filter(dateformat)30-31-32-def var_or_none(x):33- if x is not None:34- return Variable(x)35-36-37-# and more django extensions38-@django_extensions.tag39-def 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)45-46-47-@django_extensions.tag48-def 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)54-55-56-@django_extensions.tag57-def 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)65-66-67-class 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)72-73- 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}))83-84-85-class 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)91-92- 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- )107-108-109-class FormNode(Node):110- def __init__(self, body, action=None, method=None):111- self.body = body112- self.action = action113- self.method = method114-115- 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- ~~~~~~~~~~~~~~~~~~~~~~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-15-import sys16-from datetime import datetime17-from os.path import abspath18-from os.path import dirname19-from os.path import join20-from pstats import Stats21-from random import choice22-from random import randrange23-from timeit import Timer24-25-from djangoext import django_loader26-from djangoext import DjangoContext27-from genshi.template import TemplateLoader as GenshiTemplateLoader28-from mako.lookup import TemplateLookup29-30-from jinja2 import Environment31-from jinja2 import FileSystemLoader32-from jinja2.utils import generate_lorem_ipsum33-34-try:35- from cProfile import Profile36-except ImportError:37- from profile import Profile38-39-ROOT = abspath(dirname(__file__))40-41-42-def dateformat(x):43- return x.strftime("%Y-%m-%d")44-45-46-jinja_env = Environment(loader=FileSystemLoader(join(ROOT, "jinja")))47-jinja_env.filters["dateformat"] = dateformat48-mako_lookup = TemplateLookup(directories=[join(ROOT, "mako")])49-genshi_loader = GenshiTemplateLoader([join(ROOT, "genshi")])50-51-52-class 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 = True61-62-63-class User(object):64- def __init__(self, username):65- self.href = "/user/%s" % username66- self.username = username67-68-69-users = map(User, [u"John Doe", u"Jane Doe", u"Peter Somewhat"])70-articles = map(Article, range(20))71-navigation = [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-] * 579-80-context = dict(users=users, articles=articles, page_navigation=navigation)81-82-jinja_template = jinja_env.get_template("index.html")83-mako_template = mako_lookup.get_template("index.html")84-genshi_template = genshi_loader.load("index.html")85-86-87-def test_jinja():88- jinja_template.render(context)89-90-91-def test_mako():92- mako_template.render_unicode(**context)93-94-95-def 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))100-101-102-def test_genshi():103- genshi_template.generate(**context).render("html", doctype="html")104-105-106-if __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- )115-116- 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-"""6-import cgi7-import sys8-from timeit import Timer9-10-from jinja2 import Environment as JinjaEnvironment11-from jinja2._compat import text_type12-13-context = {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-}19-20-jinja_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-)57-58-59-def test_jinja():60- jinja_template.render(context)61-62-63-try:64- from tornado.template import Template65-except ImportError:66- test_tornado = None67-else: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- )103-104- def test_tornado():105- tornado_template.generate(**context)106-107-108-try:109- from django.conf import settings110-111- settings.configure()112- from django.template import Template as DjangoTemplate, Context as DjangoContext113-except ImportError:114- test_django = None115-else: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- )147-148- 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)156-157-158-try:159- from mako.template import Template as MakoTemplate160-except ImportError:161- test_mako = None162-else: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- )195-196- def test_mako():197- mako_template.render(**context)198-199-200-try:201- from genshi.template import MarkupTemplate as GenshiTemplate202-except ImportError:203- test_genshi = None204-else: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- )232-233- def test_genshi():234- genshi_template.generate(**context).render("html", strip_whitespace=False)235-236-237-try:238- from Cheetah.Template import Template as CheetahTemplate239-except ImportError:240- test_cheetah = None241-else: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- )276-277- def test_cheetah():278- text_type(cheetah_template)279-280-281-try:282- import tenjin283-except ImportError:284- test_tenjin = None285-else: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- )319-320- def test_tenjin():321- tenjin_template.render(context, locals())322-323-324-try:325- from spitfire.compiler import util as SpitfireTemplate326- from spitfire.compiler.analyzer import o2_options as spitfire_optimizer327-except ImportError:328- test_spitfire = None329-else: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})366-367- def test_spitfire():368- spitfire_template(search_list=[spitfire_context]).main()369-370-371-try:372- from chameleon.zpt.template import PageTemplate373-except ImportError:374- test_chameleon = None375-else: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]" \388-tal: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- ]407-408- def test_chameleon():409- chameleon_template.render(**chameleon_context)410-411-412-try:413- from chameleon.zpt.template import PageTemplate414- from chameleon.genshi import language415-except ImportError:416- test_chameleon_genshi = None417-else: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- ]449-450- def test_chameleon_genshi():451- chameleon_genshi_template.render(**chameleon_genshi_context)452-453-454-sys.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-)467-468-469-for 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))488-sys.stdout.write("-" * 80 + "\n")489-sys.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
1-from __future__ import print_function2-3-try:4- from cProfile import Profile5-except ImportError:6- from profile import Profile7-from pstats import Stats8-from jinja2 import Environment as JinjaEnvironment9-10-context = {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-}16-17-source = """\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-"""44-jinja_template = JinjaEnvironment(45- line_statement_prefix="%", variable_start_string="${", variable_end_string="}"46-).from_string(source)47-print(jinja_template.environment.compile(source, raw=True))48-49-50-p = Profile()51-p.runcall(lambda: jinja_template.render(context))52-stats = Stats(p)53-stats.sort_stats("time", "calls")54-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-812 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-19- os.environ["DJANGO_SETTINGS_MODULE"] = "yourapplication.settings"20- from yourapplication.foo.templatetags.bar import MyNode21-22- from django2jinja import Writer, convert_templates23-24- 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()33-34- writer = Writer()35- writer.node_handlers[MyNode] = write_my_node36- convert_templates("/path/to/output/folder", writer=writer)37-38-Here is an example hos to automatically translate your django39-variables to jinja2::40-41- 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)68-69-For details about the writing process have a look at the module code.70-71-:copyright: (c) 2009 by the Jinja Team.72-:license: BSD.73-"""74-from __future__ import print_function75-76-import os77-import re78-import sys79-80-from django.conf import settings81-from django.template import defaulttags as core_tags82-from django.template import FilterExpression83-from django.template import libraries84-from django.template import loader85-from django.template import loader_tags86-from django.template import TextNode87-from django.template import TOKEN_TEXT88-from django.template import TOKEN_VAR89-from django.template import Variable90-from django.template.debug import DebugVariableNode as VariableNode91-from django.templatetags import i18n as i18n_tags92-93-from jinja2 import defaults94-95-_node_handlers = {}96-_resolved_filters = {}97-_newline_re = re.compile(r"(?:\r\n|\r|\n)")98-99-# 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__104-105-106-def _fixed_cycle_init(self, cyclevars, variable_name=None):107- self.raw_cycle_vars = map(Variable, cyclevars)108- _old_cycle_init(self, cyclevars, variable_name)109-110-111-core_tags.CycleNode.__init__ = _fixed_cycle_init112-113-114-def node(cls):115- def proxy(f):116- _node_handlers[cls] = f117- return f118-119- return proxy120-121-122-def 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()131-132- 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 filename138-139- def translate(f, loadname):140- template = loader.get_template(loadname)141- original = writer.stream142- writer.stream = f143- writer.body(template.nodelist)144- writer.stream = original145-146- if callback is None:147-148- def callback(template):149- print(template)150-151- 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)163-164-165-class Writer(object):166- """The core writer class."""167-168- 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 = env204-205- 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 += 1210-211- def leave_loop(self):212- """Reverse of enter_loop."""213- self._loop_depth -= 1214-215- @property216- def in_loop(self):217- """True if we are in a loop."""218- return self._loop_depth > 0219-220- def write(self, s):221- """Writes stuff to the stream."""222- self.stream.write(s.encode(settings.FILE_CHARSET))223-224- 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()231-232- def _post_open(self):233- if self.spaceless:234- self.write("- ")235- else:236- self.write(" ")237-238- def _pre_close(self):239- if self.spaceless:240- self.write(" -")241- else:242- self.write(" ")243-244- def start_variable(self):245- """Start a variable."""246- self.write(self.variable_start_string)247- self._post_open()248-249- 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)255-256- def start_block(self):257- """Starts a block."""258- self.write(self.block_start_string)259- self._post_open()260-261- def end_block(self):262- """Ends a block."""263- self._pre_close()264- self.write(self.block_end_string)265-266- def tag(self, name):267- """Like `print_expr` just for blocks."""268- self.start_block()269- self.write(name)270- self.end_block()271-272- def variable(self, name):273- """Prints a variable. This performs variable name274- transformation.275- """276- self.write(self.translate_variable_name(name))277-278- 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)284-285- 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(")")314-315- 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, lineno327-328- 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)334-335- 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:]339-340- 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 var346-347- 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)356-357- 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- )369-370- def body(self, nodes):371- """Calls node() for every node in the iterable passed."""372- for node in nodes:373- self.node(node)374-375-376-@node(TextNode)377-def text_node(writer, node):378- writer.write(node.s)379-380-381-@node(Variable)382-def 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(")")392-393-394-@node(VariableNode)395-def 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()405-406-407-@node(FilterExpression)408-def filter_expression(writer, node):409- writer.node(node.var)410- writer.filters(node.filters)411-412-413-@node(core_tags.CommentNode)414-def comment_tag(writer, node):415- pass416-417-418-@node(core_tags.DebugNode)419-def 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()")426-427-428-@node(core_tags.ForNode)429-def 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")447-448-449-@node(core_tags.IfNode)450-def 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"456-457- 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")469-470-471-@node(core_tags.IfEqualNode)472-def 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")487-488-489-@node(loader_tags.BlockNode)490-def 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")497-498-499-@node(loader_tags.ExtendsNode)500-def 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)509-510-511-@node(loader_tags.ConstantIncludeNode)512-@node(loader_tags.IncludeNode)513-def 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()521-522-523-@node(core_tags.CycleNode)524-def 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()543-544-545-@node(core_tags.FilterNode)546-def 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")553-554-555-@node(core_tags.AutoEscapeControlNode)556-def autoescape_control(writer, node):557- original = writer.autoescape558- writer.autoescape = node.setting559- writer.body(node.nodelist)560- writer.autoescape = original561-562-563-@node(core_tags.SpacelessNode)564-def 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 = original577-578-579-@node(core_tags.TemplateTagNode)580-def 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()595-596-597-@node(core_tags.URLNode)598-def 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()618-619-620-@node(core_tags.WidthRatioNode)621-def 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)636-637-638-@node(core_tags.WithNode)639-def 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)650-651-652-@node(core_tags.RegroupNode)653-def 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()675-676-677-@node(core_tags.LoadNode)678-def warn_load(writer, node):679- writer.warn("load statement used which was ignored on conversion", node)680-681-682-@node(i18n_tags.GetAvailableLanguagesNode)683-def 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- )689-690-691-@node(i18n_tags.GetCurrentLanguageNode)692-def 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- )698-699-700-@node(i18n_tags.GetCurrentLanguageBidiNode)701-def 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- )707-708-709-@node(i18n_tags.TranslateNode)710-def 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()717-718-719-@node(i18n_tags.BlockTranslateNode)720-def translate_block(writer, node):721- first_var = []722- variables = set()723-724- def touch_var(name):725- variables.add(name)726- if not first_var:727- first_var.append(name)728-729- 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)736-737- 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)747-748- 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)756-757- 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")767-768-769-@node("SimpleNode")770-def 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)780-781- 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- return788-789- first_var = node.vars_to_resolve[0]790- args = node.vars_to_resolve[1:]791- writer.start_variable()792-793- # Copied from Writer.filters()794- writer.node(first_var)795-796- 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()809-810-811-# get rid of node now, it shouldn't be used normally812-del nodedeleted:ext/django2jinja/example.py-7 removed
1-from django.conf import settings2-from django2jinja import convert_templates3-from django2jinja import Writer4-5-settings.configure(TEMPLATE_DIRS=["templates"], TEMPLATE_DEBUG=True)6-writer = Writer(use_jinja_autoescape=True)7-convert_templates("converted", writer=writer)deleted:ext/djangojinja2.py-91 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-23-from django.conf import settings24-from django.http import HttpResponse25-from django.template import TemplateDoesNotExist26-from django.template.context import get_standard_processors27-28-from jinja2 import Environment29-from jinja2 import FileSystemLoader30-from jinja2 import TemplateNotFound31-32-33-# the environment is unconfigured until the first template is loaded.34-_jinja_env = None35-36-37-def 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_env43-44-45-def 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- )54-55-56-def 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))62-63-64-def 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))73-74-75-def 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)83-84-85-def 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- ~~~~~~~~~~~~~~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-14-from jinja2.exceptions import TemplateSyntaxError15-from jinja2.ext import Extension16-from jinja2.lexer import count_newlines17-from jinja2.lexer import Token18-19-20-_outside_re = re.compile(r"\\?(gettext|_)\(")21-_inside_re = re.compile(r"\\?[()]")22-23-24-class InlineGettext(Extension):25- """This extension implements support for inline gettext blocks::26-27- <h1>_(Welcome)</h1>28- <p>_(This is a paragraph)</p>29-30- Requires the i18n extension to be loaded and configured.31- """32-33- def filter_stream(self, stream):34- paren_stack = 035-36- for token in stream:37- if token.type != "data":38- yield token39- continue40-41- pos = 042- lineno = token.lineno43-44- 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()73-74- if pos < len(token.value):75- yield Token(lineno, "data", token.value[pos:])76-77- 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- ~~~~~~~~~~~~~~~~~~~~~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-14-import sys15-16-from werkzeug import script17-18-import jinja219-20-env = 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-)30-31-32-def shell_init_func():33- def _compile(x):34- print(env.compile(x, raw=True))35-36- 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 result40-41-42-def action_compile():43- print(env.compile(sys.stdin.read(), raw=True))44-45-46-action_shell = script.make_shell(shell_init_func)47-48-49-if __name__ == "__main__":50- script.run()deleted:scripts/make-release.py-178 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 date19-from datetime import datetime20-from subprocess import PIPE21-from subprocess import Popen22-23-_date_strip_re = re.compile(r"(?<=\d)(st|nd|rd|th)")24-25-26-def 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())31-32- if match is None:33- continue34-35- version = match.group(1).strip()36-37- if next(lineiter).count("-") != len(match.group(0)):38- continue39-40- while 1:41- change_info = next(lineiter).strip()42-43- if change_info:44- break45-46- match = re.search(47- r"(?:codename (.*),\s*)?released on (\w+\s+\d+\w+\s+\d+)(?i)",48- change_info,49- )50-51- if match is None:52- continue53-54- codename, datestr = match.groups()55- return version, parse_date(datestr), codename56-57-58-def bump_version(version):59- try:60- parts = [int(i) for i in version.split(".")]61- except ValueError:62- fail("Current version is not numeric")63-64- parts[-1] += 165- return ".".join(map(str, parts))66-67-68-def parse_date(string):69- string = _date_strip_re.sub("", string)70- return datetime.strptime(string, "%B %d %Y")71-72-73-def set_filename_version(filename, version_number, pattern):74- changed = []75-76- def inject_version(match):77- before, old, after = match.groups()78- changed.append(True)79- return before + version_number + after80-81- with open(filename) as f:82- contents = re.sub(83- r"^(\s*%s\s*=\s*')(.+?)(')(?sm)" % pattern, inject_version, f.read()84- )85-86- if not changed:87- fail("Could not find %s in %s", pattern, filename)88-89- with open(filename, "w") as f:90- f.write(contents)91-92-93-def set_init_version(version):94- info("Setting __init__.py version to %s", version)95- set_filename_version("jinja2/__init__.py", version, "__version__")96-97-98-def set_setup_version(version):99- info("Setting setup.py version to %s", version)100- set_filename_version("setup.py", version, "version")101-102-103-def build_and_upload():104- cmd = [sys.executable, "setup.py", "sdist", "bdist_wheel"]105- Popen(cmd).wait()106-107-108-def fail(message, *args):109- print("Error:", message % args, file=sys.stderr)110- sys.exit(1)111-112-113-def info(message, *args):114- print(message % args, file=sys.stderr)115-116-117-def get_git_tags():118- return set(Popen(["git", "tag"], stdout=PIPE).communicate()[0].splitlines())119-120-121-def git_is_clean():122- return Popen(["git", "diff", "--quiet"]).wait() == 0123-124-125-def make_git_commit(message, *args):126- message = message % args127- Popen(["git", "commit", "-am", message]).wait()128-129-130-def make_git_tag(tag):131- info('Tagging "%s"', tag)132- Popen(["git", "tag", tag]).wait()133-134-135-def main():136- os.chdir(os.path.join(os.path.dirname(__file__), ".."))137-138- rv = parse_changelog()139-140- if rv is None:141- fail("Could not parse changelog")142-143- version, release_date, codename = rv144- dev_version = bump_version(version) + ".dev"145-146- 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()153-154- if version in tags:155- fail('Version "%s" is already tagged', version)156-157- if release_date.date() != date.today():158- fail("Release date is not today (%s != %s)", release_date.date(), date.today())159-160- if not git_is_clean():161- fail("You have uncommitted changes in git")162-163- try:164- __import__("wheel")165- except ImportError:166- fail("You need to install the wheel package.")167-168- 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)175-176-177-if __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]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=' 'modified:src/jinja2/ext.py-4 removed
109 unmodified lines110 """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`.114-115- 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 stream116 117 def parse(self, parser):600 unmodified lines