[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
Provenance
- Commit
de478f6- Tree
f219838- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e4ad284
6 files changed+526 added−49 removed
modified:jinja/translators/python.py+41 added-24 removed
14 unmodified lines15 from jinja.exceptions import TemplateSyntaxError16 from jinja.translators import Translator17 18 19+def _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+ )27+28+29 class Template(object):30 """31 Represents a finished template.32 """81 unmodified lines114 115 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 lines165 block.replace(node.blocks[block.name])166 node = tmpl167 168 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))185 186 return '\n'.join(lines)148 unmodified lines335 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 ))343 344 buf = []345 write = lambda x: buf.append(self.indent(x))346 329- 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)356 357 # -- python nodes358 18 unmodified lines377 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 )385 386 # normal operators387 buf = []24 unmodified lines412 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 )420 421 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 )429 430 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])435 436 def handle_bitor(self, node):437 """438 We use the pipe operator for filtering.15 unmodified lines454 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 )473 474 def handle_call_func(self, node):475 """10 unmodified lines486 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 linesmodified:jinja/environment.py+31 added-25 removed
65 unmodified lines66 67 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()71 72 def from_string(self, source):73 """Load a template from a string."""74 from jinja.parser import Parser11 unmodified lines86 return unicode(value)87 except UnicodeError:88 return str(value).decode(self.charset, 'ignore')89 90- 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)98-99- 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 value104 107- 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))112 113 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 Undefined127 128 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)140 141+ 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()148+149 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 will7 unmodified linesmodified:jinja/loaders.py+6 added
35 unmodified lines36 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)43 44 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)51 52 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)61 62 63 class FileSystemLoader(object):39 unmodified linesadded: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>8+9+import cgi10+import sys11+import timeit12+from StringIO import StringIO13+14+from genshi.builder import tag15+from genshi.template import MarkupTemplate16+17+from jinja import Environment18+19+from django.conf import settings20+settings.configure()21+from django.template import Context as DjangoContext22+from django.template import Template as DjangoTemplate23+24+from Cheetah.Template import Template as CheetahTemplate25+26+from mako.template import Template as MakoTemplate27+28+table = [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)]30+31+genshi_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+""")38+39+django_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+""")46+47+jinja_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+''')54+55+cheetah_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}])67+68+mako_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+''')79+80+def test_django():81+ """Django Templates"""82+ context = DjangoContext({'table': table})83+ django_tmpl.render(context)84+85+def test_jinja():86+ """Jinja Templates"""87+ jinja_tmpl.render(table=table)88+89+def test_genshi():90+ """Genshi Templates"""91+ stream = genshi_tmpl.generate(table=table)92+ stream.render('html', strip_whitespace=False)93+94+def test_cheetah():95+ """Cheetah Templates"""96+ cheetah_tmpl.respond()97+98+def test_mako():99+ """Mako Templates"""100+ mako_tmpl.render(table=table)101+102+103+def run(which=None, number=10):104+ tests = ['test_django', 'test_jinja', 'test_genshi', 'test_cheetah', 'test_mako']105+106+ if which:107+ tests = filter(lambda n: n[5:] in which, tests)108+109+ 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) / number113+114+ 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)119+120+121+if __name__ == '__main__':122+ which = [arg for arg in sys.argv[1:] if arg[0] != '-']123+124+ 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 installation3+4+If you want to use setuptools in your package's setup.py, just include this5+file in the same directory with it, and add this to the top of your setup.py::6+7+ from ez_setup import use_setuptools8+ use_setuptools()9+10+If you want to require a specific version of setuptools, set a download11+mirror, or use an alternate download directory, you can do so by supplying12+the appropriate options to ``use_setuptools()``.13+14+This file can also be run as a script to install or upgrade setuptools.15+"""16+import sys17+DEFAULT_VERSION = "0.6b3"18+DEFAULT_URL = "http://cheeseshop.python.org/packages/%s/s/setuptools/" % sys.version[:3]19+20+md5_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+}30+31+import sys, os32+33+def _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 data44+45+46+def 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.path51+52+ `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 = egg73+74+ import pkg_resources75+ try:76+ pkg_resources.require("setuptools>="+version)77+78+ 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)86+87+def 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 filename92+93+ `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+---------------------------------------------------------------------------109+This script requires setuptools version %s to run (even to display110+help). I will attempt to download it for you (from111+%s), but112+you may need to enable firewall access for this script first.113+I will start the download in %d seconds.114+115+(Note: if this machine does not have network access, please obtain the file116+117+ %s118+119+and 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)133+134+def main(argv, version=DEFAULT_VERSION):135+ """Install or upgrade setuptools and EasyInstall"""136+137+ 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)153+154+ 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.)'172+173+174+175+def update_md5(filenames):176+ """Update our built-in md5 registry"""177+178+ import re179+ from md5 import md5180+181+ 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()186+187+ data = [" %r: %r,\n" % it for it in md5_data.items()]188+ data.sort()189+ repl = "".join(data)190+191+ import inspect192+ srcfile = inspect.getsourcefile(sys.modules[__name__])193+ f = open(srcfile, 'rb'); src = f.read(); f.close()194+195+ match = re.search("\nmd5_data = {\n([^}]+)}", src)196+ if not match:197+ print >>sys.stderr, "Internal error!"198+ sys.exit(2)199+200+ src = src[:match.start(1)] + repl + src[match.end(1):]201+ f = open(srcfile,'w')202+ f.write(src)203+ f.close()204+205+206+if __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:])211+212+213+214+215+added:setup.py+100 added
1+# -*- coding: utf-8 -*-2+try:3+ import ez_setup4+ ez_setup.use_setuptools()5+except ImportError:6+ pass7+from setuptools import setup8+9+10+setup(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 = '''\19+Jinja is a small but very fast and easy to use stand-alone template engine20+written in pure Python.21+22+Since version 0.6 it uses a new parser that increases parsing performance23+a lot by caching the nodelists on disk if wanted.24+25+It includes multiple template inheritance and other features like simple26+value escaping.27+28+29+Template Syntax30+===============31+32+This is a small example template in which you can see how Jinja's syntax33+looks like::34+35+ <!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>47+48+ <h1>My Webpage</h1>49+ {{ variable }}50+ </body>51+ </html>52+53+54+Usage55+=====56+57+Here is a small example::58+59+ from jinja import Template, Context, FileSystemLoader60+61+ 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)70+71+72+Unicode Support73+===============74+75+Jinja comes with built-in Unicode support. As a matter of fact, the return76+value of ``Template.render()`` will be a Python unicode object.77+78+You can still output ``str`` objects as well when you encode the result::79+80+ s = t.render(c).encode('utf-8')81+82+For more examples check out the `documentation`_ on the `jinja webpage`_.83+84+.. _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+)