Skip to content
Myr

added attr filter

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 f15f5f7 · Browse files · 5 files+44 added−6 removed
This commit

State

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

Diff stats

5 files+44 added−6 removed

  • tests:+10 added−0 removed
  • other:+34 added−6 removed

5 files+44 added−6 removed

modified:jinja2/filters.py+23 added-1 removed
14 unmodified lines
15from operator import itemgetter16from itertools import imap, groupby17from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode18from jinja2.runtime import Undefined19from jinja2.exceptions import FilterArgumentError19from jinja2.exceptions import FilterArgumentError, SecurityError202122_word_re = re.compile(r'\w+')23
595 unmodified lines
619 except TypeError:620 raise FilterArgumentError('argument must be iterable')621622623@environmentfilter624def do_attr(environment, obj, name):625 """Get an attribute of an object. ``foo|attr("bar")`` works like626 ``foo["bar"]`` just that always an attribute is returned. This is useful627 if data structures are passed to the template that have an item that hides628 an attribute with the same name. For example a dict ``{'items': []}``629 that obviously hides the item method of a dict.630 """631 try:632 value = getattr(obj, name)633 except AttributeError:634 return environment.undefined(obj=obj, name=name)635 if environment.sandboxed and not \636 environment.is_safe_attribute(obj, name, value):637 return environment.undefined('access to attribute %r of %r '638 'object is unsafe.' % (639 name, obj.__class__.__name__640 ), name=name, obj=obj, exc=SecurityError)641 return value642643644FILTERS = {645 'attr': do_attr,646 'replace': do_replace,647 'upper': do_upper,648 'lower': do_lower,649 'escape': escape,
41 unmodified lines
modified:jinja2/runtime.py+10 added-4 removed
7 unmodified lines
8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10"""11import sys12from types import FunctionType, MethodType13from itertools import chain, imap14from jinja2.utils import Markup, partial, soft_unicode, escape, missing, concat15from jinja2.exceptions import UndefinedError, TemplateRuntimeError16
2 unmodified lines
19__all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',20 'TemplateRuntimeError', 'missing', 'concat', 'escape',21 'markup_join', 'unicode_join']2223_context_function_types = (FunctionType, MethodType)242526def markup_join(seq):27 """Concatenation that escapes if necessary and converts to unicode."""28 buf = []29 iterator = imap(soft_unicode, seq)
90 unmodified lines
120 """Called by the template code to inject the current context121 or environment as first arguments. Then forwards the call to122 the object with the arguments and keyword arguments.123 """124 if __debug__:125 __traceback_hide__ = True126 if isinstance(__obj, _context_function_types):121 if getattr(__obj, 'contextfunction', 0):122 args = (__self,) + args123 elif getattr(__obj, 'environmentfunction', 0):124 args = (__self.environment,) + args127 if getattr(__obj, 'contextfunction', 0):128 args = (__self,) + args129 elif getattr(__obj, 'environmentfunction', 0):130 args = (__self.environment,) + args131 return __obj(*args, **kwargs)132133 def _all(meth):134 proxy = lambda self: getattr(self.get_all(), meth)()
317 unmodified lines
modified:jinja2/sandbox.py+1 added-1 removed
182 unmodified lines
183 return self.undefined('access to attribute %r of %r '184 'object is unsafe.' % (185 argument,186 obj.__class__.__name__187 ), name=argument, exc=SecurityError)187 ), name=argument, obj=obj, exc=SecurityError)188 return self.undefined(obj=obj, name=argument)189190 def call(__self, __context, __obj, *args, **kwargs):191 """Call an object from sandboxed code."""
17 unmodified lines
modified:tests/test_security.py+8 added
4 unmodified lines
56 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8"""9from py.test import raises10from jinja2 import Environment11from jinja2.sandbox import SandboxedEnvironment, \12 ImmutableSandboxedEnvironment, unsafe13from jinja2 import Markup, escape14from jinja2.exceptions import SecurityError151617class PrivateStuff(object):18
114 unmodified lines
133 assert unicode(t.module) == escaped_out134 assert escape(t.module) == escaped_out135 assert t.module.say_hello('<blink>foo</blink>') == escaped_out136 assert escape(t.module.say_hello('<blink>foo</blink>')) == escaped_out137138139def test_attr_filter():140 env = SandboxedEnvironment()141 tmpl = env.from_string('{{ 42|attr("__class__")|attr("__subclasses__")() }}')142 raises(SecurityError, tmpl.render)
modified:tests/test_various.py+2 added
66 unmodified lines
67 for env in Environment(), SandboxedEnvironment():68 tmpl = env.from_string('{{ foo.items() }}')69 assert tmpl.render(foo={'items': lambda: 42}) == '42'70 assert tmpl.render(foo={}) == '[]'71 tmpl = env.from_string('{{ foo|attr("items")() }}')72 assert tmpl.render(foo={'items': None}) == "[('items', None)]"