Skip to content
Myr

[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

12 files+209 added−143 removed

modified:docs/src/contextenv.txt+22 added-4 removed
55 unmodified lines
56 `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.5960 **Warning** this is a jinja internal method. The actual implementation61 and function signature might change.6263**def** `perform_test` *(self, context, testname, args, value, invert)*:6465 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 lines
71 with the `is not` operator, `False` if with the `is` operator.7273 Missing tests should raise a `TestNotFound` exception.7472**def** `get_attribute` *(self, obj, attributes)*:75 **Warning** this is a jinja internal method. The actual implementation76 and function signature might change.7774 Get `attributes` from the object provided. The default implementation75 performs security tests for each attribute.78**def** `get_attribute` *(self, obj, attribute)*:7980 Get `attribute` from the object provided. The default implementation81 performs security tests.8283 **Warning** this is a jinja internal method. The actual implementation84 and function signature might change.8586**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 line
91 not `None` you have to update the `kwargs` with it.9293 The default implementation performs some security checks.9495 **Warning** this is a jinja internal method. The actual implementation96 and function signature might change.9798**def** `call_function_simple` *(self, f, context)*:99100 Like `call_function` but without arguments.10190**def** `finish_var` *(self, value)*:102 **Warning** this is a jinja internal method. The actual implementation103 and function signature might change.104105**def** `finish_var` *(self, value, ctx)*:106107 Postprocess a variable before it's sent to the template.108109 **Warning** this is a jinja internal method. The actual implementation110 and function signature might change.111 112.. admonition:: Note113114 The Enviornment class is defined in `jinja.environment.Environment`
48 unmodified lines
modified:docs/src/devintro.txt+28 added
49 unmodified lines
50 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 lines
9899There are also some internal functions on the environment used by the template100evaluation code to keep it sandboxed.101102Automatic Escaping103==================104105Jinja provides a way for automatic escaping, but we do not recommend using it.106Because Jinja was designed as multi purpose template engine there are some107issues with automatic escaping. For example filters don't deal with markup108data. Also you can easily bypass the automatic escaping so it's not something109you can expect to "just work". Also there is a huge overhead when escaping110everything.111112The best idea is to think about which data already contains html, which will113probably contain (eg: every user input, etc) etc. And live with self escaping.114115That's usually a much better idea.116117118Loading Templates From Files119============================120121Loading templates from a string is always a bad idea. It doesn't allow template
49 unmodified lines
modified:jinja/translators/python.py+14 added-21 removed
202 unmodified lines
203 '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 lines
239 self.last_debug_comment = None240241 def translate(self):242 self.reset()243 return self.handle_node(self.node)243 rv = self.handle_node(self.node)244 print rv245 return rv246247 # -- jinja nodes248249 def handle_template(self, node):
218 unmodified lines
468 hardcoded = False469 self.indention -= 1470471 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 lines
484 """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))490491 def handle_macro(self, node):492 """
164 unmodified lines
657 '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 lines
699 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 )707708 def handle_getattr(self, node):709 """708 Handle hardcoded attribute access. foo.bar710 Handle hardcoded attribute access.711 """710 expr = node.expr711712 # 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()718719 return 'get_attribute(%s, %s)' % (712 return 'get_attribute(%s, %r)' % (713 self.handle_node(node.expr),721 _to_tuple(path)714 node.attrname715 )716717 def handle_ass_tuple(self, node):718 """
170 unmodified lines
modified:jinja/__init__.py+62 added-4 removed
1# -*- coding: utf-8 -*-2"""3 Jinja Sandboxed Template Engine4 ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~3 jinja4 ~~~~~56 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.1011 Nutshell12 --------1314 Here a small example of a Jinja template::1516 {% 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 %}2526 Philosophy27 ----------2829 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.3132 For more informations visit the new `jinja webpage`_ and `documentation`_.3334 Note35 ----3637 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.4142 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.4546 The `Jinja trunk`_ is installable via `easy_install` with ``easy_install47 Jinja==dev``.4849 .. _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-dev545556 :copyright: 2007 by Armin Ronacher.57 :license: BSD, see LICENSE for more details.58"""5960from jinja.environment import Environment61from jinja.datastructure import Markup62from jinja.utils import from_string63from jinja.plugin import jinja_plugin_factory as template_plugin_factory11from jinja.loaders import *12from_string = Environment().from_string64from jinja.loaders import FileSystemLoader, PackageLoader, DictLoader, \65 ChoiceLoader, FunctionLoader666768__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 lines
15except NameError:16 from sets import Set as set1718from jinja.exceptions import TemplateSyntaxError, TemplateRuntimeError19from cgi import escape2021_known_safe_types = set([int, long, float])222324def contextcallable(f):25 """26 Mark a function context callable.27 """
96 unmodified lines
124125126class 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 """130129 def __repr__(self):130 return 'Markup(%s)' % unicode.__repr__(self)131 def __html__(self):132 return unicode(self)133134135class TemplateData(Markup):136 """137 Subclass of unicode to mark objects that are coming from the138 template. The autoescape filter can use that.139 """140141142class Context(object):143 """144 Dict like object.145 """
237 unmodified lines
modified:jinja/environment.py+31 added-27 removed
10 unmodified lines
11import re12from jinja.lexer import Lexer13from jinja.parser import Parser14from jinja.loaders import LoaderWrapper15from jinja.datastructure import Undefined, Context, Markup, FakeTranslator15from jinja.datastructure import Undefined, Markup, Context, FakeTranslator16from jinja.utils import escape, collect_translations17from jinja.exceptions import FilterNotFound, TestNotFound, SecurityException17from jinja.exceptions import FilterNotFound, TestNotFound18from jinja.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE192021class Environment(object):
9 unmodified lines
31 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 lines
55 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_class6162 # global namespace63 self.globals = namespace is None and DEFAULT_NAMESPACE.copy() \64 or namespace6566 # jinja 1.0 compatibility67 if auto_escape:68 self.default_filters.append(('escape', (True,)))69 self.globals['Markup'] = Markup7071 # create lexer72 self.lexer = Lexer(self)7374 def loader(self, value):
81 unmodified lines
156 if invert:157 return not rv158 return bool(rv)159154 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 Undefined176177 def call_function(self, f, context, args, kwargs, dyn_args, dyn_kwargs):178 """179 Function call helper. Called for all functions that are passed
4 unmodified lines
184 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 lines
196 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()204199 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 val
modified:jinja/exceptions.py+2 added
15 unmodified lines
1617class SecurityException(TemplateError):18 """19 Raise if the template designer tried to do something dangerous.2021 Not used any more. exists for backwards compatibility.22 """232425class FilterNotFound(KeyError, TemplateError):
60 unmodified lines
modified:jinja/filters.py+15 added-10 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11from random import choice12from urllib import urlencode, quote13from jinja.utils import escape, urlize14from jinja.datastructure import Undefined13from jinja.utils import urlize, escape14from jinja.datastructure import Undefined, Markup, TemplateData15from jinja.exceptions import FilterArgumentError161718try:
48 unmodified lines
67 -> 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)80do_replace = stringfilter(do_replace)
14 unmodified lines
95 return s.lower()96do_lower = stringfilter(do_lower)979899def do_escape(s, attribute=False):99def 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 ``&quot;``. This filter is just used if the environment104 was configured with disabled `auto_escape`.105106 This method will have no effect it the value is already escaped.107 """108 return escape(s, attribute)109do_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 wrapped115116117def do_capitalize(s):118 """
532 unmodified lines
modified:jinja/loaders.py+1 added
23 unmodified lines
24except ImportError:25 resource_exists = resource_string = resource_filename = None262728#: when updating this, update the listing in the jinja package too29__all__ = ['FileSystemLoader', 'PackageLoader', 'DictLoader', 'ChoiceLoader',30 'FunctionLoader']3132
444 unmodified lines
modified:jinja/parser.py+1 added-1 removed
264 unmodified lines
265 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 lines
modified:jinja/utils.py+17 added-20 removed
12 unmodified lines
13"""14import re15import sys16import string17import cgi18from types import MethodType, FunctionType19from compiler.ast import CallFunc, Name, Const20from jinja.nodes import Trans20from jinja.datastructure import Markup, Context21from jinja.datastructure import Context, TemplateData2223try:24 from collections import deque25except ImportError:
3 unmodified lines
29MAX_RANGE = 10000003031_debug_info_re = re.compile(r'^\s*\# DEBUG\(filename=(.*?), lineno=(.*?)\)$')3232_escape_pairs = {33 '&': '&amp;',34 '<': '&lt;',35 '>': '&gt;',36 '"': '&quot;'37}3839_escape_res = (40 re.compile('(&|<|>|")'),41 re.compile('(&|<|>)')42)4333_integer_re = re.compile('^(\d+)$')3435_word_split_re = re.compile(r'(\s+)')36
5 unmodified lines
42)4344_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')4546#: used by from_string as cache47_from_string_env = None4858def 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))49escape = cgi.escape505152def urlize(text, trim_url_limit=None, nofollow=False):53 """
39 unmodified lines
93 words[i] = lead + middle + trail94 return u''.join(words)959697def 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)106107108def debug_context(env, context):109 """110 Use this function in templates to get a printed context.111 """
41 unmodified lines
153 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 wrapped159160161def fake_template_exception(exception, filename, lineno, context_or_env):
240 unmodified lines
modified:setup.py+3 added-52 removed
1# -*- coding: utf-8 -*-2"""3Jinja4=====56Jinja is a `sandboxed`_ template engine written in pure Python. It provides a7`Django`_ like non-XML syntax and compiles templates into executable python code.8It's basically a combination of Django templates and python code.910Nutshell11--------1213Here a small example of a Jinja template::1415 {% 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 %}2425Philosophy26----------2728Application logic is for the controller but don't try to make the life for the29template designer too hard by giving him too few functionality.3031For more informations visit the new `jinja webpage`_ and `documentation`_.3233Note34----3536This 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 and38bugfixes but the 1.0 branch will be the only version that receives support.3940If you have an application that uses Jinja 0.9 and won't be updated in the41near future the best idea is to ship a Jinja 0.9 checkout together with42the application.4344The `Jinja trunk`_ is installable via `easy_install` with ``easy_install45Jinja==dev``.4647.. _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"""2import jinja3import os4import ez_setup5ez_setup.use_setuptools()6from setuptools import setup7from inspect import getdoc8910def list_files(path):11 for fn in os.listdir(path):
12 unmodified lines
24 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