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
Provenance
- Commit
18c6ca0- Tree
d206b8f- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
e6aa662
7 files changed+124 added−26 removed
modified:jinja2/__init__.py+1 added
56 unmodified lines57 :license: BSD, see LICENSE for more details.58 """59 from jinja2.environment import Environment60 from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined61+from jinja2.utils import Markup, escapemodified:jinja2/compiler.py+3 added-3 removed
779 unmodified lines780 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 = True786 787 # 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 lines845 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 linesmodified:jinja2/debug.py+4 added-1 removed
7 unmodified lines8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: BSD.10 """11 import sys12-from jinja2.exceptions import TemplateNotFound12 13 14 def translate_exception(exc_info):15 """If passed an exc_info it will automatically rewrite the exceptions26 unmodified lines42 for name, value in real_locals.iteritems():43 if name.startswith('l_'):44 locals[name[2:]] = value45 46+ # 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)49+50 # assamble fake globals we need51 globals = {52 '__name__': filename,53 '__file__': filename,89 unmodified linesmodified:jinja2/environment.py+3 added-7 removed
40 unmodified lines41 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:48 49 ========================= ============================================50 `block_start_string` the string marking the begin of a block.37 unmodified lines88 self.line_statement_prefix = line_statement_prefix89 self.trim_blocks = trim_blocks90 self.undefined = undefined91 self.optimized = optimized92+ self.finalize = finalize93 94 # defaults95 self.filters = DEFAULT_FILTERS.copy()96 self.tests = DEFAULT_TESTS.copy()97 self.globals = DEFAULT_NAMESPACE.copy()98 97- # 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 = unicode102-99 # set the loader provided100 self.loader = loader101 102 # create lexer186 unmodified linesmodified:jinja2/filters.py+3 added-2 removed
13 unmodified lines14 from operator import itemgetter15 except ImportError:16 itemgetter = lambda a: lambda b: b[a]17 from urllib import urlencode, quote18-from jinja2.utils import escape, pformat, urlize18+from jinja2.utils import Markup, escape, pformat, urlize19 from jinja2.runtime import Undefined20 21 22 687 unmodified lines710 '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 lines11 try:12 from collections import defaultdict13 except ImportError:14 defaultdict = None15+from jinja2.utils import Markup16 17 18 __all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',19 'Macro', 'IncludedTemplate', 'TemplateData']20 21 21-class TemplateData(unicode):22+class 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__ = ()28 26- def __html__(self):27- return self29 29-30 class 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 update84 unmodified lines118 def __getitem__(self, name):119 return self._context[name]120 121 def __unicode__(self):122- return self._context122+ return self._rendered_body123 124+ def __html__(self):125+ return self._rendered_body126+127 def __repr__(self):128 return '<%s %r>' % (129 self.__class__.__name__,130 self._filename197 unmodified linesmodified:jinja2/utils.py+101 added-7 removed
8 unmodified lines9 :license: BSD, see LICENSE for more details.10 """11 import re12 import string13+from functools import update_wrapper14+from itertools import imap15 16 17 def escape(obj, attribute=False):18 """HTML escape an object."""19 if hasattr(obj, '__html__'):20 return obj.__html__()19- return unicode(obj) \20- .replace('&', '&') \21- .replace('>', '>') \22- .replace('<', '<') \21+ return Markup(unicode(obj)22+ .replace('&', '&')23+ .replace('>', '>')24+ .replace('<', '<')25 .replace('"', '"')26+ )27 28 29 def pformat(obj, verbose=False):30 """10 unmodified lines41 42 _word_split_re = re.compile(r'(\s+)')43 44 _punctuation_re = re.compile(42- '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (43- '|'.join([re.escape(p) for p in ('(', '<', '<')]),44- '|'.join([re.escape(p) for p in ('.', ',', ')', '>', '\n', '>')])45+ '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (46+ '|'.join(imap(re.escape, ('(', '<', '<'))),47+ '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '>')))48 )49 )50 51 _simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')41 unmodified lines93 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)97+98+99+class 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.103+104+ 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+ """108+109+ __slots__ = ()110+111+ def __html__(self):112+ return self113+114+ def __add__(self, other):115+ if hasattr(other, '__html__') or isinstance(other, basestring):116+ return self.__class__(unicode(self) + unicode(escape(other)))117+ return NotImplemented118+119+ def __radd__(self, other):120+ if hasattr(other, '__html__') or isinstance(other, basestring):121+ return self.__class__(unicode(escape(other)) + unicode(self))122+ return NotImplemented123+124+ def __mul__(self, num):125+ if not isinstance(num, (int, long)):126+ return NotImplemented127+ return self.__class__(unicode.__mul__(self, num))128+ __rmul__ = __mul__129+130+ 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))136+137+ def __repr__(self):138+ return '%s(%s)' % (139+ self.__class__.__name__,140+ unicode.__repr__(self)141+ )142+143+ def join(self, seq):144+ return self.__class__(unicode.join(self, imap(escape, seq)))145+146+ def split(self, *args, **kwargs):147+ return map(self.__class__, unicode.split(self, *args, **kwargs))148+149+ def rsplit(self, *args, **kwargs):150+ return map(self.__class__, unicode.rsplit(self, *args, **kwargs))151+152+ def splitlines(self, *args, **kwargs):153+ return map(self.__class__, unicode.splitlines(self, *args, **kwargs))154+155+ 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_wrapper174+175+176+class _MarkupEscapeHelper(object):177+ """Helper for Markup.__mod__"""178+179+ def __init__(self, obj):180+ self.obj = obj181+182+ __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)