diff options
author | David Lord <davidism@gmail.com> | 2020-01-10 07:46:18 -0800 |
---|---|---|
committer | David Lord <davidism@gmail.com> | 2020-01-10 07:54:39 -0800 |
commit | 04c8787155137206d58d6ee147d06482c1a8b598 (patch) | |
tree | 3d0abf84d0296a15fdd949bcbf8570ae4b93d912 /examples | |
parent | d177eeb295e2552227bf569d703ca32bb509a628 (diff) | |
download | jinja-04c8787155137206d58d6ee147d06482c1a8b598.tar.gz |
apply black
Diffstat (limited to 'examples')
-rw-r--r-- | examples/basic/cycle.py | 12 | ||||
-rw-r--r-- | examples/basic/debugger.py | 4 | ||||
-rw-r--r-- | examples/basic/inheritance.py | 16 | ||||
-rw-r--r-- | examples/basic/test.py | 20 | ||||
-rw-r--r-- | examples/basic/test_filter_and_linestatements.py | 10 | ||||
-rw-r--r-- | examples/basic/test_loop_filter.py | 6 | ||||
-rw-r--r-- | examples/basic/translate.py | 20 | ||||
-rw-r--r-- | examples/bench.py | 169 | ||||
-rw-r--r-- | examples/profile.py | 13 | ||||
-rw-r--r-- | examples/rwbench/djangoext.py | 55 | ||||
-rw-r--r-- | examples/rwbench/rwbench.py | 62 |
11 files changed, 230 insertions, 157 deletions
diff --git a/examples/basic/cycle.py b/examples/basic/cycle.py index 63d8a425..25dcb0b0 100644 --- a/examples/basic/cycle.py +++ b/examples/basic/cycle.py @@ -2,11 +2,17 @@ from __future__ import print_function from jinja2 import Environment -env = Environment(line_statement_prefix="#", variable_start_string="${", variable_end_string="}") -print(env.from_string("""\ +env = Environment( + line_statement_prefix="#", variable_start_string="${", variable_end_string="}" +) +print( + env.from_string( + """\ <ul> # for item in range(10) <li class="${loop.cycle('odd', 'even')}">${item}</li> # endfor </ul>\ -""").render()) +""" + ).render() +) diff --git a/examples/basic/debugger.py b/examples/basic/debugger.py index b74125b0..d3c1a60a 100644 --- a/examples/basic/debugger.py +++ b/examples/basic/debugger.py @@ -3,6 +3,6 @@ from __future__ import print_function from jinja2 import Environment from jinja2.loaders import FileSystemLoader -env = Environment(loader=FileSystemLoader('templates')) -tmpl = env.get_template('broken.html') +env = Environment(loader=FileSystemLoader("templates")) +tmpl = env.get_template("broken.html") print(tmpl.render(seq=[3, 2, 4, 5, 3, 2, 0, 2, 1])) diff --git a/examples/basic/inheritance.py b/examples/basic/inheritance.py index 647f42cd..a3073a5e 100644 --- a/examples/basic/inheritance.py +++ b/examples/basic/inheritance.py @@ -3,9 +3,13 @@ from __future__ import print_function from jinja2 import Environment from jinja2.loaders import DictLoader -env = Environment(loader=DictLoader({ -'a': '''[A[{% block body %}{% endblock %}]]''', -'b': '''{% extends 'a' %}{% block body %}[B]{% endblock %}''', -'c': '''{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}''' -})) -print(env.get_template('c').render()) +env = Environment( + loader=DictLoader( + { + "a": """[A[{% block body %}{% endblock %}]]""", + "b": """{% extends 'a' %}{% block body %}[B]{% endblock %}""", + "c": """{% extends 'b' %}{% block body %}###{{ super() }}###{% endblock %}""", + } + ) +) +print(env.get_template("c").render()) diff --git a/examples/basic/test.py b/examples/basic/test.py index 04a6adc7..80b9d1f0 100644 --- a/examples/basic/test.py +++ b/examples/basic/test.py @@ -3,8 +3,10 @@ from __future__ import print_function from jinja2 import Environment from jinja2.loaders import DictLoader -env = Environment(loader=DictLoader({ -'child.html': u'''\ +env = Environment( + loader=DictLoader( + { + "child.html": u"""\ {% extends master_layout or 'master.html' %} {% include helpers = 'helpers.html' %} {% macro get_the_answer() %}42{% endmacro %} @@ -13,15 +15,17 @@ env = Environment(loader=DictLoader({ {{ get_the_answer() }} {{ helpers.conspirate() }} {% endblock %} -''', -'master.html': u'''\ +""", + "master.html": u"""\ <!doctype html> <title>{{ title }}</title> {% block body %}{% endblock %} -''', -'helpers.html': u'''\ +""", + "helpers.html": u"""\ {% macro conspirate() %}23{% endmacro %} -''' -})) +""", + } + ) +) tmpl = env.get_template("child.html") print(tmpl.render()) diff --git a/examples/basic/test_filter_and_linestatements.py b/examples/basic/test_filter_and_linestatements.py index c18731c1..673b67ed 100644 --- a/examples/basic/test_filter_and_linestatements.py +++ b/examples/basic/test_filter_and_linestatements.py @@ -2,8 +2,11 @@ from __future__ import print_function from jinja2 import Environment -env = Environment(line_statement_prefix='%', variable_start_string="${", variable_end_string="}") -tmpl = env.from_string("""\ +env = Environment( + line_statement_prefix="%", variable_start_string="${", variable_end_string="}" +) +tmpl = env.from_string( + """\ % macro foo() ${caller(42)} % endmacro @@ -21,5 +24,6 @@ tmpl = env.from_string("""\ - ${item} % endfor % endfilter -""") +""" +) print(tmpl.render(seq=range(10))) diff --git a/examples/basic/test_loop_filter.py b/examples/basic/test_loop_filter.py index d5b908b8..39be08d6 100644 --- a/examples/basic/test_loop_filter.py +++ b/examples/basic/test_loop_filter.py @@ -2,12 +2,14 @@ from __future__ import print_function from jinja2 import Environment -tmpl = Environment().from_string("""\ +tmpl = Environment().from_string( + """\ <ul> {%- for item in [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] if item % 2 == 0 %} <li>{{ loop.index }} / {{ loop.length }}: {{ item }}</li> {%- endfor %} </ul> if condition: {{ 1 if foo else 0 }} -""") +""" +) print(tmpl.render(foo=True)) diff --git a/examples/basic/translate.py b/examples/basic/translate.py index bbe445a1..fda8f7a1 100644 --- a/examples/basic/translate.py +++ b/examples/basic/translate.py @@ -2,15 +2,17 @@ from __future__ import print_function from jinja2 import Environment -env = Environment(extensions=['jinja2.ext.i18n']) -env.globals['gettext'] = { - 'Hello %(user)s!': 'Hallo %(user)s!' -}.__getitem__ -env.globals['ngettext'] = lambda s, p, n: { - '%(count)s user': '%(count)d Benutzer', - '%(count)s users': '%(count)d Benutzer' +env = Environment(extensions=["jinja2.ext.i18n"]) +env.globals["gettext"] = {"Hello %(user)s!": "Hallo %(user)s!"}.__getitem__ +env.globals["ngettext"] = lambda s, p, n: { + "%(count)s user": "%(count)d Benutzer", + "%(count)s users": "%(count)d Benutzer", }[n == 1 and s or p] -print(env.from_string("""\ +print( + env.from_string( + """\ {% trans %}Hello {{ user }}!{% endtrans %} {% trans count=users|count %}{{ count }} user{% pluralize %}{{ count }} users{% endtrans %} -""").render(user="someone", users=[1, 2, 3])) +""" + ).render(user="someone", users=[1, 2, 3]) +) diff --git a/examples/bench.py b/examples/bench.py index 7d988cd9..473928b9 100644 --- a/examples/bench.py +++ b/examples/bench.py @@ -10,15 +10,16 @@ from timeit import Timer from jinja2 import Environment as JinjaEnvironment context = { - 'page_title': 'mitsuhiko\'s benchmark', - 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)] + "page_title": "mitsuhiko's benchmark", + "table": [ + dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10) for x in range(1000) + ], } jinja_template = JinjaEnvironment( - line_statement_prefix='%', - variable_start_string="${", - variable_end_string="}" -).from_string("""\ + line_statement_prefix="%", variable_start_string="${", variable_end_string="}" +).from_string( + """\ <!doctype html> <html> <head> @@ -50,17 +51,21 @@ jinja_template = JinjaEnvironment( </div> </body> </html>\ -""") +""" +) + def test_jinja(): jinja_template.render(context) + try: from tornado.template import Template except ImportError: test_tornado = None else: - tornado_template = Template("""\ + tornado_template = Template( + """\ <!doctype html> <html> <head> @@ -92,19 +97,23 @@ else: </div> </body> </html>\ -""") +""" + ) def test_tornado(): tornado_template.generate(**context) + try: from django.conf import settings + settings.configure() from django.template import Template as DjangoTemplate, Context as DjangoContext except ImportError: test_django = None else: - django_template = DjangoTemplate("""\ + django_template = DjangoTemplate( + """\ <!doctype html> <html> <head> @@ -132,20 +141,26 @@ else: </div> </body> </html>\ -""") +""" + ) def test_django(): c = DjangoContext(context) - c['navigation'] = [('index.html', 'Index'), ('downloads.html', 'Downloads'), - ('products.html', 'Products')] + c["navigation"] = [ + ("index.html", "Index"), + ("downloads.html", "Downloads"), + ("products.html", "Products"), + ] django_template.render(c) + try: from mako.template import Template as MakoTemplate except ImportError: test_mako = None else: - mako_template = MakoTemplate("""\ + mako_template = MakoTemplate( + """\ <!doctype html> <html> <head> @@ -173,17 +188,20 @@ else: </div> </body> </html>\ -""") +""" + ) def test_mako(): mako_template.render(**context) + try: from genshi.template import MarkupTemplate as GenshiTemplate except ImportError: test_genshi = None else: - genshi_template = GenshiTemplate("""\ + genshi_template = GenshiTemplate( + """\ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/"> <head> <title>${page_title}</title> @@ -207,17 +225,20 @@ else: </div> </body> </html>\ -""") +""" + ) def test_genshi(): - genshi_template.generate(**context).render('html', strip_whitespace=False) + genshi_template.generate(**context).render("html", strip_whitespace=False) + try: from Cheetah.Template import Template as CheetahTemplate except ImportError: test_cheetah = None else: - cheetah_template = CheetahTemplate("""\ + cheetah_template = CheetahTemplate( + """\ #import cgi <!doctype html> <html> @@ -246,18 +267,22 @@ else: </div> </body> </html>\ -""", searchList=[dict(context)]) +""", + searchList=[dict(context)], + ) def test_cheetah(): unicode(cheetah_template) + try: import tenjin except ImportError: test_tenjin = None else: tenjin_template = tenjin.Template() - tenjin_template.convert("""\ + tenjin_template.convert( + """\ <!doctype html> <html> <head> @@ -285,19 +310,23 @@ else: </div> </body> </html>\ -""") +""" + ) def test_tenjin(): from tenjin.helpers import escape, to_str + tenjin_template.render(context, locals()) + try: from spitfire.compiler import util as SpitfireTemplate from spitfire.compiler.analyzer import o2_options as spitfire_optimizer except ImportError: test_spitfire = None else: - spitfire_template = SpitfireTemplate.load_template("""\ + spitfire_template = SpitfireTemplate.load_template( + """\ <!doctype html> <html> <head> @@ -325,8 +354,12 @@ else: </div> </body> </html>\ -""", 'spitfire_tmpl', spitfire_optimizer, {'enable_filters': False}) - spitfire_context = dict(context, **{'cgi': cgi}) +""", + "spitfire_tmpl", + spitfire_optimizer, + {"enable_filters": False}, + ) + spitfire_context = dict(context, **{"cgi": cgi}) def test_spitfire(): spitfire_template(search_list=[spitfire_context]).main() @@ -337,7 +370,8 @@ try: except ImportError: test_chameleon = None else: - chameleon_template = PageTemplate("""\ + chameleon_template = PageTemplate( + """\ <html xmlns:tal="http://xml.zope.org/namespaces/tal"> <head> <title tal:content="page_title">Page Title</title> @@ -358,23 +392,27 @@ else: </div> </body> </html>\ -""") +""" + ) chameleon_context = dict(context) - chameleon_context['sections'] = [ - ('index.html', 'Index'), - ('downloads.html', 'Downloads'), - ('products.html', 'Products') + chameleon_context["sections"] = [ + ("index.html", "Index"), + ("downloads.html", "Downloads"), + ("products.html", "Products"), ] + def test_chameleon(): chameleon_template.render(**chameleon_context) + try: from chameleon.zpt.template import PageTemplate from chameleon.genshi import language except ImportError: test_chameleon_genshi = None else: - chameleon_genshi_template = PageTemplate("""\ + chameleon_genshi_template = PageTemplate( + """\ <html xmlns="http://www.w3.org/1999/xhtml" xmlns:py="http://genshi.edgewall.org/"> <head> <title>${page_title}</title> @@ -395,40 +433,63 @@ else: </div> </body> </html>\ -""", parser=language.Parser()) +""", + parser=language.Parser(), + ) chameleon_genshi_context = dict(context) - chameleon_genshi_context['sections'] = [ - ('index.html', 'Index'), - ('downloads.html', 'Downloads'), - ('products.html', 'Products') + chameleon_genshi_context["sections"] = [ + ("index.html", "Index"), + ("downloads.html", "Downloads"), + ("products.html", "Products"), ] + def test_chameleon_genshi(): chameleon_genshi_template.render(**chameleon_genshi_context) -sys.stdout.write('\r' + '\n'.join(( - '=' * 80, - 'Template Engine BigTable Benchmark'.center(80), - '=' * 80, - __doc__, - '-' * 80 -)) + '\n') +sys.stdout.write( + "\r" + + "\n".join( + ( + "=" * 80, + "Template Engine BigTable Benchmark".center(80), + "=" * 80, + __doc__, + "-" * 80, + ) + ) + + "\n" +) -for test in 'jinja', 'mako', 'tornado', 'tenjin', 'spitfire', 'django', 'genshi', 'cheetah', 'chameleon', 'chameleon_genshi': - if locals()['test_' + test] is None: - sys.stdout.write(' %-20s*not installed*\n' % test) +for test in ( + "jinja", + "mako", + "tornado", + "tenjin", + "spitfire", + "django", + "genshi", + "cheetah", + "chameleon", + "chameleon_genshi", +): + if locals()["test_" + test] is None: + sys.stdout.write(" %-20s*not installed*\n" % test) continue - t = Timer(setup='from __main__ import test_%s as bench' % test, - stmt='bench()') - sys.stdout.write(' >> %-20s<running>' % test) + t = Timer(setup="from __main__ import test_%s as bench" % test, stmt="bench()") + sys.stdout.write(" >> %-20s<running>" % test) sys.stdout.flush() - sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=50) / 50)) -sys.stdout.write('-' * 80 + '\n') -sys.stdout.write('''\ + sys.stdout.write("\r %-20s%.4f seconds\n" % (test, t.timeit(number=50) / 50)) +sys.stdout.write("-" * 80 + "\n") +sys.stdout.write( + """\ WARNING: The results of this benchmark are useless to compare the performance of template engines and should not be taken seriously in any way. It's testing the performance of simple loops and has no real-world usefulnes. It only used to check if changes on the Jinja code affect performance in a good or bad way and how it roughly compares to others. -''' + '=' * 80 + '\n') +""" + + "=" * 80 + + "\n" +) diff --git a/examples/profile.py b/examples/profile.py index e6deb47f..b16d99f2 100644 --- a/examples/profile.py +++ b/examples/profile.py @@ -1,4 +1,5 @@ from __future__ import print_function + try: from cProfile import Profile except ImportError: @@ -7,8 +8,10 @@ from pstats import Stats from jinja2 import Environment as JinjaEnvironment context = { - 'page_title': 'mitsuhiko\'s benchmark', - 'table': [dict(a=1,b=2,c=3,d=4,e=5,f=6,g=7,h=8,i=9,j=10) for x in range(1000)] + "page_title": "mitsuhiko's benchmark", + "table": [ + dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10) for x in range(1000) + ], } source = """\ @@ -39,9 +42,7 @@ source = """\ </html>\ """ jinja_template = JinjaEnvironment( - line_statement_prefix='%', - variable_start_string="${", - variable_end_string="}" + line_statement_prefix="%", variable_start_string="${", variable_end_string="}" ).from_string(source) print(jinja_template.environment.compile(source, raw=True)) @@ -49,5 +50,5 @@ print(jinja_template.environment.compile(source, raw=True)) p = Profile() p.runcall(lambda: jinja_template.render(context)) stats = Stats(p) -stats.sort_stats('time', 'calls') +stats.sort_stats("time", "calls") stats.print_stats() diff --git a/examples/rwbench/djangoext.py b/examples/rwbench/djangoext.py index 06897e5f..0052aefc 100644 --- a/examples/rwbench/djangoext.py +++ b/examples/rwbench/djangoext.py @@ -12,12 +12,13 @@ from rwbench import dateformat from rwbench import ROOT settings.configure( - TEMPLATE_DIRS=(join(ROOT, 'django'),), + TEMPLATE_DIRS=(join(ROOT, "django"),), TEMPLATE_LOADERS=( - ('django.template.loaders.cached.Loader', ( - 'django.template.loaders.filesystem.Loader', - )), - ) + ( + "django.template.loaders.cached.Loader", + ("django.template.loaders.filesystem.Loader",), + ), + ), ) # for django extensions. We monkey patch our extensions in so that @@ -58,13 +59,12 @@ def form(parser, token): args = [] while p.more(): args.append(p.value()) - body = parser.parse(('endform',)) + body = parser.parse(("endform",)) parser.delete_first_token() return FormNode(body, *args) class InputFieldNode(Node): - def __init__(self, name, type=None, value=None): self.name = var_or_none(name) self.type = var_or_none(type) @@ -72,22 +72,17 @@ class InputFieldNode(Node): def render(self, context): name = self.name.resolve(context) - type = 'text' - value = '' + type = "text" + value = "" if self.type is not None: type = self.type.resolve(context) if self.value is not None: value = self.value.resolve(context) - tmpl = django_loader.get_template('_input_field.html') - return tmpl.render(DjangoContext({ - 'name': name, - 'type': type, - 'value': value - })) + tmpl = django_loader.get_template("_input_field.html") + return tmpl.render(DjangoContext({"name": name, "type": type, "value": value})) class TextareaNode(Node): - def __init__(self, name, rows=None, cols=None, value=None): self.name = var_or_none(name) self.rows = var_or_none(rows) @@ -98,24 +93,20 @@ class TextareaNode(Node): name = self.name.resolve(context) rows = 10 cols = 40 - value = '' + value = "" if self.rows is not None: rows = int(self.rows.resolve(context)) if self.cols is not None: cols = int(self.cols.resolve(context)) if self.value is not None: value = self.value.resolve(context) - tmpl = django_loader.get_template('_textarea.html') - return tmpl.render(DjangoContext({ - 'name': name, - 'rows': rows, - 'cols': cols, - 'value': value - })) + tmpl = django_loader.get_template("_textarea.html") + return tmpl.render( + DjangoContext({"name": name, "rows": rows, "cols": cols, "value": value}) + ) class FormNode(Node): - def __init__(self, body, action=None, method=None): self.body = body self.action = action @@ -123,15 +114,13 @@ class FormNode(Node): def render(self, context): body = self.body.render(context) - action = '' - method = 'post' + action = "" + method = "post" if self.action is not None: action = self.action.resolve(context) if self.method is not None: method = self.method.resolve(context) - tmpl = django_loader.get_template('_form.html') - return tmpl.render(DjangoContext({ - 'body': body, - 'action': action, - 'method': method - })) + tmpl = django_loader.get_template("_form.html") + return tmpl.render( + DjangoContext({"body": body, "action": action, "method": method}) + ) diff --git a/examples/rwbench/rwbench.py b/examples/rwbench/rwbench.py index af5d40bb..957216af 100644 --- a/examples/rwbench/rwbench.py +++ b/examples/rwbench/rwbench.py @@ -40,20 +40,19 @@ ROOT = abspath(dirname(__file__)) def dateformat(x): - return x.strftime('%Y-%m-%d') + return x.strftime("%Y-%m-%d") -jinja_env = Environment(loader=FileSystemLoader(join(ROOT, 'jinja'))) -jinja_env.filters['dateformat'] = dateformat -mako_lookup = TemplateLookup(directories=[join(ROOT, 'mako')]) -genshi_loader = GenshiTemplateLoader([join(ROOT, 'genshi')]) +jinja_env = Environment(loader=FileSystemLoader(join(ROOT, "jinja"))) +jinja_env.filters["dateformat"] = dateformat +mako_lookup = TemplateLookup(directories=[join(ROOT, "mako")]) +genshi_loader = GenshiTemplateLoader([join(ROOT, "genshi")]) class Article(object): - def __init__(self, id): self.id = id - self.href = '/article/%d' % self.id + self.href = "/article/%d" % self.id self.title = generate_lorem_ipsum(1, False, 5, 10) self.user = choice(users) self.body = generate_lorem_ipsum() @@ -62,33 +61,33 @@ class Article(object): class User(object): - def __init__(self, username): - self.href = '/user/%s' % username + self.href = "/user/%s" % username self.username = username -users = map(User, [u'John Doe', u'Jane Doe', u'Peter Somewhat']) +users = map(User, [u"John Doe", u"Jane Doe", u"Peter Somewhat"]) articles = map(Article, range(20)) navigation = [ - ('index', 'Index'), - ('about', 'About'), - ('foo?bar=1', 'Foo with Bar'), - ('foo?bar=2&s=x', 'Foo with X'), - ('blah', 'Blub Blah'), - ('hehe', 'Haha'), + ("index", "Index"), + ("about", "About"), + ("foo?bar=1", "Foo with Bar"), + ("foo?bar=2&s=x", "Foo with X"), + ("blah", "Blub Blah"), + ("hehe", "Haha"), ] * 5 context = dict(users=users, articles=articles, page_navigation=navigation) -jinja_template = jinja_env.get_template('index.html') -mako_template = mako_lookup.get_template('index.html') -genshi_template = genshi_loader.load('index.html') +jinja_template = jinja_env.get_template("index.html") +mako_template = mako_lookup.get_template("index.html") +genshi_template = genshi_loader.load("index.html") def test_jinja(): jinja_template.render(context) + def test_mako(): mako_template.render_unicode(**context) @@ -96,27 +95,28 @@ def test_mako(): def test_django(): # not cached because django is not thread safe and does # not cache by itself so it would be unfair to cache it here. - django_template = django_loader.get_template('index.html') + django_template = django_loader.get_template("index.html") django_template.render(DjangoContext(context)) def test_genshi(): - genshi_template.generate(**context).render('html', doctype='html') + genshi_template.generate(**context).render("html", doctype="html") -if __name__ == '__main__': - sys.stdout.write('Realworldish Benchmark:\n') - for test in 'jinja', 'mako', 'django', 'genshi': - t = Timer(setup='from __main__ import test_%s as bench' % test, - stmt='bench()') - sys.stdout.write(' >> %-20s<running>' % test) +if __name__ == "__main__": + sys.stdout.write("Realworldish Benchmark:\n") + for test in "jinja", "mako", "django", "genshi": + t = Timer(setup="from __main__ import test_%s as bench" % test, stmt="bench()") + sys.stdout.write(" >> %-20s<running>" % test) sys.stdout.flush() - sys.stdout.write('\r %-20s%.4f seconds\n' % (test, t.timeit(number=200) / 200)) + sys.stdout.write( + "\r %-20s%.4f seconds\n" % (test, t.timeit(number=200) / 200) + ) - if '-p' in sys.argv: - print('Jinja profile') + if "-p" in sys.argv: + print("Jinja profile") p = Profile() p.runcall(test_jinja) stats = Stats(p) - stats.sort_stats('time', 'calls') + stats.sort_stats("time", "calls") stats.print_stats() |