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
Provenance
- Commit
24b6558- Tree
b502205- Author
Armin Ronacher <armin.ronacher@active-4.com>- Committer
Armin Ronacher <armin.ronacher@active-4.com>- Parent
f15f5f7
5 files changed+44 added−6 removed
modified:jinja2/filters.py+23 added-1 removed
14 unmodified lines15 from operator import itemgetter16 from itertools import imap, groupby17 from jinja2.utils import Markup, escape, pformat, urlize, soft_unicode18 from jinja2.runtime import Undefined19-from jinja2.exceptions import FilterArgumentError19+from jinja2.exceptions import FilterArgumentError, SecurityError20 21 22 _word_re = re.compile(r'\w+')23 595 unmodified lines619 except TypeError:620 raise FilterArgumentError('argument must be iterable')621 622 623+@environmentfilter624+def 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 value642+643+644 FILTERS = {645+ 'attr': do_attr,646 'replace': do_replace,647 'upper': do_upper,648 'lower': do_lower,649 'escape': escape,41 unmodified linesmodified:jinja2/runtime.py+10 added-4 removed
7 unmodified lines8 :copyright: Copyright 2008 by Armin Ronacher.9 :license: GNU GPL.10 """11 import sys12+from types import FunctionType, MethodType13 from itertools import chain, imap14 from jinja2.utils import Markup, partial, soft_unicode, escape, missing, concat15 from jinja2.exceptions import UndefinedError, TemplateRuntimeError16 2 unmodified lines19 __all__ = ['LoopContext', 'Context', 'TemplateReference', 'Macro', 'Markup',20 'TemplateRuntimeError', 'missing', 'concat', 'escape',21 'markup_join', 'unicode_join']22 23+_context_function_types = (FunctionType, MethodType)24 25+26 def markup_join(seq):27 """Concatenation that escapes if necessary and converts to unicode."""28 buf = []29 iterator = imap(soft_unicode, seq)90 unmodified lines120 """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)132 133 def _all(meth):134 proxy = lambda self: getattr(self.get_all(), meth)()317 unmodified linesmodified:jinja2/sandbox.py+1 added-1 removed
182 unmodified lines183 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)189 190 def call(__self, __context, __obj, *args, **kwargs):191 """Call an object from sandboxed code."""17 unmodified linesmodified:tests/test_security.py+8 added
4 unmodified lines5 6 :copyright: 2007 by Armin Ronacher.7 :license: BSD, see LICENSE for more details.8 """9+from py.test import raises10 from jinja2 import Environment11 from jinja2.sandbox import SandboxedEnvironment, \12 ImmutableSandboxedEnvironment, unsafe13 from jinja2 import Markup, escape14+from jinja2.exceptions import SecurityError15 16 17 class PrivateStuff(object):18 114 unmodified lines133 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_out137+138+139+def 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 lines67 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)]"