Skip to content
Myr

added autoescaping

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 e6aa662 · Browse files · 7 files+124 added−26 removed
This commit

State

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

Diff stats

7 files+124 added−26 removed

  • other:+124 added−26 removed

7 files+124 added−26 removed

modified:jinja2/__init__.py+1 added
56 unmodified lines
57 :license: BSD, see LICENSE for more details.58"""59from jinja2.environment import Environment60from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined61from jinja2.utils import Markup, escape
modified:jinja2/compiler.py+3 added-3 removed
779 unmodified lines
780 if self.environment.finalize is unicode:781 finalizer = 'unicode'782 have_finalizer = False783 else:784 finalizer = 'context.finalize'785 have_finalizer = False784 finalizer = 'environment.finalize'785 have_finalizer = True786787 # if we are in the toplevel scope and there was already an extends788 # statement we have to add a check that disables our yield(s) here789 # so that they don't appear in the output.
55 unmodified lines
845 self.indent()846 for argument in arguments:847 self.newline(argument)848 if have_finalizer:849 self.write('(')849 self.write(finalizer + '(')850 self.visit(argument, frame)851 if have_finalizer:852 self.write(')')853 self.write(',')
201 unmodified lines
modified:jinja2/debug.py+4 added-1 removed
7 unmodified lines
8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10"""11import sys12from jinja2.exceptions import TemplateNotFound121314def translate_exception(exc_info):15 """If passed an exc_info it will automatically rewrite the exceptions
26 unmodified lines
42 for name, value in real_locals.iteritems():43 if name.startswith('l_'):44 locals[name[2:]] = value4546 # if there is a local called __jinja_exception__, we get47 # rid of it to not break the debug functionality.48 locals.pop('__jinja_exception__', None)4950 # assamble fake globals we need51 globals = {52 '__name__': filename,53 '__file__': filename,
89 unmodified lines
modified:jinja2/environment.py+3 added-7 removed
40 unmodified lines
41 line_statement_prefix=None,42 trim_blocks=False,43 optimized=True,44 undefined=Undefined,45 loader=None):45 loader=None,46 finalize=unicode):47 """Here the possible initialization parameters:4849 ========================= ============================================50 `block_start_string` the string marking the begin of a block.
37 unmodified lines
88 self.line_statement_prefix = line_statement_prefix89 self.trim_blocks = trim_blocks90 self.undefined = undefined91 self.optimized = optimized92 self.finalize = finalize9394 # defaults95 self.filters = DEFAULT_FILTERS.copy()96 self.tests = DEFAULT_TESTS.copy()97 self.globals = DEFAULT_NAMESPACE.copy()9897 # if no finalize function/method exists we default to unicode. The98 # compiler check if the finalize attribute *is* unicode, if yes no99 # finalizaion is written where it can be avoided.100 if not hasattr(self, 'finalize'):101 self.finalize = unicode10299 # set the loader provided100 self.loader = loader101102 # create lexer
186 unmodified lines
modified:jinja2/filters.py+3 added-2 removed
13 unmodified lines
14 from operator import itemgetter15except ImportError:16 itemgetter = lambda a: lambda b: b[a]17from urllib import urlencode, quote18from jinja2.utils import escape, pformat, urlize18from jinja2.utils import Markup, escape, pformat, urlize19from jinja2.runtime import Undefined202122
687 unmodified lines
710 'sum': sum,711 'abs': abs,712 'round': do_round,713 'sort': do_sort,714 'groupby': do_groupby714 'groupby': do_groupby,715 'safe': Markup716}
modified:jinja2/runtime.py+9 added-6 removed
10 unmodified lines
11try:12 from collections import defaultdict13except ImportError:14 defaultdict = None15from jinja2.utils import Markup161718__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',19 'Macro', 'IncludedTemplate', 'TemplateData']202121class TemplateData(unicode):22class TemplateData(Markup):23 """Marks data as "coming from the template". This is used to let the24 system know that this data is already processed if a finalization is24 used."""25 used.26 """27 __slots__ = ()2826 def __html__(self):27 return self292930class TemplateContext(dict):31 """Holds the variables of the local template or of the global one. It's32 not save to use this class outside of the compiled code. For example33 update and other methods will not work as they seem (they don't update
84 unmodified lines
118 def __getitem__(self, name):119 return self._context[name]120121 def __unicode__(self):122 return self._context122 return self._rendered_body123124 def __html__(self):125 return self._rendered_body126127 def __repr__(self):128 return '<%s %r>' % (129 self.__class__.__name__,130 self._filename
197 unmodified lines
modified:jinja2/utils.py+101 added-7 removed
8 unmodified lines
9 :license: BSD, see LICENSE for more details.10"""11import re12import string13from functools import update_wrapper14from itertools import imap151617def escape(obj, attribute=False):18 """HTML escape an object."""19 if hasattr(obj, '__html__'):20 return obj.__html__()19 return unicode(obj) \20 .replace('&', '&amp;') \21 .replace('>', '&gt;') \22 .replace('<', '&lt;') \21 return Markup(unicode(obj)22 .replace('&', '&amp;')23 .replace('>', '&gt;')24 .replace('<', '&lt;')25 .replace('"', '&quot;')26 )272829def pformat(obj, verbose=False):30 """
10 unmodified lines
4142_word_split_re = re.compile(r'(\s+)')4344_punctuation_re = re.compile(42 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (43 '|'.join([re.escape(p) for p in ('(', '<', '&lt;')]),44 '|'.join([re.escape(p) for p in ('.', ',', ')', '>', '\n', '&gt;')])45 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (46 '|'.join(imap(re.escape, ('(', '<', '&lt;'))),47 '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '&gt;')))48 )49)5051_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')
41 unmodified lines
93 middle = '<a href="mailto:%s">%s</a>' % (middle, middle)94 if lead + middle + trail != word:95 words[i] = lead + middle + trail96 return u''.join(words)979899class Markup(unicode):100 """Marks a string as being safe for inclusion in HTML/XML output without101 needing to be escaped. This implements the `__html__` interface a couple102 of frameworks and web applications use.103104 The `escape` function returns markup objects so that double escaping can't105 happen. If you want to use autoescaping in Jinja just set the finalizer106 of the environment to `escape`.107 """108109 __slots__ = ()110111 def __html__(self):112 return self113114 def __add__(self, other):115 if hasattr(other, '__html__') or isinstance(other, basestring):116 return self.__class__(unicode(self) + unicode(escape(other)))117 return NotImplemented118119 def __radd__(self, other):120 if hasattr(other, '__html__') or isinstance(other, basestring):121 return self.__class__(unicode(escape(other)) + unicode(self))122 return NotImplemented123124 def __mul__(self, num):125 if not isinstance(num, (int, long)):126 return NotImplemented127 return self.__class__(unicode.__mul__(self, num))128 __rmul__ = __mul__129130 def __mod__(self, arg):131 if isinstance(arg, tuple):132 arg = tuple(imap(_MarkupEscapeHelper, arg))133 else:134 arg = _MarkupEscapeHelper(arg)135 return self.__class__(unicode.__mod__(self, arg))136137 def __repr__(self):138 return '%s(%s)' % (139 self.__class__.__name__,140 unicode.__repr__(self)141 )142143 def join(self, seq):144 return self.__class__(unicode.join(self, imap(escape, seq)))145146 def split(self, *args, **kwargs):147 return map(self.__class__, unicode.split(self, *args, **kwargs))148149 def rsplit(self, *args, **kwargs):150 return map(self.__class__, unicode.rsplit(self, *args, **kwargs))151152 def splitlines(self, *args, **kwargs):153 return map(self.__class__, unicode.splitlines(self, *args, **kwargs))154155 def make_wrapper(name):156 orig = getattr(unicode, name)157 def func(self, *args, **kwargs):158 args = list(args)159 for idx, arg in enumerate(args):160 if hasattr(arg, '__html__') or isinstance(arg, basestring):161 args[idx] = escape(arg)162 for name, arg in kwargs.iteritems():163 if hasattr(arg, '__html__') or isinstance(arg, basestring):164 kwargs[name] = escape(arg)165 return self.__class__(orig(self, *args, **kwargs))166 return update_wrapper(func, orig, ('__name__', '__doc__'))167 for method in '__getitem__', '__getslice__', 'capitalize', \168 'title', 'lower', 'upper', 'replace', 'ljust', \169 'rjust', 'lstrip', 'rstrip', 'partition', 'center', \170 'strip', 'translate', 'expandtabs', 'rpartition', \171 'swapcase', 'zfill':172 locals()[method] = make_wrapper(method)173 del method, make_wrapper174175176class _MarkupEscapeHelper(object):177 """Helper for Markup.__mod__"""178179 def __init__(self, obj):180 self.obj = obj181182 __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x])183 __unicode__ = lambda s: unicode(escape(s.obj))184 __str__ = lambda s: str(escape(s.obj))185 __repr__ = lambda s: str(repr(escape(s.obj)))186 __int__ = lambda s: int(s.obj)187 __float__ = lambda s: float(s.obj)