Skip to content
Myr

Pulled in code from markupsafe

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 f9f5f26 · Browse files · 4 files+617 added−0 removed
This commit

State

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

Diff stats

4 files+617 added−0 removed

  • other:+617 added−0 removed

4 files+617 added−0 removed

added:jinja2/_markupsafe/__init__.py+225 added
1# -*- coding: utf-8 -*-2"""3 markupsafe4 ~~~~~~~~~~56 Implements a Markup string.78 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11import re12from itertools import imap131415__all__ = ['Markup', 'soft_unicode', 'escape', 'escape_silent']161718_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')19_entity_re = re.compile(r'&([^;]+);')202122class Markup(unicode):23 r"""Marks a string as being safe for inclusion in HTML/XML output without24 needing to be escaped. This implements the `__html__` interface a couple25 of frameworks and web applications use. :class:`Markup` is a direct26 subclass of `unicode` and provides all the methods of `unicode` just that27 it escapes arguments passed and always returns `Markup`.2829 The `escape` function returns markup objects so that double escaping can't30 happen.3132 The constructor of the :class:`Markup` class can be used for three33 different things: When passed an unicode object it's assumed to be safe,34 when passed an object with an HTML representation (has an `__html__`35 method) that representation is used, otherwise the object passed is36 converted into a unicode string and then assumed to be safe:3738 >>> Markup("Hello <em>World</em>!")39 Markup(u'Hello <em>World</em>!')40 >>> class Foo(object):41 ... def __html__(self):42 ... return '<a href="#">foo</a>'43 ... 44 >>> Markup(Foo())45 Markup(u'<a href="#">foo</a>')4647 If you want object passed being always treated as unsafe you can use the48 :meth:`escape` classmethod to create a :class:`Markup` object:4950 >>> Markup.escape("Hello <em>World</em>!")51 Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')5253 Operations on a markup string are markup aware which means that all54 arguments are passed through the :func:`escape` function:5556 >>> em = Markup("<em>%s</em>")57 >>> em % "foo & bar"58 Markup(u'<em>foo &amp; bar</em>')59 >>> strong = Markup("<strong>%(text)s</strong>")60 >>> strong % {'text': '<blink>hacker here</blink>'}61 Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')62 >>> Markup("<em>Hello</em> ") + "<foo>"63 Markup(u'<em>Hello</em> &lt;foo&gt;')64 """65 __slots__ = ()6667 def __new__(cls, base=u'', encoding=None, errors='strict'):68 if hasattr(base, '__html__'):69 base = base.__html__()70 if encoding is None:71 return unicode.__new__(cls, base)72 return unicode.__new__(cls, base, encoding, errors)7374 def __html__(self):75 return self7677 def __add__(self, other):78 if hasattr(other, '__html__') or isinstance(other, basestring):79 return self.__class__(unicode(self) + unicode(escape(other)))80 return NotImplemented8182 def __radd__(self, other):83 if hasattr(other, '__html__') or isinstance(other, basestring):84 return self.__class__(unicode(escape(other)) + unicode(self))85 return NotImplemented8687 def __mul__(self, num):88 if isinstance(num, (int, long)):89 return self.__class__(unicode.__mul__(self, num))90 return NotImplemented91 __rmul__ = __mul__9293 def __mod__(self, arg):94 if isinstance(arg, tuple):95 arg = tuple(imap(_MarkupEscapeHelper, arg))96 else:97 arg = _MarkupEscapeHelper(arg)98 return self.__class__(unicode.__mod__(self, arg))99100 def __repr__(self):101 return '%s(%s)' % (102 self.__class__.__name__,103 unicode.__repr__(self)104 )105106 def join(self, seq):107 return self.__class__(unicode.join(self, imap(escape, seq)))108 join.__doc__ = unicode.join.__doc__109110 def split(self, *args, **kwargs):111 return map(self.__class__, unicode.split(self, *args, **kwargs))112 split.__doc__ = unicode.split.__doc__113114 def rsplit(self, *args, **kwargs):115 return map(self.__class__, unicode.rsplit(self, *args, **kwargs))116 rsplit.__doc__ = unicode.rsplit.__doc__117118 def splitlines(self, *args, **kwargs):119 return map(self.__class__, unicode.splitlines(self, *args, **kwargs))120 splitlines.__doc__ = unicode.splitlines.__doc__121122 def unescape(self):123 r"""Unescape markup again into an unicode string. This also resolves124 known HTML4 and XHTML entities:125126 >>> Markup("Main &raquo; <em>About</em>").unescape()127 u'Main \xbb <em>About</em>'128 """129 from jinja2._markupsafe._constants import HTML_ENTITIES130 def handle_match(m):131 name = m.group(1)132 if name in HTML_ENTITIES:133 return unichr(HTML_ENTITIES[name])134 try:135 if name[:2] in ('#x', '#X'):136 return unichr(int(name[2:], 16))137 elif name.startswith('#'):138 return unichr(int(name[1:]))139 except ValueError:140 pass141 return u''142 return _entity_re.sub(handle_match, unicode(self))143144 def striptags(self):145 r"""Unescape markup into an unicode string and strip all tags. This146 also resolves known HTML4 and XHTML entities. Whitespace is147 normalized to one:148149 >>> Markup("Main &raquo; <em>About</em>").striptags()150 u'Main \xbb About'151 """152 stripped = u' '.join(_striptags_re.sub('', self).split())153 return Markup(stripped).unescape()154155 @classmethod156 def escape(cls, s):157 """Escape the string. Works like :func:`escape` with the difference158 that for subclasses of :class:`Markup` this function would return the159 correct subclass.160 """161 rv = escape(s)162 if rv.__class__ is not cls:163 return cls(rv)164 return rv165166 def make_wrapper(name):167 orig = getattr(unicode, name)168 def func(self, *args, **kwargs):169 args = _escape_argspec(list(args), enumerate(args))170 _escape_argspec(kwargs, kwargs.iteritems())171 return self.__class__(orig(self, *args, **kwargs))172 func.__name__ = orig.__name__173 func.__doc__ = orig.__doc__174 return func175176 for method in '__getitem__', 'capitalize', \177 'title', 'lower', 'upper', 'replace', 'ljust', \178 'rjust', 'lstrip', 'rstrip', 'center', 'strip', \179 'translate', 'expandtabs', 'swapcase', 'zfill':180 locals()[method] = make_wrapper(method)181182 # new in python 2.5183 if hasattr(unicode, 'partition'):184 partition = make_wrapper('partition'),185 rpartition = make_wrapper('rpartition')186187 # new in python 2.6188 if hasattr(unicode, 'format'):189 format = make_wrapper('format')190191 # not in python 3192 if hasattr(unicode, '__getslice__'):193 __getslice__ = make_wrapper('__getslice__')194195 del method, make_wrapper196197198def _escape_argspec(obj, iterable):199 """Helper for various string-wrapped functions."""200 for key, value in iterable:201 if hasattr(value, '__html__') or isinstance(value, basestring):202 obj[key] = escape(value)203 return obj204205206class _MarkupEscapeHelper(object):207 """Helper for Markup.__mod__"""208209 def __init__(self, obj):210 self.obj = obj211212 __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x])213 __str__ = lambda s: str(escape(s.obj))214 __unicode__ = lambda s: unicode(escape(s.obj))215 __repr__ = lambda s: str(escape(repr(s.obj)))216 __int__ = lambda s: int(s.obj)217 __float__ = lambda s: float(s.obj)218219220# we have to import it down here as the speedups and native221# modules imports the markup type which is define above.222try:223 from jinja2._markupsafe._speedups import escape, escape_silent, soft_unicode224except ImportError:225 from jinja2._markupsafe._native import escape, escape_silent, soft_unicode
added:jinja2/_markupsafe/_constants.py+267 added
1# -*- coding: utf-8 -*-2"""3 markupsafe._constants4 ~~~~~~~~~~~~~~~~~~~~~56 Highlevel implementation of the Markup string.78 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""111213HTML_ENTITIES = {14 'AElig': 198,15 'Aacute': 193,16 'Acirc': 194,17 'Agrave': 192,18 'Alpha': 913,19 'Aring': 197,20 'Atilde': 195,21 'Auml': 196,22 'Beta': 914,23 'Ccedil': 199,24 'Chi': 935,25 'Dagger': 8225,26 'Delta': 916,27 'ETH': 208,28 'Eacute': 201,29 'Ecirc': 202,30 'Egrave': 200,31 'Epsilon': 917,32 'Eta': 919,33 'Euml': 203,34 'Gamma': 915,35 'Iacute': 205,36 'Icirc': 206,37 'Igrave': 204,38 'Iota': 921,39 'Iuml': 207,40 'Kappa': 922,41 'Lambda': 923,42 'Mu': 924,43 'Ntilde': 209,44 'Nu': 925,45 'OElig': 338,46 'Oacute': 211,47 'Ocirc': 212,48 'Ograve': 210,49 'Omega': 937,50 'Omicron': 927,51 'Oslash': 216,52 'Otilde': 213,53 'Ouml': 214,54 'Phi': 934,55 'Pi': 928,56 'Prime': 8243,57 'Psi': 936,58 'Rho': 929,59 'Scaron': 352,60 'Sigma': 931,61 'THORN': 222,62 'Tau': 932,63 'Theta': 920,64 'Uacute': 218,65 'Ucirc': 219,66 'Ugrave': 217,67 'Upsilon': 933,68 'Uuml': 220,69 'Xi': 926,70 'Yacute': 221,71 'Yuml': 376,72 'Zeta': 918,73 'aacute': 225,74 'acirc': 226,75 'acute': 180,76 'aelig': 230,77 'agrave': 224,78 'alefsym': 8501,79 'alpha': 945,80 'amp': 38,81 'and': 8743,82 'ang': 8736,83 'apos': 39,84 'aring': 229,85 'asymp': 8776,86 'atilde': 227,87 'auml': 228,88 'bdquo': 8222,89 'beta': 946,90 'brvbar': 166,91 'bull': 8226,92 'cap': 8745,93 'ccedil': 231,94 'cedil': 184,95 'cent': 162,96 'chi': 967,97 'circ': 710,98 'clubs': 9827,99 'cong': 8773,100 'copy': 169,101 'crarr': 8629,102 'cup': 8746,103 'curren': 164,104 'dArr': 8659,105 'dagger': 8224,106 'darr': 8595,107 'deg': 176,108 'delta': 948,109 'diams': 9830,110 'divide': 247,111 'eacute': 233,112 'ecirc': 234,113 'egrave': 232,114 'empty': 8709,115 'emsp': 8195,116 'ensp': 8194,117 'epsilon': 949,118 'equiv': 8801,119 'eta': 951,120 'eth': 240,121 'euml': 235,122 'euro': 8364,123 'exist': 8707,124 'fnof': 402,125 'forall': 8704,126 'frac12': 189,127 'frac14': 188,128 'frac34': 190,129 'frasl': 8260,130 'gamma': 947,131 'ge': 8805,132 'gt': 62,133 'hArr': 8660,134 'harr': 8596,135 'hearts': 9829,136 'hellip': 8230,137 'iacute': 237,138 'icirc': 238,139 'iexcl': 161,140 'igrave': 236,141 'image': 8465,142 'infin': 8734,143 'int': 8747,144 'iota': 953,145 'iquest': 191,146 'isin': 8712,147 'iuml': 239,148 'kappa': 954,149 'lArr': 8656,150 'lambda': 955,151 'lang': 9001,152 'laquo': 171,153 'larr': 8592,154 'lceil': 8968,155 'ldquo': 8220,156 'le': 8804,157 'lfloor': 8970,158 'lowast': 8727,159 'loz': 9674,160 'lrm': 8206,161 'lsaquo': 8249,162 'lsquo': 8216,163 'lt': 60,164 'macr': 175,165 'mdash': 8212,166 'micro': 181,167 'middot': 183,168 'minus': 8722,169 'mu': 956,170 'nabla': 8711,171 'nbsp': 160,172 'ndash': 8211,173 'ne': 8800,174 'ni': 8715,175 'not': 172,176 'notin': 8713,177 'nsub': 8836,178 'ntilde': 241,179 'nu': 957,180 'oacute': 243,181 'ocirc': 244,182 'oelig': 339,183 'ograve': 242,184 'oline': 8254,185 'omega': 969,186 'omicron': 959,187 'oplus': 8853,188 'or': 8744,189 'ordf': 170,190 'ordm': 186,191 'oslash': 248,192 'otilde': 245,193 'otimes': 8855,194 'ouml': 246,195 'para': 182,196 'part': 8706,197 'permil': 8240,198 'perp': 8869,199 'phi': 966,200 'pi': 960,201 'piv': 982,202 'plusmn': 177,203 'pound': 163,204 'prime': 8242,205 'prod': 8719,206 'prop': 8733,207 'psi': 968,208 'quot': 34,209 'rArr': 8658,210 'radic': 8730,211 'rang': 9002,212 'raquo': 187,213 'rarr': 8594,214 'rceil': 8969,215 'rdquo': 8221,216 'real': 8476,217 'reg': 174,218 'rfloor': 8971,219 'rho': 961,220 'rlm': 8207,221 'rsaquo': 8250,222 'rsquo': 8217,223 'sbquo': 8218,224 'scaron': 353,225 'sdot': 8901,226 'sect': 167,227 'shy': 173,228 'sigma': 963,229 'sigmaf': 962,230 'sim': 8764,231 'spades': 9824,232 'sub': 8834,233 'sube': 8838,234 'sum': 8721,235 'sup': 8835,236 'sup1': 185,237 'sup2': 178,238 'sup3': 179,239 'supe': 8839,240 'szlig': 223,241 'tau': 964,242 'there4': 8756,243 'theta': 952,244 'thetasym': 977,245 'thinsp': 8201,246 'thorn': 254,247 'tilde': 732,248 'times': 215,249 'trade': 8482,250 'uArr': 8657,251 'uacute': 250,252 'uarr': 8593,253 'ucirc': 251,254 'ugrave': 249,255 'uml': 168,256 'upsih': 978,257 'upsilon': 965,258 'uuml': 252,259 'weierp': 8472,260 'xi': 958,261 'yacute': 253,262 'yen': 165,263 'yuml': 255,264 'zeta': 950,265 'zwj': 8205,266 'zwnj': 8204267}
added:jinja2/_markupsafe/_native.py+45 added
1# -*- coding: utf-8 -*-2"""3 markupsafe._native4 ~~~~~~~~~~~~~~~~~~56 Native Python implementation the C module is not compiled.78 :copyright: (c) 2010 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja2._markupsafe import Markup121314def escape(s):15 """Convert the characters &, <, >, ' and " in string s to HTML-safe16 sequences. Use this if you need to display text that might contain17 such characters in HTML. Marks return value as markup string.18 """19 if hasattr(s, '__html__'):20 return s.__html__()21 return Markup(unicode(s)22 .replace('&', '&amp;')23 .replace('>', '&gt;')24 .replace('<', '&lt;')25 .replace("'", '&#39;')26 .replace('"', '&#34;')27 )282930def escape_silent(s):31 """Like :func:`escape` but converts `None` into an empty32 markup string.33 """34 if s is None:35 return Markup()36 return escape(s)373839def soft_unicode(s):40 """Make a string unicode if it isn't already. That way a markup41 string is not converted back to unicode.42 """43 if not isinstance(s, unicode):44 s = unicode(s)45 return s
added:jinja2/_markupsafe/tests.py+80 added
1import gc2import unittest3from jinja2._markupsafe import Markup, escape, escape_silent456class MarkupTestCase(unittest.TestCase):78 def test_markup_operations(self):9 # adding two strings should escape the unsafe one10 unsafe = '<script type="application/x-some-script">alert("foo");</script>'11 safe = Markup('<em>username</em>')12 assert unsafe + safe == unicode(escape(unsafe)) + unicode(safe)1314 # string interpolations are safe to use too15 assert Markup('<em>%s</em>') % '<bad user>' == \16 '<em>&lt;bad user&gt;</em>'17 assert Markup('<em>%(username)s</em>') % {18 'username': '<bad user>'19 } == '<em>&lt;bad user&gt;</em>'2021 # an escaped object is markup too22 assert type(Markup('foo') + 'bar') is Markup2324 # and it implements __html__ by returning itself25 x = Markup("foo")26 assert x.__html__() is x2728 # it also knows how to treat __html__ objects29 class Foo(object):30 def __html__(self):31 return '<em>awesome</em>'32 def __unicode__(self):33 return 'awesome'34 assert Markup(Foo()) == '<em>awesome</em>'35 assert Markup('<strong>%s</strong>') % Foo() == \36 '<strong><em>awesome</em></strong>'3738 # escaping and unescaping39 assert escape('"<>&\'') == '&#34;&lt;&gt;&amp;&#39;'40 assert Markup("<em>Foo &amp; Bar</em>").striptags() == "Foo & Bar"41 assert Markup("&lt;test&gt;").unescape() == "<test>"4243 def test_all_set(self):44 import jinja2._markupsafe as markup45 for item in markup.__all__:46 getattr(markup, item)4748 def test_escape_silent(self):49 assert escape_silent(None) == Markup()50 assert escape(None) == Markup(None)51 assert escape_silent('<foo>') == Markup(u'&lt;foo&gt;')525354class MarkupLeakTestCase(unittest.TestCase):5556 def test_markup_leaks(self):57 counts = set()58 for count in xrange(20):59 for item in xrange(1000):60 escape("foo")61 escape("<foo>")62 escape(u"foo")63 escape(u"<foo>")64 counts.add(len(gc.get_objects()))65 assert len(counts) == 1, 'ouch, c extension seems to leak objects'666768def suite():69 suite = unittest.TestSuite()70 suite.addTest(unittest.makeSuite(MarkupTestCase))7172 # this test only tests the c extension73 if not hasattr(escape, 'func_code'):74 suite.addTest(unittest.makeSuite(MarkupLeakTestCase))7576 return suite777879if __name__ == '__main__':80 unittest.main(defaultTest='suite')