Skip to content
Myr

utils.py

This file

Path

jinja2/utils.py

763 lines · 23.9 KiB · Python

Last changed by

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

History of this file

Take it

The walk stopped after 200 commits: lines older than c072564 point at it.

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 1–7why, one step back
1# -*- coding: utf-8 -*-
2"""3 jinja2.utils4 ~~~~~~~~~~~~56 Utility functions.7

Copyright switch to "The Jinja Team".Armin Ronacherbefore adoption62ccd1b

line 8why, one step back
8 :copyright: (c) 2009 by the Jinja Team.

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 9–12why, one step back
9 :license: BSD, see LICENSE for more details.
10"""11import re12import sys

Various cleanups and added custom cycler.Armin Ronacherbefore adoptionccae055

line 13why, one step back
13import errno

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 14–31why, one step back
14try:
15 from thread import allocate_lock16except ImportError:17 from dummy_thread import allocate_lock18from collections import deque19from itertools import imap202122_word_split_re = re.compile(r'(\s+)')23_punctuation_re = re.compile(24 '^(?P<lead>(?:%s)*)(?P<middle>.*?)(?P<trail>(?:%s)*)$' % (25 '|'.join(imap(re.escape, ('(', '<', '&lt;'))),26 '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '&gt;')))27 )28)29_simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')30_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')31_entity_re = re.compile(r'&([^;]+);')

Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d

lines 32–33why, one step back
32_letters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'
33_digits = '0123456789'

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 34–37why, one step back
34
35# special singleton representing missing values for the runtime36missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()37

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

lines 38–39why, one step back
38# internal code
39internal_code = set()

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

line 40why, one step back
40

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

line 41why, one step back
41

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 42–65why, one step back
42# concatenate a list of strings and convert them to unicode.
43# unfortunately there is a bug in python 2.4 and lower that causes44# unicode.join trash the traceback.45_concat = u''.join46try:47 def _test_gen_bug():48 raise TypeError(_test_gen_bug)49 yield None50 _concat(_test_gen_bug())51except TypeError, _error:52 if not _error.args or _error.args[0] is not _test_gen_bug:53 def concat(gen):54 try:55 return _concat(list(gen))56 except:57 # this hack is needed so that the current frame58 # does not show up in the traceback.59 exc_type, exc_value, tb = sys.exc_info()60 raise exc_type, exc_value, tb.tb_next61 else:62 concat = _concat63 del _test_gen_bug, _error6465

Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d

lines 66–99why, one step back
66# ironpython without stdlib doesn't have keyword
67try:68 from keyword import iskeyword as is_python_keyword69except ImportError:70 _py_identifier_re = re.compile(r'^[a-zA-Z_][a-zA-Z0-9]*$')71 def is_python_keyword(name):72 if _py_identifier_re.search(name) is None:73 return False74 try:75 exec name + " = 42"76 except SyntaxError:77 return False78 return True798081# common types. These do exist in the special types module too which however82# does not exist in IronPython out of the box.83class _C(object):84 def method(self): pass85def _func():86 yield None87FunctionType = type(_func)88GeneratorType = type(_func())89MethodType = type(_C.method)90CodeType = type(_C.method.func_code)91try:92 raise TypeError()93except TypeError:94 _tb = sys.exc_info()[2]95 TracebackType = type(_tb)96 FrameType = type(_tb.tb_frame)97del _C, _tb, _func9899

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

line 100why, one step back
100def contextfunction(f):

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 101–107why, one step back
101 """This decorator can be used to mark a function or method context callable.
102 A context callable is passed the active :class:`Context` as first argument when103 called from the template. This is useful if a function wants to get access104 to the context or functions provided on the context object. For example105 a function that returns a sorted list of template variables the current106 template exports could look like this::107

data files are optional nowArmin Ronacherbefore adoption58f351d

line 108why, one step back
108 @contextfunction

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 109–110why, one step back
109 def get_exported_names(context):
110 return sorted(context.exported_vars)

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 111–116why, one step back
111 """
112 f.contextfunction = True113 return f114115116def environmentfunction(f):

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 117–120why, one step back
117 """This decorator can be used to mark a function or method as environment
118 callable. This decorator works exactly like the :func:`contextfunction`119 decorator just that the first argument is the active :class:`Environment`120 and not context.

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 121–122why, one step back
121 """
122 f.environmentfunction = True

Improved Jinja's debugging support by introducing "@internalcode" which marks code objects that are skipped on tracebacks. Also template errors are now translated as well to help the pylons debugger.Armin Ronacherbefore adoptiond416a97

lines 123–128why, one step back
123 return f
124125126def internalcode(f):127 """Marks the function as internally used"""128 internal_code.add(f.func_code)

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 129–131why, one step back
129 return f
130131

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 132–147why, one step back
132def is_undefined(obj):
133 """Check if the object passed is undefined. This does nothing more than134 performing an instance check against :class:`Undefined` but looks nicer.135 This can be used for custom filters or tests that want to react to136 undefined variables. For example a custom default filter can look like137 this::138139 def default(var, default=''):140 if is_undefined(var):141 return default142 return var143 """144 from jinja2.runtime import Undefined145 return isinstance(obj, Undefined)146147

Added support for `Environment.compile_expression`.Armin Ronacherbefore adoptionba6e25a

lines 148–153why, one step back
148def consume(iterable):
149 """Consumes an iterable without doing anything with it."""150 for event in iterable:151 pass152153

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 154–191why, one step back
154def clear_caches():
155 """Jinja2 keeps internal caches for environments and lexers. These are156 used so that Jinja2 doesn't have to recreate environments and lexers all157 the time. Normally you don't have to care about that but if you are158 messuring memory consumption you may want to clean the caches.159 """160 from jinja2.environment import _spontaneous_environments161 from jinja2.lexer import _lexer_cache162 _spontaneous_environments.clear()163 _lexer_cache.clear()164165166def import_string(import_name, silent=False):167 """Imports an object based on a string. This use useful if you want to168 use import paths as endpoints or something similar. An import path can169 be specified either in dotted notation (``xml.sax.saxutils.escape``)170 or with a colon as object delimiter (``xml.sax.saxutils:escape``).171172 If the `silent` is True the return value will be `None` if the import173 fails.174175 :return: imported object176 """177 try:178 if ':' in import_name:179 module, obj = import_name.split(':', 1)180 elif '.' in import_name:181 items = import_name.split('.')182 module = '.'.join(items[:-1])183 obj = items[-1]184 else:185 return __import__(import_name)186 return getattr(__import__(module, None, None, [obj]), obj)187 except (ImportError, AttributeError):188 if not silent:189 raise190191

Various cleanups and added custom cycler.Armin Ronacherbefore adoptionccae055

lines 192–202why, one step back
192def open_if_exists(filename, mode='r'):
193 """Returns a file descriptor for the filename if that file exists,194 otherwise `None`.195 """196 try:197 return file(filename, mode)198 except IOError, e:199 if e.errno not in (errno.ENOENT, errno.EISDIR):200 raise201202

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 203–229why, one step back
203def pformat(obj, verbose=False):
204 """Prettyprint an object. Either use the `pretty` library or the205 builtin `pprint`.206 """207 try:208 from pretty import pretty209 return pretty(obj, verbose=verbose)210 except ImportError:211 from pprint import pformat212 return pformat(obj)213214215def urlize(text, trim_url_limit=None, nofollow=False):216 """Converts any URLs in text into clickable links. Works on http://,217 https:// and www. links. Links can have trailing punctuation (periods,218 commas, close-parens) and leading punctuation (opening parens) and219 it'll still do the right thing.220221 If trim_url_limit is not None, the URLs in link text will be limited222 to trim_url_limit characters.223224 If nofollow is True, the URLs in link text will get a rel="nofollow"225 attribute.226 """227 trim_url = lambda x, limit=trim_url_limit: limit is not None \228 and (x[:limit] + (len(x) >=limit and '...'229 or '')) or x

Fixed an escaping bug in urlizeArmin Ronacherbefore adoptiond9342dc

line 230why, one step back
230 words = _word_split_re.split(unicode(escape(text)))

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 231–239why, one step back
231 nofollow_attr = nofollow and ' rel="nofollow"' or ''
232 for i, word in enumerate(words):233 match = _punctuation_re.match(word)234 if match:235 lead, middle, trail = match.groups()236 if middle.startswith('www.') or (237 '@' not in middle and238 not middle.startswith('http://') and239 len(middle) > 0 and

Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d

line 240why, one step back
240 middle[0] in _letters + _digits and (

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 241–308why, one step back
241 middle.endswith('.org') or
242 middle.endswith('.net') or243 middle.endswith('.com')244 )):245 middle = '<a href="http://%s"%s>%s</a>' % (middle,246 nofollow_attr, trim_url(middle))247 if middle.startswith('http://') or \248 middle.startswith('https://'):249 middle = '<a href="%s"%s>%s</a>' % (middle,250 nofollow_attr, trim_url(middle))251 if '@' in middle and not middle.startswith('www.') and \252 not ':' in middle and _simple_email_re.match(middle):253 middle = '<a href="mailto:%s">%s</a>' % (middle, middle)254 if lead + middle + trail != word:255 words[i] = lead + middle + trail256 return u''.join(words)257258259def generate_lorem_ipsum(n=5, html=True, min=20, max=100):260 """Generate some lorem impsum for the template."""261 from jinja2.constants import LOREM_IPSUM_WORDS262 from random import choice, random, randrange263 words = LOREM_IPSUM_WORDS.split()264 result = []265266 for _ in xrange(n):267 next_capitalized = True268 last_comma = last_fullstop = 0269 word = None270 last = None271 p = []272273 # each paragraph contains out of 20 to 100 words.274 for idx, _ in enumerate(xrange(randrange(min, max))):275 while True:276 word = choice(words)277 if word != last:278 last = word279 break280 if next_capitalized:281 word = word.capitalize()282 next_capitalized = False283 # add commas284 if idx - randrange(3, 8) > last_comma:285 last_comma = idx286 last_fullstop += 2287 word += ','288 # add end of sentences289 if idx - randrange(10, 20) > last_fullstop:290 last_comma = last_fullstop = idx291 word += '.'292 next_capitalized = True293 p.append(word)294295 # ensure that the paragraph ends with a dot.296 p = u' '.join(p)297 if p.endswith(','):298 p = p[:-1] + '.'299 elif not p.endswith('.'):300 p += '.'301 result.append(p)302303 if not html:304 return u'\n\n'.join(result)305 return Markup(u'\n'.join(u'<p>%s</p>' % escape(x) for x in result))306307308class Markup(unicode):

data files are optional nowArmin Ronacherbefore adoption58f351d

line 309why, one step back
309 r"""Marks a string as being safe for inclusion in HTML/XML output without

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

line 310why, one step back
310 needing to be escaped. This implements the `__html__` interface a couple

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 311–313why, one step back
311 of frameworks and web applications use. :class:`Markup` is a direct
312 subclass of `unicode` and provides all the methods of `unicode` just that313 it escapes arguments passed and always returns `Markup`.

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 314–315why, one step back
314
315 The `escape` function returns markup objects so that double escaping can't

Fixed a documentation bug.Armin Ronacherbefore adoption88e1cb7

lines 316–317why, one step back
316 happen. If you want to use autoescaping in Jinja just enable the
317 autoescaping feature in the environment.

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 318–350why, one step back
318
319 The constructor of the :class:`Markup` class can be used for three320 different things: When passed an unicode object it's assumed to be safe,321 when passed an object with an HTML representation (has an `__html__`322 method) that representation is used, otherwise the object passed is323 converted into a unicode string and then assumed to be safe:324325 >>> Markup("Hello <em>World</em>!")326 Markup(u'Hello <em>World</em>!')327 >>> class Foo(object):328 ... def __html__(self):329 ... return '<a href="#">foo</a>'330 ... 331 >>> Markup(Foo())332 Markup(u'<a href="#">foo</a>')333334 If you want object passed being always treated as unsafe you can use the335 :meth:`escape` classmethod to create a :class:`Markup` object:336337 >>> Markup.escape("Hello <em>World</em>!")338 Markup(u'Hello &lt;em&gt;World&lt;/em&gt;!')339340 Operations on a markup string are markup aware which means that all341 arguments are passed through the :func:`escape` function:342343 >>> em = Markup("<em>%s</em>")344 >>> em % "foo & bar"345 Markup(u'<em>foo &amp; bar</em>')346 >>> strong = Markup("<strong>%(text)s</strong>")347 >>> strong % {'text': '<blink>hacker here</blink>'}348 Markup(u'<strong>&lt;blink&gt;hacker here&lt;/blink&gt;</strong>')349 >>> Markup("<em>Hello</em> ") + "<foo>"350 Markup(u'<em>Hello</em> &lt;foo&gt;')

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 351–353why, one step back
351 """
352 __slots__ = ()353

updated documentationArmin Ronacherbefore adoption3ef2043

line 354why, one step back
354 def __new__(cls, base=u'', encoding=None, errors='strict'):

added unittest for Markup and let the markup constructor accept `__html__` objectsArmin Ronacherbefore adoption4e6f9a2

lines 355–356why, one step back
355 if hasattr(base, '__html__'):
356 base = base.__html__()

updated documentationArmin Ronacherbefore adoption3ef2043

lines 357–359why, one step back
357 if encoding is None:
358 return unicode.__new__(cls, base)359 return unicode.__new__(cls, base, encoding, errors)

added unittest for Markup and let the markup constructor accept `__html__` objectsArmin Ronacherbefore adoption4e6f9a2

line 360why, one step back
360

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 361–374why, one step back
361 def __html__(self):
362 return self363364 def __add__(self, other):365 if hasattr(other, '__html__') or isinstance(other, basestring):366 return self.__class__(unicode(self) + unicode(escape(other)))367 return NotImplemented368369 def __radd__(self, other):370 if hasattr(other, '__html__') or isinstance(other, basestring):371 return self.__class__(unicode(escape(other)) + unicode(self))372 return NotImplemented373374 def __mul__(self, num):

improved sandbox and updated setup.pyArmin Ronacherbefore adoptiond71fff0

lines 375–377why, one step back
375 if isinstance(num, (int, long)):
376 return self.__class__(unicode.__mul__(self, num))377 return NotImplemented

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 378–409why, one step back
378 __rmul__ = __mul__
379380 def __mod__(self, arg):381 if isinstance(arg, tuple):382 arg = tuple(imap(_MarkupEscapeHelper, arg))383 else:384 arg = _MarkupEscapeHelper(arg)385 return self.__class__(unicode.__mod__(self, arg))386387 def __repr__(self):388 return '%s(%s)' % (389 self.__class__.__name__,390 unicode.__repr__(self)391 )392393 def join(self, seq):394 return self.__class__(unicode.join(self, imap(escape, seq)))395 join.__doc__ = unicode.join.__doc__396397 def split(self, *args, **kwargs):398 return map(self.__class__, unicode.split(self, *args, **kwargs))399 split.__doc__ = unicode.split.__doc__400401 def rsplit(self, *args, **kwargs):402 return map(self.__class__, unicode.rsplit(self, *args, **kwargs))403 rsplit.__doc__ = unicode.rsplit.__doc__404405 def splitlines(self, *args, **kwargs):406 return map(self.__class__, unicode.splitlines(self, *args, **kwargs))407 splitlines.__doc__ = unicode.splitlines.__doc__408409 def unescape(self):

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 410–415why, one step back
410 r"""Unescape markup again into an unicode string. This also resolves
411 known HTML4 and XHTML entities:412413 >>> Markup("Main &raquo; <em>About</em>").unescape()414 u'Main \xbb <em>About</em>'415 """

Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d

line 416why, one step back
416 from jinja2.constants import HTML_ENTITIES

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 417–418why, one step back
417 def handle_match(m):
418 name = m.group(1)

Removed a few stdlib dependencies. This is the first step for IronPython support, the second one being a new lexer.Armin Ronacherbefore adoption9a0078d

lines 419–420why, one step back
419 if name in HTML_ENTITIES:
420 return unichr(HTML_ENTITIES[name])

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 421–431why, one step back
421 try:
422 if name[:2] in ('#x', '#X'):423 return unichr(int(name[2:], 16))424 elif name.startswith('#'):425 return unichr(int(name[1:]))426 except ValueError:427 pass428 return u''429 return _entity_re.sub(handle_match, unicode(self))430431 def striptags(self):

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 432–438why, one step back
432 r"""Unescape markup into an unicode string and strip all tags. This
433 also resolves known HTML4 and XHTML entities. Whitespace is434 normalized to one:435436 >>> Markup("Main &raquo; <em>About</em>").striptags()437 u'Main \xbb About'438 """

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 439–441why, one step back
439 stripped = u' '.join(_striptags_re.sub('', self).split())
440 return Markup(stripped).unescape()441

some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)Armin Ronacherbefore adoptionf35e281

lines 442–443why, one step back
442 @classmethod
443 def escape(cls, s):

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 444–447why, one step back
444 """Escape the string. Works like :func:`escape` with the difference
445 that for subclasses of :class:`Markup` this function would return the446 correct subclass.447 """

some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)Armin Ronacherbefore adoptionf35e281

lines 448–452why, one step back
448 rv = escape(s)
449 if rv.__class__ is not cls:450 return cls(rv)451 return rv452

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 453–455why, one step back
453 def make_wrapper(name):
454 orig = getattr(unicode, name)455 def func(self, *args, **kwargs):

improved sandbox and updated setup.pyArmin Ronacherbefore adoptiond71fff0

lines 456–457why, one step back
456 args = _escape_argspec(list(args), enumerate(args))
457 _escape_argspec(kwargs, kwargs.iteritems())

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 458–461why, one step back
458 return self.__class__(orig(self, *args, **kwargs))
459 func.__name__ = orig.__name__460 func.__doc__ = orig.__doc__461 return func

improved sandbox and updated setup.pyArmin Ronacherbefore adoptiond71fff0

line 462why, one step back
462

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 463–470why, one step back
463 for method in '__getitem__', '__getslice__', 'capitalize', \
464 'title', 'lower', 'upper', 'replace', 'ljust', \465 'rjust', 'lstrip', 'rstrip', 'center', 'strip', \466 'translate', 'expandtabs', 'swapcase', 'zfill':467 locals()[method] = make_wrapper(method)468469 # new in python 2.5470 if hasattr(unicode, 'partition'):

improved sandbox and updated setup.pyArmin Ronacherbefore adoptiond71fff0

lines 471–477why, one step back
471 partition = make_wrapper('partition'),
472 rpartition = make_wrapper('rpartition')473474 # new in python 2.6475 if hasattr(unicode, 'format'):476 format = make_wrapper('format')477

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

line 478why, one step back
478 del method, make_wrapper

improved sandbox and updated setup.pyArmin Ronacherbefore adoptiond71fff0

lines 479–486why, one step back
479
480481def _escape_argspec(obj, iterable):482 """Helper for various string-wrapped functions."""483 for key, value in iterable:484 if hasattr(value, '__html__') or isinstance(value, basestring):485 obj[key] = escape(value)486 return obj

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 487–497why, one step back
487
488489class _MarkupEscapeHelper(object):490 """Helper for Markup.__mod__"""491492 def __init__(self, obj):493 self.obj = obj494495 __getitem__ = lambda s, x: _MarkupEscapeHelper(s.obj[x])496 __unicode__ = lambda s: unicode(escape(s.obj))497 __str__ = lambda s: str(escape(s.obj))

updated documentationArmin Ronacherbefore adoption3ef2043

line 498why, one step back
498 __repr__ = lambda s: str(escape(repr(s.obj)))

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 499–504why, one step back
499 __int__ = lambda s: int(s.obj)
500 __float__ = lambda s: float(s.obj)501502503class LRUCache(object):504 """A simple LRU Cache implementation."""

data files are optional nowArmin Ronacherbefore adoption58f351d

lines 505–508why, one step back
505
506 # this is fast for small capacities (something below 1000) but doesn't507 # scale. But as long as it's only used as storage for templates this508 # won't do any harm.

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 509–513why, one step back
509
510 def __init__(self, capacity):511 self.capacity = capacity512 self._mapping = {}513 self._queue = deque()

fixed babel entry pointArmin Ronacherbefore adoption7962ce7

line 514why, one step back
514 self._postinit()

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

line 515why, one step back
515

fixed babel entry pointArmin Ronacherbefore adoption7962ce7

line 516why, one step back
516 def _postinit(self):

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 517–530why, one step back
517 # alias all queue methods for faster lookup
518 self._popleft = self._queue.popleft519 self._pop = self._queue.pop520 if hasattr(self._queue, 'remove'):521 self._remove = self._queue.remove522 self._wlock = allocate_lock()523 self._append = self._queue.append524525 def _remove(self, obj):526 """Python 2.4 compatibility."""527 for idx, item in enumerate(self._queue):528 if item == obj:529 del self._queue[idx]530 break

fixed babel entry pointArmin Ronacherbefore adoption7962ce7

lines 531–544why, one step back
531
532 def __getstate__(self):533 return {534 'capacity': self.capacity,535 '_mapping': self._mapping,536 '_queue': self._queue537 }538539 def __setstate__(self, d):540 self.__dict__.update(d)541 self._postinit()542543 def __getnewargs__(self):544 return (self.capacity,)

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 545–600why, one step back
545
546 def copy(self):547 """Return an shallow copy of the instance."""548 rv = self.__class__(self.capacity)549 rv._mapping.update(self._mapping)550 rv._queue = deque(self._queue)551 return rv552553 def get(self, key, default=None):554 """Return an item from the cache dict or `default`"""555 try:556 return self[key]557 except KeyError:558 return default559560 def setdefault(self, key, default=None):561 """Set `default` if the key is not in the cache otherwise562 leave unchanged. Return the value of this key.563 """564 try:565 return self[key]566 except KeyError:567 self[key] = default568 return default569570 def clear(self):571 """Clear the cache."""572 self._wlock.acquire()573 try:574 self._mapping.clear()575 self._queue.clear()576 finally:577 self._wlock.release()578579 def __contains__(self, key):580 """Check if a key exists in this cache."""581 return key in self._mapping582583 def __len__(self):584 """Return the current size of the cache."""585 return len(self._mapping)586587 def __repr__(self):588 return '<%s %r>' % (589 self.__class__.__name__,590 self._mapping591 )592593 def __getitem__(self, key):594 """Get an item from the cache. Moves the item up so that it has the595 highest priority then.596597 Raise an `KeyError` if it does not exist.598 """599 rv = self._mapping[key]600 if self._queue[-1] != key:

Fixed a threading issue with the LRUCache. Still not sure if I should release a Jinja 2.1.2 for that.Armin Ronacherbefore adoption8de6f18

lines 601–607why, one step back
601 try:
602 self._remove(key)603 except:604 # if something removed the key from the container605 # when we read, ignore the ValueError that we would606 # get otherwise.607 pass

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 608–636why, one step back
608 self._append(key)
609 return rv610611 def __setitem__(self, key, value):612 """Sets the value for an item. Moves the item up so that it613 has the highest priority then.614 """615 self._wlock.acquire()616 try:617 if key in self._mapping:618 self._remove(key)619 elif len(self._mapping) == self.capacity:620 del self._mapping[self._popleft()]621 self._append(key)622 self._mapping[key] = value623 finally:624 self._wlock.release()625626 def __delitem__(self, key):627 """Remove an item from the cache dict.628 Raise an `KeyError` if it does not exist.629 """630 self._wlock.acquire()631 try:632 del self._mapping[key]633 self._remove(key)634 finally:635 self._wlock.release()636

more thread safety in LRUCacheArmin Ronacherbefore adoptione25f24d

lines 637–660why, one step back
637 def items(self):
638 """Return a list of items."""639 result = [(key, self._mapping[key]) for key in list(self._queue)]640 result.reverse()641 return result642643 def iteritems(self):644 """Iterate over all items."""645 return iter(self.items())646647 def values(self):648 """Return a list of all values."""649 return [x[1] for x in self.items()]650651 def itervalue(self):652 """Iterate over all values."""653 return iter(self.values())654655 def keys(self):656 """Return a list of all keys ordered by most recent usage."""657 return list(self)658659 def iterkeys(self):660 """Iterate over all keys in the cache dict, ordered by

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 661–662why, one step back
661 the most recent usage.
662 """

improved thread safety of the LRUCache and fixed a bug in for loopsArmin Ronacherbefore adoptione224488

line 663why, one step back
663 return reversed(tuple(self._queue))

more thread safety in LRUCacheArmin Ronacherbefore adoptione25f24d

lines 664–665why, one step back
664
665 __iter__ = iterkeys

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 666–670why, one step back
666
667 def __reversed__(self):668 """Iterate over the values in the cache dict, oldest items669 coming first.670 """

improved thread safety of the LRUCache and fixed a bug in for loopsArmin Ronacherbefore adoptione224488

line 671why, one step back
671 return iter(tuple(self._queue))

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 672–673why, one step back
672
673 __copy__ = copy

some more documentation updates and minor code cleanups. Additionally True and true in the template are the same now, same for false/False and none/None.Armin Ronacherbefore adoption9bb7e47

lines 674–681why, one step back
674
675676# register the LRU cache as mutable mapping if possible677try:678 from collections import MutableMapping679 MutableMapping.register(LRUCache)680except ImportError:681 pass

Various cleanups and added custom cycler.Armin Ronacherbefore adoptionccae055

lines 682–706why, one step back
682
683684class Cycler(object):685 """A cycle helper for templates."""686687 def __init__(self, *items):688 if not items:689 raise RuntimeError('at least one item has to be provided')690 self.items = items691 self.reset()692693 def reset(self):694 """Resets the cycle."""695 self.pos = 0696697 @property698 def current(self):699 """Returns the current item."""700 return self.items[self.pos]701702 def next(self):703 """Goes one item ahead and returns it."""704 rv = self.current705 self.pos = (self.pos + 1) % len(self.items)706 return rv

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 707–708why, one step back
707
708

Implemented and documented "joiner"Armin Ronacherbefore adoptiond34eb12

lines 709–722why, one step back
709class Joiner(object):
710 """A joining helper for templates."""711712 def __init__(self, sep=u', '):713 self.sep = sep714 self.used = False715716 def __call__(self):717 if not self.used:718 self.used = True719 return u''720 return self.sep721722

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 723–728why, one step back
723# we have to import it down here as the speedups module imports the
724# markup type which is define above.725try:726 from jinja2._speedups import escape, soft_unicode727except ImportError:728 def escape(s):

some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)Armin Ronacherbefore adoptionf35e281

lines 729–730why, one step back
729 """Convert the characters &, <, >, ' and " in string s to HTML-safe
730 sequences. Use this if you need to display text that might contain

added macro for char* to Py_UNICODE conversionArmin Ronacherbefore adoption9a1e33c

line 731why, one step back
731 such characters in HTML. Marks return value as markup string.

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 732–738why, one step back
732 """
733 if hasattr(s, '__html__'):734 return s.__html__()735 return Markup(unicode(s)736 .replace('&', '&amp;')737 .replace('>', '&gt;')738 .replace('<', '&lt;')

some documentation improvements, jinja escapes " and ' now, both into charpoints and no named entities for html 3.2 support ;-)Armin Ronacherbefore adoptionf35e281

line 739why, one step back
739 .replace("'", '&#39;')

the two escape implementations work the same now, updated jinja2-debug to load the i18n extensionArmin Ronacherbefore adoption9d42abf

line 740why, one step back
740 .replace('"', '&#34;')

fixed a bug with filtered loopsArmin Ronacherbefore adoptionc072564

lines 741–763why, one step back
741 )
742743 def soft_unicode(s):744 """Make a string unicode if it isn't already. That way a markup745 string is not converted back to unicode.746 """747 if not isinstance(s, unicode):748 s = unicode(s)749 return s750751752# partials753try:754 from functools import partial755except ImportError:756 class partial(object):757 def __init__(self, _func, *args, **kwargs):758 self._func = _func759 self._args = args760 self._kwargs = kwargs761 def __call__(self, *args, **kwargs):762 kwargs.update(self._kwargs)763 return self._func(*(self._args + args), **kwargs)