Skip to content
Myr

[svn] some small updates to make jinja performing better

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

--HG-- branch : trunk

authored by Armin Ronacher · committed by Armin Ronacher · parent e4ad284 · Browse files · 6 files+526 added−49 removed
This commit

State

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

Diff stats

6 files+526 added−49 removed

  • tests:+133 added−0 removed
  • other:+393 added−49 removed

6 files+526 added−49 removed

modified:jinja/translators/python.py+41 added-24 removed
14 unmodified lines
15from jinja.exceptions import TemplateSyntaxError16from jinja.translators import Translator171819def _to_tuple(args):20 """21 Return a tuple repr without nested repr.22 """23 return '(%s%s)' % (24 ', '.join(args),25 len(args) == 1 and ',' or ''26 )272829class Template(object):30 """31 Represents a finished template.32 """
81 unmodified lines
114115 def process(environment, node):116 translator = PythonTranslator(environment, node)117 source = translator.translate()118 print source119 ns = {}120 exec source in ns121 return Template(environment, ns['generate'])122 process = staticmethod(process)
42 unmodified lines
165 block.replace(node.blocks[block.name])166 node = tmpl167168 lines = [self.indent(158 'from jinja.datastructure import Undefined, LoopContext, CycleContext\n'159 'def generate(context, write, write_var=None):\n'169 'from jinja.datastructure import Undefined, LoopContext, CycleContext\n\n'170 'def generate(context, write):\n'171 ' # BOOTSTRAPPING CODE\n'172 ' environment = context.environment\n'161 ' if write_var is None:\n'162 ' write_var = lambda x: write(environment.finish_var(x))'173 ' get_attribute = environment.get_attribute\n'174 ' perform_test = environment.perform_test\n'175 ' apply_filters = environment.apply_filters\n'176 ' call_function = environment.call_function\n'177 ' call_function_simple = environment.call_function_simple\n'178 ' finish_var = environment.finish_var\n'179 ' write_var = lambda x: write(finish_var(x))\n'180 ' filtercache = {}\n\n'181 ' # TEMPLATE CODE'182 )]164 write = lambda x: lines.append(self.indent(x))183 self.indention += 1184 lines.append(self.handle_node_list(node))185186 return '\n'.join(lines)
148 unmodified lines
335 else.336 """337 rv = self.handle_node(node.body)338 if not rv:321 return self.indent('# empty block from %r, line %s' % (339 return self.indent('# EMPTY BLOCK (%r:%s)' % (340 node.filename or '?',341 node.lineno342 ))343344 buf = []345 write = lambda x: buf.append(self.indent(x))346329 write('# block from %r, line %s' % (347 write('# BLOCK (%r:%s)' % (348 node.filename or '?',349 node.lineno350 ))351 write('context.push()')352 buf.append(self.handle_node(node.body))353 write('context.pop()')336 buf.append(self.indent('# end of block'))354 buf.append(self.indent('# END OF BLOCK'))355 return '\n'.join(buf)356357 # -- python nodes358
18 unmodified lines
377 node.lineno)378 elif node.ops[0][1].__class__ is not ast.Name:379 raise TemplateSyntaxError('is operator requires a test name',380 ' as operand', node.lineno)363 return 'environment.perform_test(%s, context, %r)' % (364 self.handle_node(node.expr),365 node.ops[0][1].name381 return 'perform_test(context, %r, %s)' % (382 node.ops[0][1].name,383 self.handle_node(node.expr)384 )385386 # normal operators387 buf = []
24 unmodified lines
412 return '%s[%s]' % (413 self.handle_node(node.expr),414 self.handle_node(node.subs[0])415 )398 return 'environment.get_attribute(%s, %s)' % (416 return 'get_attribute(%s, %s)' % (417 self.handle_node(node.expr),418 self.handle_node(node.subs[0])419 )420421 def handle_getattr(self, node):422 """423 Handle hardcoded attribute access. foo.bar424 """407 return 'environment.get_attribute(%s, %r)' % (425 return 'get_attribute(%s, %r)' % (426 self.handle_node(node.expr),427 node.attrname428 )429430 def handle_ass_tuple(self, node):431 """432 Tuple unpacking loops.433 """416 return '(%s)' % ', '.join([self.handle_node(n) for n in node.nodes])434 return _to_tuple([self.handle_node(n) for n in node.nodes])435436 def handle_bitor(self, node):437 """438 We use the pipe operator for filtering.
15 unmodified lines
454 args.append(self.handle_node(arg))455 if n.star_args is not None or n.dstar_args is not None:456 raise TemplateSynaxError('*args / **kwargs is not supported '457 'for filters', n.lineno)440 if args:441 args = ', ' + ', '.join(args)442 filters.append('environment.prepare_filter(%r%s)' % (458 filters.append('(%r, %s)' % (459 n.node.name,444 args or ''460 _to_tuple(args)461 ))462 elif n.__class__ is ast.Name:447 filters.append('environment.prepare_filter(%r)' %448 n.name)463 filters.append('(%r, ())' % n.name)464 else:465 raise TemplateSyntaxError('invalid filter. filter must be a '466 'hardcoded function name from the '467 'filter namespace',468 n.lineno)454 return 'environment.apply_filters(%s, context, [%s])' % (469 return 'apply_filters(%s, filtercache, context, %s)' % (470 self.handle_node(node.nodes[0]),456 ', '.join(filters)471 _to_tuple(filters)472 )473474 def handle_call_func(self, node):475 """
10 unmodified lines
486 if arg.__class__ is ast.Keyword:487 kwargs[arg.name] = self.handle_node(arg.expr)488 else:489 args.append(self.handle_node(arg))475 return 'environment.call_function(%s, [%s], {%s}, %s, %s)' % (490 if not (args or kwargs or star_args or dstar_args):491 return 'call_function_simple(%s)' % self.handle_node(node.node)492 return 'call_function(%s, %s, {%s}, %s, %s)' % (493 self.handle_node(node.node),477 ', '.join(args),494 _to_tuple(args),495 ', '.join(['%r: %s' % i for i in kwargs.iteritems()]),496 star_args,497 dstar_args498 )
143 unmodified lines
modified:jinja/environment.py+31 added-25 removed
65 unmodified lines
6667 def parse(self, source):68 """Function that creates a new parser and parses the source."""69 parser = Parser(self, source)70 return parser.parse_page()70 return parser.parse()7172 def from_string(self, source):73 """Load a template from a string."""74 from jinja.parser import Parser
11 unmodified lines
86 return unicode(value)87 except UnicodeError:88 return str(value).decode(self.charset, 'ignore')8990 def prepare_filter(self, name, *args):90 def apply_filters(self, value, filtercache, context, filters):91 """92 Prepare a filter.93 """94 try:95 return self.filters[name](*args)96 except KeyError:97 raise FilterNotFound(name)9899 def apply_filters(self, value, context, filters):100 """92 Apply a list of filters on the variable.93 """103 for f in filters:104 value = f(self, context, value)94 for key in filters:95 if key in filtercache:96 func = filtercache[key]97 else:98 filtername, args = key99 if filtername not in self.filters:100 raise FilterNotFound(filtername)101 filtercache[key] = func = self.filters[filtername](*args)102 value = func(self, context, value)103 return value104107 def perform_test(self, value, context, testname):105 def perform_test(self, context, testname, value):106 """107 Perform a test on a variable.108 """111 try:112 test = self.tests[testname]113 except KeyError:109 if testname not in self.tests:110 raise TestNotFound(testname)115 return bool(test(self, context, value))111 return bool(self.tests[testname](self, context, value))112113 def get_attribute(self, obj, name):114 """115 Get the attribute name from obj.116 """121 try:117 if name in obj:118 return obj[name]119 elif hasattr(obj, name):120 rv = getattr(obj, name)121 r = getattr(obj, 'jinja_allowed_attributes', None)122 if r is not None:123 if name not in r:124 raise AttributeError()125 return rv128 except AttributeError:129 return obj[name]130 except:131 return Undefined126 return Undefined127128 def call_function(self, f, args, kwargs, dyn_args, dyn_kwargs):129 """135 Function call helper130 Function call helper. Called for all functions that are passed131 any arguments.132 """133 if dyn_args is not None:138 args += dyn_args134 args += tuple(dyn_args)135 elif dyn_kwargs is not None:136 kwargs.update(dyn_kwargs)137 if getattr(f, 'jinja_unsafe_call', False):138 raise SecurityException('unsafe function %r called' % f.__name__)139 return f(*args, **kwargs)140141 def call_function_simple(self, f):142 """143 Function call without arguments.144 """145 if getattr(f, 'jinja_unsafe_call', False):146 raise SecurityException('unsafe function %r called' % f.__name__)147 return f()148149 def finish_var(self, value):150 """151 As long as no write_var function is passed to the template152 evaluator the source generated by the python translator will
7 unmodified lines
modified:jinja/loaders.py+6 added
35 unmodified lines
36 def get_source(self, name, parent=None):37 """38 Retrieve the sourcecode of a template.39 """40 # just ascii chars are allowed as template names41 name = str(name)42 return self.loader.get_source(self.environment, name, parent)4344 def parse(self, name, parent=None):45 """46 Retreive a template and parse it.47 """48 # just ascii chars are allowed as template names49 name = str(name)50 return self.loader.parse(self.environment, name, parent)5152 def load(self, name, translator=PythonTranslator):53 """54 Translate a template and return it. This must not necesarily55 be a template class. The javascript translator for example56 will just output a string with the translated code.57 """58 # just ascii chars are allowed as template names59 name = str(name)60 return self.loader.load(self.environment, name, translator)616263class FileSystemLoader(object):
39 unmodified lines
added:tests/bigtable.py+133 added
1# Template language benchmarks2#3# Objective: Generate a 1000x10 HTML table as fast as possible.4# adapted for jinja 15#6# Author: Jonas Borgström <jonas@edgewall.com>7# Author: Armin Ronacher <armin.ronacher@active-4.com>89import cgi10import sys11import timeit12from StringIO import StringIO1314from genshi.builder import tag15from genshi.template import MarkupTemplate1617from jinja import Environment1819from django.conf import settings20settings.configure()21from django.template import Context as DjangoContext22from django.template import Template as DjangoTemplate2324from Cheetah.Template import Template as CheetahTemplate2526from mako.template import Template as MakoTemplate2728table = [dict(a='1',b='2',c='3',d='4',e='5',f='6',g='7',h='8',i='9',j='10')29 for x in range(1000)]3031genshi_tmpl = MarkupTemplate("""32<table xmlns:py="http://genshi.edgewall.org/">33<tr py:for="row in table">34<td py:for="c in row.values()" py:content="c"/>35</tr>36</table>37""")3839django_tmpl = DjangoTemplate("""40<table>41{% for row in table %}42<tr>{% for col in row.values %}{{ col|escape }}{% endfor %}</tr>43{% endfor %}44</table>45""")4647jinja_tmpl = Environment().from_string('''48<table>49{% for row in table %}50<tr>{% for col in row.values() %}{{ col|escape }}{% endfor %}</tr>51{% endfor %}52</table>53''')5455cheetah_tmpl = CheetahTemplate('''56# filter escape57<table>58#for $row in $table59<tr>60#for $col in $row.values()61$col62#end for63</tr>64#end for65</table>66''', searchList=[{'table': table, 'escape': cgi.escape}])6768mako_tmpl = MakoTemplate('''69<table>70% for row in table:71<tr>72% for col in row.values():73 ${col|h}74% endfor75</tr>76% endfor77</table>78''')7980def test_django():81 """Django Templates"""82 context = DjangoContext({'table': table})83 django_tmpl.render(context)8485def test_jinja():86 """Jinja Templates"""87 jinja_tmpl.render(table=table)8889def test_genshi():90 """Genshi Templates"""91 stream = genshi_tmpl.generate(table=table)92 stream.render('html', strip_whitespace=False)9394def test_cheetah():95 """Cheetah Templates"""96 cheetah_tmpl.respond()9798def test_mako():99 """Mako Templates"""100 mako_tmpl.render(table=table)101102103def run(which=None, number=10):104 tests = ['test_django', 'test_jinja', 'test_genshi', 'test_cheetah', 'test_mako']105106 if which:107 tests = filter(lambda n: n[5:] in which, tests)108109 for test in [t for t in tests if hasattr(sys.modules[__name__], t)]:110 t = timeit.Timer(setup='from __main__ import %s;' % test,111 stmt='%s()' % test)112 time = t.timeit(number=number) / number113114 if time < 0.00001:115 result = ' (not installed?)'116 else:117 result = '%16.2f ms' % (1000 * time)118 print '%-35s %s' % (getattr(sys.modules[__name__], test).__doc__, result)119120121if __name__ == '__main__':122 which = [arg for arg in sys.argv[1:] if arg[0] != '-']123124 if '-p' in sys.argv:125 import hotshot, hotshot.stats126 prof = hotshot.Profile("template.prof")127 benchtime = prof.runcall(run, which, number=1)128 stats = hotshot.stats.load("template.prof")129 stats.strip_dirs()130 stats.sort_stats('time', 'calls')131 stats.print_stats()132 else:133 run(which)
added:ez_setup.py+215 added
1#!python2"""Bootstrap setuptools installation34If you want to use setuptools in your package's setup.py, just include this5file in the same directory with it, and add this to the top of your setup.py::67 from ez_setup import use_setuptools8 use_setuptools()910If you want to require a specific version of setuptools, set a download11mirror, or use an alternate download directory, you can do so by supplying12the appropriate options to ``use_setuptools()``.1314This file can also be run as a script to install or upgrade setuptools.15"""16import sys17DEFAULT_VERSION = "0.6b3"18DEFAULT_URL = "http://cheeseshop.python.org/packages/%s/s/setuptools/" % sys.version[:3]1920md5_data = {21 'setuptools-0.6b1-py2.3.egg': '8822caf901250d848b996b7f25c6e6ca',22 'setuptools-0.6b1-py2.4.egg': 'b79a8a403e4502fbb85ee3f1941735cb',23 'setuptools-0.6b2-py2.3.egg': '5657759d8a6d8fc44070a9d07272d99b',24 'setuptools-0.6b2-py2.4.egg': '4996a8d169d2be661fa32a6e52e4f82a',25 'setuptools-0.6b3-py2.3.egg': 'bb31c0fc7399a63579975cad9f5a0618',26 'setuptools-0.6b3-py2.4.egg': '38a8c6b3d6ecd22247f179f7da669fac',27 'setuptools-0.6b3dev_r46791-py2.3.egg': 'e765a29566575ffac5d81cdf0c6f8db9',28 'setuptools-0.6b3dev_r46791-py2.4.egg': 'd249c022ed029ad60d134bd998adc880',29}3031import sys, os3233def _validate_md5(egg_name, data):34 if egg_name in md5_data:35 from md5 import md536 digest = md5(data).hexdigest()37 if digest != md5_data[egg_name]:38 print >>sys.stderr, (39 "md5 validation of %s failed! (Possible download problem?)"40 % egg_name41 )42 sys.exit(2)43 return data444546def use_setuptools(47 version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,48 download_delay=1549):50 """Automatically find/download setuptools and make it available on sys.path5152 `version` should be a valid setuptools version number that is available53 as an egg for download under the `download_base` URL (which should end with54 a '/'). `to_dir` is the directory where setuptools will be downloaded, if55 it is not already available. If `download_delay` is specified, it should56 be the number of seconds that will be paused before initiating a download,57 should one be required. If an older version of setuptools is installed,58 this routine will print a message to ``sys.stderr`` and raise SystemExit in59 an attempt to abort the calling script.60 """61 try:62 import setuptools63 if setuptools.__version__ == '0.0.1':64 print >>sys.stderr, (65 "You have an obsolete version of setuptools installed. Please\n"66 "remove it from your system entirely before rerunning this script."67 )68 sys.exit(2)69 except ImportError:70 egg = download_setuptools(version, download_base, to_dir, download_delay)71 sys.path.insert(0, egg)72 import setuptools; setuptools.bootstrap_install_from = egg7374 import pkg_resources75 try:76 pkg_resources.require("setuptools>="+version)7778 except pkg_resources.VersionConflict:79 # XXX could we install in a subprocess here?80 print >>sys.stderr, (81 "The required version of setuptools (>=%s) is not available, and\n"82 "can't be installed while this script is running. Please install\n"83 " a more recent version first."84 ) % version85 sys.exit(2)8687def download_setuptools(88 version=DEFAULT_VERSION, download_base=DEFAULT_URL, to_dir=os.curdir,89 delay = 1590):91 """Download setuptools from a specified location and return its filename9293 `version` should be a valid setuptools version number that is available94 as an egg for download under the `download_base` URL (which should end95 with a '/'). `to_dir` is the directory where the egg will be downloaded.96 `delay` is the number of seconds to pause before an actual download attempt.97 """98 import urllib2, shutil99 egg_name = "setuptools-%s-py%s.egg" % (version,sys.version[:3])100 url = download_base + egg_name101 saveto = os.path.join(to_dir, egg_name)102 src = dst = None103 if not os.path.exists(saveto): # Avoid repeated downloads104 try:105 from distutils import log106 if delay:107 log.warn("""108---------------------------------------------------------------------------109This script requires setuptools version %s to run (even to display110help). I will attempt to download it for you (from111%s), but112you may need to enable firewall access for this script first.113I will start the download in %d seconds.114115(Note: if this machine does not have network access, please obtain the file116117 %s118119and place it in this directory before rerunning this script.)120---------------------------------------------------------------------------""",121 version, download_base, delay, url122 ); from time import sleep; sleep(delay)123 log.warn("Downloading %s", url)124 src = urllib2.urlopen(url)125 # Read/write all in one block, so we don't create a corrupt file126 # if the download is interrupted.127 data = _validate_md5(egg_name, src.read())128 dst = open(saveto,"wb"); dst.write(data)129 finally:130 if src: src.close()131 if dst: dst.close()132 return os.path.realpath(saveto)133134def main(argv, version=DEFAULT_VERSION):135 """Install or upgrade setuptools and EasyInstall"""136137 try:138 import setuptools139 except ImportError:140 import tempfile, shutil141 tmpdir = tempfile.mkdtemp(prefix="easy_install-")142 try:143 egg = download_setuptools(version, to_dir=tmpdir, delay=0)144 sys.path.insert(0,egg)145 from setuptools.command.easy_install import main146 return main(list(argv)+[egg]) # we're done here147 finally:148 shutil.rmtree(tmpdir)149 else:150 if setuptools.__version__ == '0.0.1':151 # tell the user to uninstall obsolete version152 use_setuptools(version)153154 req = "setuptools>="+version155 import pkg_resources156 try:157 pkg_resources.require(req)158 except pkg_resources.VersionConflict:159 try:160 from setuptools.command.easy_install import main161 except ImportError:162 from easy_install import main163 main(list(argv)+[download_setuptools(delay=0)])164 sys.exit(0) # try to force an exit165 else:166 if argv:167 from setuptools.command.easy_install import main168 main(argv)169 else:170 print "Setuptools version",version,"or greater has been installed."171 print '(Run "ez_setup.py -U setuptools" to reinstall or upgrade.)'172173174175def update_md5(filenames):176 """Update our built-in md5 registry"""177178 import re179 from md5 import md5180181 for name in filenames:182 base = os.path.basename(name)183 f = open(name,'rb')184 md5_data[base] = md5(f.read()).hexdigest()185 f.close()186187 data = [" %r: %r,\n" % it for it in md5_data.items()]188 data.sort()189 repl = "".join(data)190191 import inspect192 srcfile = inspect.getsourcefile(sys.modules[__name__])193 f = open(srcfile, 'rb'); src = f.read(); f.close()194195 match = re.search("\nmd5_data = {\n([^}]+)}", src)196 if not match:197 print >>sys.stderr, "Internal error!"198 sys.exit(2)199200 src = src[:match.start(1)] + repl + src[match.end(1):]201 f = open(srcfile,'w')202 f.write(src)203 f.close()204205206if __name__=='__main__':207 if len(sys.argv)>2 and sys.argv[1]=='--md5update':208 update_md5(sys.argv[2:])209 else:210 main(sys.argv[1:])211212213214215
added:setup.py+100 added
1# -*- coding: utf-8 -*-2try:3 import ez_setup4 ez_setup.use_setuptools()5except ImportError:6 pass7from setuptools import setup8910setup(11 name = 'Jinja',12 version = '0.9',13 url = 'http://wsgiarea.pocoo.org/jinja/',14 license = 'BSD',15 author = 'Armin Ronacher',16 author_email = 'armin.ronacher@active-4.com',17 description = 'A small but fast and easy to use stand-alone template engine written in pure python.',18 long_description = '''\19Jinja is a small but very fast and easy to use stand-alone template engine20written in pure Python.2122Since version 0.6 it uses a new parser that increases parsing performance23a lot by caching the nodelists on disk if wanted.2425It includes multiple template inheritance and other features like simple26value escaping.272829Template Syntax30===============3132This is a small example template in which you can see how Jinja's syntax33looks like::3435 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"36 "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">37 <html xmlns="http://www.w3.org/1999/xhtml" lang="en" xml:lang="en">38 <head>39 <title>My Webpage</title>40 </head41 <body>42 <ul id="navigation">43 {% for item in navigation %}44 <li><a href="{{ item.href }}">{{ item.caption|e }}</a></li>45 {% endfor %}46 </ul>4748 <h1>My Webpage</h1>49 {{ variable }}50 </body>51 </html>525354Usage55=====5657Here is a small example::5859 from jinja import Template, Context, FileSystemLoader6061 t = Template('mytemplate', FileSystemLoader('/path/to/the/templates'))62 c = Context({63 'navigation' [64 {'href': '#', 'caption': 'Index'},65 {'href': '#', 'caption': 'Spam'}66 ],67 'variable': '<strong>hello world</strong>'68 })69 print t.render(c)707172Unicode Support73===============7475Jinja comes with built-in Unicode support. As a matter of fact, the return76value of ``Template.render()`` will be a Python unicode object.7778You can still output ``str`` objects as well when you encode the result::7980 s = t.render(c).encode('utf-8')8182For more examples check out the `documentation`_ on the `jinja webpage`_.8384.. _documentation: http://wsgiarea.pocoo.org/jinja/docs/85.. _jinja webpage: http://wsgiarea.pocoo.org/jinja/86''',87 keywords = 'wsgi web templateengine templates',88 packages = ['jinja'],89 platforms = 'any',90 classifiers = [91 'Development Status :: 5 - Production/Stable',92 'Environment :: Web Environment',93 'Intended Audience :: Developers',94 'License :: OSI Approved :: BSD License',95 'Operating System :: OS Independent',96 'Programming Language :: Python',97 'Topic :: Internet :: WWW/HTTP',98 'Topic :: Internet :: WWW/HTTP :: Dynamic Content'99 ]100)