Skip to content
Myr

MarkupSafe is now used for the Jinja2 speedups

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 fd72972 · Browse files · 4 files+58 added−492 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+58 added−492 removed

  • other:+58 added−492 removed

4 files+58 added−492 removed

added:jinja2/_markupsafe/_bundle.py+49 added
1# -*- coding: utf-8 -*-2"""3 jinja2._markupsafe._bundle4 ~~~~~~~~~~~~~~~~~~~~~~~~~~56 This script pulls in markupsafe from a source folder and7 bundles it with Jinja2. It does not pull in the speedups8 module though.910 :copyright: Copyright 2010 by the Jinja team, see AUTHORS.11 :license: BSD, see LICENSE for details.12"""13import sys14import os15import re161718def rewrite_imports(lines):19 for idx, line in enumerate(lines):20 new_line = re.sub(r'(import|from)\s+markupsafe\b',21 r'\1 jinja2._markupsafe', line)22 if new_line != line:23 lines[idx] = new_line242526def main():27 if len(sys.argv) != 2:28 print 'error: only argument is path to markupsafe'29 sys.exit(1)30 basedir = os.path.dirname(__file__)31 markupdir = sys.argv[1]32 for filename in os.listdir(markupdir):33 if filename.endswith('.py'):34 f = open(os.path.join(markupdir, filename))35 try:36 lines = list(f)37 finally:38 f.close()39 rewrite_imports(lines)40 f = open(os.path.join(basedir, filename), 'w')41 try:42 for line in lines:43 f.write(line)44 finally:45 f.close()464748if __name__ == '__main__':49 main()
modified:jinja2/constants.py-258 removed
28 unmodified lines
29sociis sociosqu sodales sollicitudin suscipit suspendisse taciti tellus tempor30tempus tincidunt torquent tortor tristique turpis ullamcorper ultrices31ultricies urna ut varius vehicula vel velit venenatis vestibulum vitae vivamus32viverra volutpat vulputate'''333435#: a dict of all html entities + apos36HTML_ENTITIES = {37 'AElig': 198,38 'Aacute': 193,39 'Acirc': 194,40 'Agrave': 192,41 'Alpha': 913,42 'Aring': 197,43 'Atilde': 195,44 'Auml': 196,45 'Beta': 914,46 'Ccedil': 199,47 'Chi': 935,48 'Dagger': 8225,49 'Delta': 916,50 'ETH': 208,51 'Eacute': 201,52 'Ecirc': 202,53 'Egrave': 200,54 'Epsilon': 917,55 'Eta': 919,56 'Euml': 203,57 'Gamma': 915,58 'Iacute': 205,59 'Icirc': 206,60 'Igrave': 204,61 'Iota': 921,62 'Iuml': 207,63 'Kappa': 922,64 'Lambda': 923,65 'Mu': 924,66 'Ntilde': 209,67 'Nu': 925,68 'OElig': 338,69 'Oacute': 211,70 'Ocirc': 212,71 'Ograve': 210,72 'Omega': 937,73 'Omicron': 927,74 'Oslash': 216,75 'Otilde': 213,76 'Ouml': 214,77 'Phi': 934,78 'Pi': 928,79 'Prime': 8243,80 'Psi': 936,81 'Rho': 929,82 'Scaron': 352,83 'Sigma': 931,84 'THORN': 222,85 'Tau': 932,86 'Theta': 920,87 'Uacute': 218,88 'Ucirc': 219,89 'Ugrave': 217,90 'Upsilon': 933,91 'Uuml': 220,92 'Xi': 926,93 'Yacute': 221,94 'Yuml': 376,95 'Zeta': 918,96 'aacute': 225,97 'acirc': 226,98 'acute': 180,99 'aelig': 230,100 'agrave': 224,101 'alefsym': 8501,102 'alpha': 945,103 'amp': 38,104 'and': 8743,105 'ang': 8736,106 'apos': 39,107 'aring': 229,108 'asymp': 8776,109 'atilde': 227,110 'auml': 228,111 'bdquo': 8222,112 'beta': 946,113 'brvbar': 166,114 'bull': 8226,115 'cap': 8745,116 'ccedil': 231,117 'cedil': 184,118 'cent': 162,119 'chi': 967,120 'circ': 710,121 'clubs': 9827,122 'cong': 8773,123 'copy': 169,124 'crarr': 8629,125 'cup': 8746,126 'curren': 164,127 'dArr': 8659,128 'dagger': 8224,129 'darr': 8595,130 'deg': 176,131 'delta': 948,132 'diams': 9830,133 'divide': 247,134 'eacute': 233,135 'ecirc': 234,136 'egrave': 232,137 'empty': 8709,138 'emsp': 8195,139 'ensp': 8194,140 'epsilon': 949,141 'equiv': 8801,142 'eta': 951,143 'eth': 240,144 'euml': 235,145 'euro': 8364,146 'exist': 8707,147 'fnof': 402,148 'forall': 8704,149 'frac12': 189,150 'frac14': 188,151 'frac34': 190,152 'frasl': 8260,153 'gamma': 947,154 'ge': 8805,155 'gt': 62,156 'hArr': 8660,157 'harr': 8596,158 'hearts': 9829,159 'hellip': 8230,160 'iacute': 237,161 'icirc': 238,162 'iexcl': 161,163 'igrave': 236,164 'image': 8465,165 'infin': 8734,166 'int': 8747,167 'iota': 953,168 'iquest': 191,169 'isin': 8712,170 'iuml': 239,171 'kappa': 954,172 'lArr': 8656,173 'lambda': 955,174 'lang': 9001,175 'laquo': 171,176 'larr': 8592,177 'lceil': 8968,178 'ldquo': 8220,179 'le': 8804,180 'lfloor': 8970,181 'lowast': 8727,182 'loz': 9674,183 'lrm': 8206,184 'lsaquo': 8249,185 'lsquo': 8216,186 'lt': 60,187 'macr': 175,188 'mdash': 8212,189 'micro': 181,190 'middot': 183,191 'minus': 8722,192 'mu': 956,193 'nabla': 8711,194 'nbsp': 160,195 'ndash': 8211,196 'ne': 8800,197 'ni': 8715,198 'not': 172,199 'notin': 8713,200 'nsub': 8836,201 'ntilde': 241,202 'nu': 957,203 'oacute': 243,204 'ocirc': 244,205 'oelig': 339,206 'ograve': 242,207 'oline': 8254,208 'omega': 969,209 'omicron': 959,210 'oplus': 8853,211 'or': 8744,212 'ordf': 170,213 'ordm': 186,214 'oslash': 248,215 'otilde': 245,216 'otimes': 8855,217 'ouml': 246,218 'para': 182,219 'part': 8706,220 'permil': 8240,221 'perp': 8869,222 'phi': 966,223 'pi': 960,224 'piv': 982,225 'plusmn': 177,226 'pound': 163,227 'prime': 8242,228 'prod': 8719,229 'prop': 8733,230 'psi': 968,231 'quot': 34,232 'rArr': 8658,233 'radic': 8730,234 'rang': 9002,235 'raquo': 187,236 'rarr': 8594,237 'rceil': 8969,238 'rdquo': 8221,239 'real': 8476,240 'reg': 174,241 'rfloor': 8971,242 'rho': 961,243 'rlm': 8207,244 'rsaquo': 8250,245 'rsquo': 8217,246 'sbquo': 8218,247 'scaron': 353,248 'sdot': 8901,249 'sect': 167,250 'shy': 173,251 'sigma': 963,252 'sigmaf': 962,253 'sim': 8764,254 'spades': 9824,255 'sub': 8834,256 'sube': 8838,257 'sum': 8721,258 'sup': 8835,259 'sup1': 185,260 'sup2': 178,261 'sup3': 179,262 'supe': 8839,263 'szlig': 223,264 'tau': 964,265 'there4': 8756,266 'theta': 952,267 'thetasym': 977,268 'thinsp': 8201,269 'thorn': 254,270 'tilde': 732,271 'times': 215,272 'trade': 8482,273 'uArr': 8657,274 'uacute': 250,275 'uarr': 8593,276 'ucirc': 251,277 'ugrave': 249,278 'uml': 168,279 'upsih': 978,280 'upsilon': 965,281 'uuml': 252,282 'weierp': 8472,283 'xi': 958,284 'yacute': 253,285 'yen': 165,286 'yuml': 255,287 'zeta': 950,288 'zwj': 8205,289 'zwnj': 8204290}
modified:jinja2/utils.py+6 added-224 removed
347 unmodified lines
348 return u'\n\n'.join(result)349 return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))350351352class Markup(unicode):353 r"""Marks a string as being safe for inclusion in HTML/XML output without354 needing to be escaped. This implements the `__html__` interface a couple355 of frameworks and web applications use. :class:`Markup` is a direct356 subclass of `unicode` and provides all the methods of `unicode` just that357 it escapes arguments passed and always returns `Markup`.358359 The `escape` function returns markup objects so that double escaping can't360 happen. If you want to use autoescaping in Jinja just enable the361 autoescaping feature in the environment.362363 The constructor of the :class:`Markup` class can be used for three364 different things: When passed an unicode object it's assumed to be safe,365 when passed an object with an HTML representation (has an `__html__`366 method) that representation is used, otherwise the object passed is367 converted into a unicode string and then assumed to be safe:368369 >>> Markup("Hello <em>World</em>!")370 Markup(u'Hello <em>World</em>!')371 >>> class Foo(object):372 ... def __html__(self):373 ... return '<a href="#">foo</a>'374 ... 375 >>> Markup(Foo())376 Markup(u'<a href="#">foo</a>')377378 If you want object passed being always treated as unsafe you can use the379 :meth:`escape` classmethod to create a :class:`Markup` object:380381 >>> Markup.escape("Hello <em>World</em>!")382 Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')383384 Operations on a markup string are markup aware which means that all385 arguments are passed through the :func:`escape` function:386387 >>> em = Markup("<em>%s</em>")388 >>> em % "foo & bar"389 Markup(u'<em>foo &amp; bar</em>')390 >>> strong = Markup("<strong>%(text)s</strong>")391 >>> strong % {'text': '<blink>hacker here</blink>'}392 Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')393 >>> Markup("<em>Hello</em> ") + "<foo>"394 Markup(u'<em>Hello</em> &lt;foo&gt;')395 """396 __slots__ = ()397398 def __new__(cls, base=u'', encoding=None, errors='strict'):399 if hasattr(base, '__html__'):400 base = base.__html__()401 if encoding is None:402 return unicode.__new__(cls, base)403 return unicode.__new__(cls, base, encoding, errors)404405 def __html__(self):406 return self407408 def __add__(self, other):409 if hasattr(other, '__html__') or isinstance(other, basestring):410 return self.__class__(unicode(self) + unicode(escape(other)))411 return NotImplemented412413 def __radd__(self, other):414 if hasattr(other, '__html__') or isinstance(other, basestring):415 return self.__class__(unicode(escape(other)) + unicode(self))416 return NotImplemented417418 def __mul__(self, num):419 if isinstance(num, (int, long)):420 return self.__class__(unicode.__mul__(self, num))421 return NotImplemented422 __rmul__ = __mul__423424 def __mod__(self, arg):425 if isinstance(arg, tuple):426 arg = tuple(imap(_MarkupEscapeHelper, arg))427 else:428 arg = _MarkupEscapeHelper(arg)429 return self.__class__(unicode.__mod__(self, arg))430431 def __repr__(self):432 return '%s(%s)' % (433 self.__class__.__name__,434 unicode.__repr__(self)435 )436437 def join(self, seq):438 return self.__class__(unicode.join(self, imap(escape, seq)))439 join.__doc__ = unicode.join.__doc__440441 def split(self, *args, **kwargs):442 return map(self.__class__, unicode.split(self, *args, **kwargs))443 split.__doc__ = unicode.split.__doc__444445 def rsplit(self, *args, **kwargs):446 return map(self.__class__, unicode.rsplit(self, *args, **kwargs))447 rsplit.__doc__ = unicode.rsplit.__doc__448449 def splitlines(self, *args, **kwargs):450 return map(self.__class__, unicode.splitlines(self, *args, **kwargs))451 splitlines.__doc__ = unicode.splitlines.__doc__452453 def unescape(self):454 r"""Unescape markup again into an unicode string. This also resolves455 known HTML4 and XHTML entities:456457 >>> Markup("Main &raquo; <em>About</em>").unescape()458 u'Main \xbb <em>About</em>'459 """460 from jinja2.constants import HTML_ENTITIES461 def handle_match(m):462 name = m.group(1)463 if name in HTML_ENTITIES:464 return unichr(HTML_ENTITIES[name])465 try:466 if name[:2] in ('#x', '#X'):467 return unichr(int(name[2:], 16))468 elif name.startswith('#'):469 return unichr(int(name[1:]))470 except ValueError:471 pass472 return u''473 return _entity_re.sub(handle_match, unicode(self))474475 def striptags(self):476 r"""Unescape markup into an unicode string and strip all tags. This477 also resolves known HTML4 and XHTML entities. Whitespace is478 normalized to one:479480 >>> Markup("Main &raquo; <em>About</em>").striptags()481 u'Main \xbb About'482 """483 stripped = u' '.join(_striptags_re.sub('', self).split())484 return Markup(stripped).unescape()485486 @classmethod487 def escape(cls, s):488 """Escape the string. Works like :func:`escape` with the difference489 that for subclasses of :class:`Markup` this function would return the490 correct subclass.491 """492 rv = escape(s)493 if rv.__class__ is not cls:494 return cls(rv)495 return rv496497 def make_wrapper(name):498 orig = getattr(unicode, name)499 def func(self, *args, **kwargs):500 args = _escape_argspec(list(args), enumerate(args))501 _escape_argspec(kwargs, kwargs.iteritems())502 return self.__class__(orig(self, *args, **kwargs))503 func.__name__ = orig.__name__504 func.__doc__ = orig.__doc__505 return func506507 for method in '__getitem__', 'capitalize', \508 'title', 'lower', 'upper', 'replace', 'ljust', \509 'rjust', 'lstrip', 'rstrip', 'center', 'strip', \510 'translate', 'expandtabs', 'swapcase', 'zfill':511 locals()[method] = make_wrapper(method)512513 # new in python 2.5514 if hasattr(unicode, 'partition'):515 partition = make_wrapper('partition'),516 rpartition = make_wrapper('rpartition')517518 # new in python 2.6519 if hasattr(unicode, 'format'):520 format = make_wrapper('format')521522 # not in python 3523 if hasattr(unicode, '__getslice__'):524 __getslice__ = make_wrapper('__getslice__')525526 del method, make_wrapper527528529def _escape_argspec(obj, iterable):530 """Helper for various string-wrapped functions."""531 for key, value in iterable:532 if hasattr(value, '__html__') or isinstance(value, basestring):533 obj[key] = escape(value)534 return obj535536537class _MarkupEscapeHelper(object):538 """Helper for Markup.__mod__"""539540 def __init__(self, obj):541 self.obj = obj542543 __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x])544 __str__ = lambda s: str(escape(s.obj))545 __unicode__ = lambda s: unicode(escape(s.obj))546 __repr__ = lambda s: str(escape(repr(s.obj)))547 __int__ = lambda s: int(s.obj)548 __float__ = lambda s: float(s.obj)549550352class LRUCache(object):353 """A simple LRU Cache implementation."""354355 # this is fast for small capacities (something below 1000) but doesn't
220 unmodified lines
576 return u''577 return self.sep578579779# we have to import it down here as the speedups module imports the780# markup type which is define above.580# try markupsafe first, if that fails go with Jinja2's bundled version581# of markupsafe. Markupsafe was previously Jinja2's implementation of582# the Markup object but was moved into a separate package in a patchleve583# release584try:782 from jinja2._speedups import escape, soft_unicode585 from markupsafe import Markup, escape, soft_unicode586except ImportError:784 def escape(s):785 """Convert the characters &, <, >, ' and " in string s to HTML-safe786 sequences. Use this if you need to display text that might contain787 such characters in HTML. Marks return value as markup string.788 """789 if hasattr(s, '__html__'):790 return s.__html__()791 return Markup(unicode(s)792 .replace('&', '&amp;')793 .replace('>', '&gt;')794 .replace('<', '&lt;')795 .replace("'", '&#39;')796 .replace('"', '&#34;')797 )587 from jinja2._markupsafe import Markup, escape, soft_unicode588799 def soft_unicode(s):800 """Make a string unicode if it isn't already. That way a markup801 string is not converted back to unicode.802 """803 if not isinstance(s, unicode):804 s = unicode(s)805 return s589807590# partials591try:592 from functools import partial593except ImportError:
8 unmodified lines
modified:setup.py+3 added-10 removed
40 unmodified lines
41"""42import os43import sys4445from setuptools import setup, Extension, Feature45from setuptools import setup4647# tell distribute to use 2to3 with our own fixers.48extra = {}49if sys.version_info >= (3, 0):
26 unmodified lines
76 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',77 'Topic :: Software Development :: Libraries :: Python Modules',78 'Topic :: Text Processing :: Markup :: HTML'79 ],80 packages=['jinja2', 'jinja2.testsuite', 'jinja2.testsuite.res'],81 features={82 'speedups': Feature("optional C speed-enhancements",83 standard=False,84 ext_modules=[85 Extension('jinja2._speedups', ['jinja2/_speedups.c'])86 ]87 )88 },80 packages=['jinja2', 'jinja2.testsuite', 'jinja2.testsuite.res',81 'jinja2._markupsafe'],82 extras_require={'i18n': ['Babel>=0.8']},83 test_suite='jinja2.testsuite.suite',84 include_package_data=True,85 entry_points="""
5 unmodified lines