improved sandbox, added proper striptags and updated documentation to latest sphinx changes
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 4dc9578 · Browse files · 7 files·+46 added−14 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+46 added−14 removed
- other:+46 added−14 removed
Provenance
- Commit
76c280b- Tree
951c7b7- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
4dc9578
7 files changed+46 added−14 removed
modified:docs/conf.py+1 added-1 removed
143 unmodified lines144 # Documents to append as an appendix to all manuals.145 #latex_appendices = []146 147 # If false, no module index is generated.148-#latex_use_modindex = True148+latex_use_modindex = Falsemodified:docs/index.rst-7 removed
7 unmodified lines8 9 intro10 api11 templates12-13-Indices and tables14-==================15-16-* :ref:`genindex`17-* :ref:`modindex`18-* :ref:`search`modified:docs/templates.rst+5 added
836 unmodified lines837 Generates some lorem ipsum for the template. Per default five paragraphs838 with HTML are generated each paragraph between 20 and 100 words. If html839 is disabled regular text is returned. This is useful to generate simple840 contents for layout testing.841+842+.. function:: dict(**items)843+844+ A convenient alternative to dict literals. ``{'foo': 'bar'}`` is the same845+ as ``dict(foo='bar')``.modified:jinja2/defaults.py+1 added
22 unmodified lines23 24 25 DEFAULT_NAMESPACE = {26 'range': xrange,27+ 'dict': lambda **kw: kw,28 'lipsum': generate_lorem_ipsum29 }30 31 2 unmodified linesmodified:jinja2/filters.py+1 added-2 removed
17 unmodified lines18 from jinja2.runtime import Undefined19 from jinja2.exceptions import FilterArgumentError20 21 22-_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')22 _word_re = re.compile(r'\w+')23 24 25 def contextfilter(f):400 unmodified lines426 """Strip SGML/XML tags and replace adjacent whitespace by one space.427 """428 if hasattr(value, '__html__'):429 value = value.__html__()431- return u' '.join(_striptags_re.sub('', value).split())430+ return Markup(unicode(value)).striptags()431 432 433 def do_slice(value, slices, fill_with=None):434 """Slice an iterator and return a list of lists containing230 unmodified linesmodified:jinja2/sandbox.py+12 added-3 removed
18 unmodified lines19 20 #: maximum number of items a range may produce21 MAX_RANGE = 10000022 23+#: attributes of function objects that are considered unsafe.24+UNSAFE_FUNCTION_ATTRIBUTES = set(['func_closure', 'func_code', 'func_dict',25+ 'func_defaults', 'func_globals'])26 27+#: unsafe method attributes. function attributes are unsafe for methods too28+UNSAFE_METHOD_ATTRIBUTES = set(['im_class', 'im_func', 'im_self'])29+30+31 def safe_range(*args):32 """A range that can't generate ranges with a length of more than33 MAX_RANGE items.34 """35 rng = xrange(*args)36 if len(rng) > MAX_RANGE:30- raise OverflowError('range too big')37+ raise OverflowError('range too big, maximum size for range is %d' %38+ MAX_RANGE)39 return rng40 41 42 def unsafe(f):18 unmodified lines61 """62 if attr.startswith('_'):63 return False64 if isinstance(obj, FunctionType):57- return not attr.startswith('func_')65+ return attr not in UNSAFE_FUNCTION_ATTRIBUTES66 if isinstance(obj, MethodType):59- return not attr.startswith('im_')67+ return attr not in UNSAFE_FUNCTION_ATTRIBUTES and \68+ attr not in UNSAFE_METHOD_ATTRIBUTES69 return True70 71 def is_safe_callable(self, obj):72 """Check if an object is safely callable. Per default a function is36 unmodified linesmodified:jinja2/utils.py+26 added-1 removed
13 unmodified lines14 try:15 from thread import allocate_lock16 except ImportError:17 from dummy_thread import allocate_lock18+from htmlentitydefs import name2codepoint19 from collections import deque20 from copy import deepcopy21 from itertools import imap22 5 unmodified lines28 '|'.join(imap(re.escape, ('.', ',', ')', '>', '\n', '>')))29 )30 )31 _simple_email_re = re.compile(r'^\S+@[a-zA-Z0-9._-]+\.[a-zA-Z0-9._-]+$')32+_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')33+_entity_re = re.compile(r'&([^;]+);')34+_entities = name2codepoint.copy()35+_entities['apos'] = 3936 32-37 # special singleton representing missing values for the runtime38 missing = type('MissingType', (), {'__repr__': lambda x: 'missing'})()39 40 240 unmodified lines281 def splitlines(self, *args, **kwargs):282 return map(self.__class__, unicode.splitlines(self, *args, **kwargs))283 splitlines.__doc__ = unicode.splitlines.__doc__284 285+ def unescape(self):286+ """Unescape markup."""287+ def handle_match(m):288+ name = m.group(1)289+ if name in _entities:290+ return unichr(_entities[name])291+ try:292+ if name[:2] in ('#x', '#X'):293+ return unichr(int(name[2:], 16))294+ elif name.startswith('#'):295+ return unichr(int(name[1:]))296+ except ValueError:297+ pass298+ return u''299+ return _entity_re.sub(handle_match, unicode(self))300+301+ def striptags(self):302+ """Strip tags and resolve enities."""303+ stripped = u' '.join(_striptags_re.sub('', self).split())304+ return Markup(stripped).unescape()305+306 def make_wrapper(name):307 orig = getattr(unicode, name)308 def func(self, *args, **kwargs):309 args = list(args)205 unmodified lines