[svn] reworked the jinja escaping system, removed getattr concatenating and documented internal jinja functions.
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 72bb257 · Browse files · 12 files·+209 added−143 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
12 files+209 added−143 removed
- other:+209 added−143 removed
Provenance
- Commit
ae16fd0- Tree
64f544b- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
72bb257
12 files changed+209 added−143 removed
modified:docs/src/contextenv.txt+22 added-4 removed
55 unmodified lines56 `replace` is called with the two literal strings ``a`` and ``b``, both57 unicode. The filters for the names are stored on ``self.filters`` in a58 dict. Missing filters should raise a `FilterNotFound` exception.59 60+ **Warning** this is a jinja internal method. The actual implementation61+ and function signature might change.62+63 **def** `perform_test` *(self, context, testname, args, value, invert)*:64 65 Like `apply_filters` you usually don't override this one. It's the66 callback function for tests (``foo is bar`` / ``foo is not bar``).4 unmodified lines71 with the `is not` operator, `False` if with the `is` operator.72 73 Missing tests should raise a `TestNotFound` exception.74 72-**def** `get_attribute` *(self, obj, attributes)*:75+ **Warning** this is a jinja internal method. The actual implementation76+ and function signature might change.77 74- Get `attributes` from the object provided. The default implementation75- performs security tests for each attribute.78+**def** `get_attribute` *(self, obj, attribute)*:79 80+ Get `attribute` from the object provided. The default implementation81+ performs security tests.82+83+ **Warning** this is a jinja internal method. The actual implementation84+ and function signature might change.85+86 **def** `call_function` *(self, f, context, args, kwargs, dyn_args, dyn_kwargs)*:87 88 Call a function `f` with the arguments `args`, `kwargs`, `dyn_args` and89 `dyn_kwargs` where `args` is a tuple and `kwargs` a dict. If `dyn_args`1 unmodified line91 not `None` you have to update the `kwargs` with it.92 93 The default implementation performs some security checks.94 95+ **Warning** this is a jinja internal method. The actual implementation96+ and function signature might change.97+98 **def** `call_function_simple` *(self, f, context)*:99 100 Like `call_function` but without arguments.101 90-**def** `finish_var` *(self, value)*:102+ **Warning** this is a jinja internal method. The actual implementation103+ and function signature might change.104 105+**def** `finish_var` *(self, value, ctx)*:106+107 Postprocess a variable before it's sent to the template.108+109+ **Warning** this is a jinja internal method. The actual implementation110+ and function signature might change.111 112 .. admonition:: Note113 114 The Enviornment class is defined in `jinja.environment.Environment`48 unmodified linesmodified:docs/src/devintro.txt+28 added
49 unmodified lines50 automatically escape all variables using xml51 escaping methods. If you don't want to escape a52 string you have to wrap it in a ``Markup``53 object from the ``jinja.datastructure`` module.54+ If `auto_escape` is ``True`` there will be also55+ a ``Markup`` object in the template namespace56+ to define partial html fragments. Note that we do57+ not recomment this feature, see also the comment58+ below.59+`default_filters` list of tuples in the form (``filter_name``,60+ ``arguments``) where ``filter_name`` is the61+ name of a registered filter and ``arguments``62+ a tuple with the filter arguments. The filters63+ specified here will always be applied when64+ printing data to the template.65+ *new in jinja 1.1*66 `template_charset` The charset of the templates. Defaults67 to ``'utf-8'``.68 `charset` Charset of all string input data. Defaults69 to ``'utf-8'``.28 unmodified lines98 99 There are also some internal functions on the environment used by the template100 evaluation code to keep it sandboxed.101 102+Automatic Escaping103+==================104+105+Jinja provides a way for automatic escaping, but we do not recommend using it.106+Because Jinja was designed as multi purpose template engine there are some107+issues with automatic escaping. For example filters don't deal with markup108+data. Also you can easily bypass the automatic escaping so it's not something109+you can expect to "just work". Also there is a huge overhead when escaping110+everything.111+112+The best idea is to think about which data already contains html, which will113+probably contain (eg: every user input, etc) etc. And live with self escaping.114+115+That's usually a much better idea.116+117+118 Loading Templates From Files119 ============================120 121 Loading templates from a string is always a bad idea. It doesn't allow template49 unmodified linesmodified:jinja/translators/python.py+14 added-21 removed
202 unmodified lines203 'filters are not supported.',204 n.lineno)205 args.append(self.handle_node(arg))206 if n.star_args is not None or n.dstar_args is not None:207- raise TemplateSynaxError('*args / **kwargs is not supported '208- 'for filters', n.lineno)207+ raise TemplateSyntaxError('*args / **kwargs is not supported '208+ 'for filters', n.lineno)209 filters.append('(%r, %s)' % (210 n.node.name,211 _to_tuple(args)212 ))26 unmodified lines239 self.last_debug_comment = None240 241 def translate(self):242 self.reset()243- return self.handle_node(self.node)243+ rv = self.handle_node(self.node)244+ print rv245+ return rv246 247 # -- jinja nodes248 249 def handle_template(self, node):218 unmodified lines468 hardcoded = False469 self.indention -= 1470 471 if hardcoded:470- write('yield finish_var(context.current[%r].cycle())' % name)472+ write('yield finish_var(context.current[%r].cycle(), context)' % name)473 else:472- write('yield finish_var(context.current[%r].cycle(%s))' % (474+ write('yield finish_var(context.current[%r].cycle(%s), context)' % (475 name,476 self.handle_node(node.seq)477 ))478 5 unmodified lines484 """485 nodeinfo = self.nodeinfo(node) or ''486 if nodeinfo:487 nodeinfo = self.indent(nodeinfo) + '\n'486- return nodeinfo + self.indent('yield finish_var(%s)' %488+ return nodeinfo + self.indent('yield finish_var(%s, context)' %489 self.handle_node(node.variable))490 491 def handle_macro(self, node):492 """164 unmodified lines657 'tests are not supported.',658 n.lineno)659 args.append(self.handle_node(arg))660 if n.star_args is not None or n.dstar_args is not None:659- raise TemplateSynaxError('*args / **kwargs is not supported '660- 'for tests', n.lineno)661+ raise TemplateSyntaxError('*args / **kwargs is not supported '662+ 'for tests', n.lineno)663 else:664 raise TemplateSyntaxError('is operator requires a test name'665 ' as operand', node.lineno)666 return 'perform_test(context, %r, %s, %s, %s)' % (32 unmodified lines699 return '%s[%s]' % (700 self.handle_node(node.expr),701 self.handle_node(node.subs[0])702 )701- return 'get_attribute(%s, (%s,))' % (703+ return 'get_attribute(%s, %s)' % (704 self.handle_node(node.expr),705 self.handle_node(node.subs[0])706 )707 708 def handle_getattr(self, node):709 """708- Handle hardcoded attribute access. foo.bar710+ Handle hardcoded attribute access.711 """710- expr = node.expr711-712- # chain getattrs for speed reasons713- path = [repr(node.attrname)]714- while node.expr.__class__ is ast.Getattr:715- node = node.expr716- path.append(repr(node.attrname))717- path.reverse()718-719- return 'get_attribute(%s, %s)' % (712+ return 'get_attribute(%s, %r)' % (713 self.handle_node(node.expr),721- _to_tuple(path)714+ node.attrname715 )716 717 def handle_ass_tuple(self, node):718 """170 unmodified linesmodified:jinja/__init__.py+62 added-4 removed
1 # -*- coding: utf-8 -*-2 """3- Jinja Sandboxed Template Engine4- ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~3+ jinja4+ ~~~~~5 6+ Jinja is a `sandboxed`_ template engine written in pure Python. It7+ provides a `Django`_ like non-XML syntax and compiles templates into8+ executable python code. It's basically a combination of Django templates9+ and python code.10+11+ Nutshell12+ --------13+14+ Here a small example of a Jinja template::15+16+ {% extends 'base.html' %}17+ {% block title %}Memberlist{% endblock %}18+ {% block content %}19+ <ul>20+ {% for user in users %}21+ <li><a href="{{ user.url|e }}">{{ user.username|e }}</a></li>22+ {% endfor %}23+ </ul>24+ {% endblock %}25+26+ Philosophy27+ ----------28+29+ Application logic is for the controller but don't try to make the life30+ for the template designer too hard by giving him too few functionality.31+32+ For more informations visit the new `jinja webpage`_ and `documentation`_.33+34+ Note35+ ----36+37+ This is the Jinja 1.0 release which is completely incompatible with the38+ old "pre 1.0" branch. The old branch will still receive security updates39+ and bugfixes but the 1.0 branch will be the only version that receives40+ support.41+42+ If you have an application that uses Jinja 0.9 and won't be updated in43+ the near future the best idea is to ship a Jinja 0.9 checkout together44+ with the application.45+46+ The `Jinja trunk`_ is installable via `easy_install` with ``easy_install47+ Jinja==dev``.48+49+ .. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_(computer_security)50+ .. _Django: http://www.djangoproject.com/51+ .. _jinja webpage: http://jinja.pocoo.org/52+ .. _documentation: http://jinja.pocoo.org/documentation/index.html53+ .. _Jinja trunk: http://trac.pocoo.org/repos/jinja/trunk#egg=Jinja-dev54+55+56 :copyright: 2007 by Armin Ronacher.57 :license: BSD, see LICENSE for more details.58 """59+60 from jinja.environment import Environment61+from jinja.datastructure import Markup62+from jinja.utils import from_string63 from jinja.plugin import jinja_plugin_factory as template_plugin_factory11-from jinja.loaders import *12-from_string = Environment().from_string64+from jinja.loaders import FileSystemLoader, PackageLoader, DictLoader, \65+ ChoiceLoader, FunctionLoader66+67+68+__all__ = ['Environment', 'Markup', 'FileSystemLoader', 'PackageLoader',69+ 'DictLoader', 'ChoiceLoader', 'FunctionLoader', 'from_string',70+ 'template_plugin_factory']modified:jinja/datastructure.py+13 added-4 removed
14 unmodified lines15 except NameError:16 from sets import Set as set17 18 from jinja.exceptions import TemplateSyntaxError, TemplateRuntimeError19+from cgi import escape20 21+_known_safe_types = set([int, long, float])22 23+24 def contextcallable(f):25 """26 Mark a function context callable.27 """96 unmodified lines124 125 126 class Markup(unicode):127 """125- Mark a string as safe for XML. If the environment uses the126- auto_escape option values marked as `Markup` aren't escaped.128+ Compatibility for Pylons and probably some other frameworks.129 """130 129- def __repr__(self):130- return 'Markup(%s)' % unicode.__repr__(self)131+ def __html__(self):132+ return unicode(self)133 134 135+class TemplateData(Markup):136+ """137+ Subclass of unicode to mark objects that are coming from the138+ template. The autoescape filter can use that.139+ """140+141+142 class Context(object):143 """144 Dict like object.145 """237 unmodified linesmodified:jinja/environment.py+31 added-27 removed
10 unmodified lines11 import re12 from jinja.lexer import Lexer13 from jinja.parser import Parser14 from jinja.loaders import LoaderWrapper15-from jinja.datastructure import Undefined, Context, Markup, FakeTranslator15+from jinja.datastructure import Undefined, Markup, Context, FakeTranslator16 from jinja.utils import escape, collect_translations17-from jinja.exceptions import FilterNotFound, TestNotFound, SecurityException17+from jinja.exceptions import FilterNotFound, TestNotFound18 from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE19 20 21 class Environment(object):9 unmodified lines31 comment_start_string='{#',32 comment_end_string='#}',33 trim_blocks=False,34 auto_escape=False,35+ default_filters=None,36 template_charset='utf-8',37 charset='utf-8',38 namespace=None,39 loader=None,15 unmodified lines55 self.charset = charset56 self.loader = loader57 self.filters = filters is None and DEFAULT_FILTERS.copy() or filters58 self.tests = tests is None and DEFAULT_TESTS.copy() or tests58- self.auto_escape = auto_escape59+ self.default_filters = default_filters or []60 self.context_class = context_class61 62 # global namespace63 self.globals = namespace is None and DEFAULT_NAMESPACE.copy() \64 or namespace65 66+ # jinja 1.0 compatibility67+ if auto_escape:68+ self.default_filters.append(('escape', (True,)))69+ self.globals['Markup'] = Markup70+71 # create lexer72 self.lexer = Lexer(self)73 74 def loader(self, value):81 unmodified lines156 if invert:157 return not rv158 return bool(rv)159 154- def get_attribute(self, obj, attributes):160+ def get_attribute(self, obj, name):161 """156- Get some attributes from an object.162+ Get one attribute from an object.163 """158- node = obj159- for name in attributes:160- try:161- node = node[name]162- except (TypeError, KeyError, IndexError):163- if not hasattr(node, name):164- return Undefined165- r = getattr(obj, 'jinja_allowed_attributes', None)166- if r is not None and name not in r:167- raise SecurityException('unsafe attributed %r accessed' % name)168- node = getattr(node, name)169- return node164+ try:165+ return obj[name]166+ except (TypeError, KeyError, IndexError):167+ if name[:2] == name[-2:] == '__':168+ return Undefined169+ if not hasattr(obj, name):170+ return Undefined171+ r = getattr(obj, 'jinja_allowed_attributes', None)172+ if r is not None and name not in r:173+ return Undefined174+ return getattr(obj, name)175+ return Undefined176 177 def call_function(self, f, context, args, kwargs, dyn_args, dyn_kwargs):178 """179 Function call helper. Called for all functions that are passed4 unmodified lines184 elif dyn_kwargs is not None:185 kwargs.update(dyn_kwargs)186 if getattr(f, 'jinja_unsafe_call', False) or \187 getattr(f, 'alters_data', False):182- raise SecurityException('unsafe function %r called' % f.__name__)188+ return Undefined189 if getattr(f, 'jinja_context_callable', False):190 args = (self, context) + args191 return f(*args, **kwargs)192 3 unmodified lines196 fewer logic here we have a bit of redundant code.197 """198 if getattr(f, 'jinja_unsafe_call', False) or \199 getattr(f, 'alters_data', False):194- raise SecurityException('unsafe function %r called' % f.__name__)200+ return Undefined201 if getattr(f, 'jinja_context_callable', False):202 return f(self, context)203 return f()204 199- def finish_var(self, value):205+ def finish_var(self, value, ctx):206 """207 As long as no write_var function is passed to the template208 evaluator the source generated by the python translator will209 call this function for all variables.210 """211 if value is Undefined or value is None:212 return u''207- elif isinstance(value, (int, float, Markup, bool)):208- return unicode(value)209- elif not isinstance(value, unicode):210- value = self.to_unicode(value)211- if self.auto_escape:212- return escape(value, True)213- return value213+ val = self.to_unicode(value)214+ # apply default filters215+ if self.default_filters:216+ val = self.apply_filters(val, ctx, self.default_filters)217+ return valmodified:jinja/exceptions.py+2 added
15 unmodified lines16 17 class SecurityException(TemplateError):18 """19 Raise if the template designer tried to do something dangerous.20+21+ Not used any more. exists for backwards compatibility.22 """23 24 25 class FilterNotFound(KeyError, TemplateError):60 unmodified linesmodified:jinja/filters.py+15 added-10 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 from random import choice12 from urllib import urlencode, quote13-from jinja.utils import escape, urlize14-from jinja.datastructure import Undefined13+from jinja.utils import urlize, escape14+from jinja.datastructure import Undefined, Markup, TemplateData15 from jinja.exceptions import FilterArgumentError16 17 18 try:48 unmodified lines67 -> d'oh, d'oh, aaargh68 """69 if not isinstance(old, basestring) or \70 not isinstance(new, basestring):71- raise FilterArgumentException('the replace filter requires '72- 'string replacement arguments')71+ raise FilterArgumentError('the replace filter requires '72+ 'string replacement arguments')73 elif not isinstance(count, (int, long)):74- raise FilterArgumentException('the count parameter of the '75- 'replace filter requires '76- 'an integer')74+ raise FilterArgumentError('the count parameter of the '75+ 'replace filter requires '76+ 'an integer')77 if count is None:78 return s.replace(old, new)79 return s.replace(old, new, count)80 do_replace = stringfilter(do_replace)14 unmodified lines95 return s.lower()96 do_lower = stringfilter(do_lower)97 98 99-def do_escape(s, attribute=False):99+def do_escape(attribute=False):100 """101 XML escape ``&``, ``<``, and ``>`` in a string of data. If the102 optional parameter is `true` this filter will also convert103 ``"`` to ``"``. This filter is just used if the environment104 was configured with disabled `auto_escape`.105 106 This method will have no effect it the value is already escaped.107 """108- return escape(s, attribute)109-do_escape = stringfilter(do_escape)108+ def wrapped(env, context, s):109+ if isinstance(s, TemplateData):110+ return s111+ elif hasattr(s, '__html__'):112+ return s.__html__()113+ return escape(env.to_unicode(s), attribute)114+ return wrapped115 116 117 def do_capitalize(s):118 """532 unmodified linesmodified:jinja/loaders.py+1 added
23 unmodified lines24 except ImportError:25 resource_exists = resource_string = resource_filename = None26 27 28+#: when updating this, update the listing in the jinja package too29 __all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader',30 'FunctionLoader']31 32 444 unmodified linesmodified:jinja/parser.py+1 added-1 removed
264 unmodified lines265 self.filename)266 block_name = tokens.pop(0)267 if block_name[1] != 'name':268 raise TemplateSyntaxError('expected \'name\', got %r' %269- block_name[1], lineno, seilf.filename)269+ block_name[1], lineno, self.filename)270 # disallow keywords271 if not block_name[2].endswith('_'):272 raise TemplateSyntaxError('illegal use of keyword %r '273 'as block name.' % block_name[2],362 unmodified linesmodified:jinja/utils.py+17 added-20 removed
12 unmodified lines13 """14 import re15 import sys16 import string17+import cgi18 from types import MethodType, FunctionType19 from compiler.ast import CallFunc, Name, Const20 from jinja.nodes import Trans20-from jinja.datastructure import Markup, Context21+from jinja.datastructure import Context, TemplateData22 23 try:24 from collections import deque25 except ImportError:3 unmodified lines29 MAX_RANGE = 100000030 31 _debug_info_re = re.compile(r'^\s*\# DEBUG\(filename=(.*?), lineno=(.*?)\)$')32 32-_escape_pairs = {33- '&': '&',34- '<': '<',35- '>': '>',36- '"': '"'37-}38-39-_escape_res = (40- re.compile('(&|<|>|")'),41- re.compile('(&|<|>)')42-)43-33 _integer_re = re.compile('^(\d+)$')34 35 _word_split_re = re.compile(r'(\s+)')36 5 unmodified lines42 )43 44 _simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')45 46+#: used by from_string as cache47+_from_string_env = None48 58-def escape(x, attribute=False):59- """60- Escape an object x.61- """62- return Markup(_escape_res[not attribute].sub(lambda m:63- _escape_pairs[m.group()], x))49+escape = cgi.escape50 51 52 def urlize(text, trim_url_limit=None, nofollow=False):53 """39 unmodified lines93 words[i] = lead + middle + trail94 return u''.join(words)95 96 97+def from_string(source):98+ """99+ Create a template from the template source.100+ """101+ global _from_string_env102+ if _from_string_env is None:103+ from jinja.environment import Environment104+ _from_string_env = Environment()105+ return _from_string_env.from_string(source)106+107+108 def debug_context(env, context):109 """110 Use this function in templates to get a printed context.111 """41 unmodified lines153 Used by the python translator to capture output of substreams.154 (macros, filter sections etc)155 """156 def wrapped(*args, **kwargs):160- return capture_generator(f(*args, **kwargs))157+ return TemplateData(capture_generator(f(*args, **kwargs)))158 return wrapped159 160 161 def fake_template_exception(exception, filename, lineno, context_or_env):240 unmodified linesmodified:setup.py+3 added-52 removed
1 # -*- coding: utf-8 -*-2-"""3-Jinja4-=====5-6-Jinja is a `sandboxed`_ template engine written in pure Python. It provides a7-`Django`_ like non-XML syntax and compiles templates into executable python code.8-It's basically a combination of Django templates and python code.9-10-Nutshell11---------12-13-Here a small example of a Jinja template::14-15- {% extends 'base.html' %}16- {% block title %}Memberlist{% endblock %}17- {% block content %}18- <ul>19- {% for user in users %}20- <li><a href="{{ user.url|e }}">{{ user.username|e }}</a></li>21- {% endfor %}22- </ul>23- {% endblock %}24-25-Philosophy26-----------27-28-Application logic is for the controller but don't try to make the life for the29-template designer too hard by giving him too few functionality.30-31-For more informations visit the new `jinja webpage`_ and `documentation`_.32-33-Note34-----35-36-This is the Jinja 1.0 release which is completely incompatible with the old37-"pre 1.0" branch. The old branch will still receive security updates and38-bugfixes but the 1.0 branch will be the only version that receives support.39-40-If you have an application that uses Jinja 0.9 and won't be updated in the41-near future the best idea is to ship a Jinja 0.9 checkout together with42-the application.43-44-The `Jinja trunk`_ is installable via `easy_install` with ``easy_install45-Jinja==dev``.46-47-.. _sandboxed: http://en.wikipedia.org/wiki/Sandbox_%28computer_security%2948-.. _Django: http://www.djangoproject.com/49-.. _jinja webpage: http://jinja.pocoo.org/50-.. _documentation: http://jinja.pocoo.org/documentation/index.html51-.. _Jinja trunk: http://trac.pocoo.org/repos/jinja/trunk#egg=Jinja-dev52-"""2+import jinja3 import os4 import ez_setup5 ez_setup.use_setuptools()6 from setuptools import setup7+from inspect import getdoc8 9 10 def list_files(path):11 for fn in os.listdir(path):12 unmodified lines24 author = 'Armin Ronacher',25 author_email = 'armin.ronacher@active-4.com',26 description = 'A small but fast and easy to use stand-alone template '27 'engine written in pure python.',77- long_description = __doc__,28+ long_description = getdoc(jinja),29 # jinja is egg safe. But because we distribute the documentation30 # in form of html and txt files it's a better idea to extract the files31 zip_safe = False,32 classifiers = [19 unmodified lines