Skip to content
Myr

added sandbox and exchageable undefined objects

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 f437fa3 · Browse files · 9 files+230 added−49 removed
This commit

State

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

Diff stats

9 files+230 added−49 removed

  • other:+230 added−49 removed

9 files+230 added−49 removed

modified:jinja2/__init__.py+1 added
55 unmodified lines
56 :copyright: 2008 by Armin Ronacher.57 :license: BSD, see LICENSE for more details.58"""59from jinja2.environment import Environment60from jinja2.runtime import Undefined, DebugUndefined, StrictUndefined
modified:jinja2/compiler.py+11 added-8 removed
455 unmodified lines
456 # generate the root render function.457 self.writeline('def root(globals, environment=environment'458 ', standalone=False):', extra=1)459 self.indent()460 self.writeline('context = TemplateContext(globals, %r, blocks'461 ', standalone)' % self.filename)460 self.writeline('context = TemplateContext(environment, globals, %r, '461 'blocks, standalone)' % self.filename)462 if have_extends:463 self.writeline('parent_root = None')464 self.outdent()465
146 unmodified lines
612613 # the expression pointing to the parent loop. We make the614 # undefined a bit more debug friendly at the same time.615 parent_loop = 'loop' in aliases and aliases['loop'] \616 or "Undefined('loop', extra=%r)" % \616 or "environment.undefined('loop', extra=%r)" % \617 'the filter section of a loop as well as the ' \618 'else block doesn\'t have access to the special ' \619 "'loop' variable of the current loop. Because " \620 'there is no parent loop it\'s undefined.'
69 unmodified lines
690 self.write('context[%r] = ' % node.name)691 arg_tuple = ', '.join(repr(x.name) for x in node.args)692 if len(node.args) == 1:693 arg_tuple += ','694 self.write('l_%s = Macro(macro, %r, (%s), (' % (node.name, node.name,695 arg_tuple))694 self.write('l_%s = Macro(environment, macro, %r, (%s), (' %695 (node.name, node.name, arg_tuple))696 for arg in node.defaults:697 self.visit(arg, macro_frame)698 self.write(', ')699 self.write('), %s, %s)' % (
14 unmodified lines
714 self.outdent()715 arg_tuple = ', '.join(repr(x.name) for x in node.args)716 if len(node.args) == 1:717 arg_tuple += ','718 self.writeline('caller = Macro(call, None, (%s), (' % arg_tuple)718 self.writeline('caller = Macro(environment, call, None, (%s), (' %719 arg_tuple)720 for arg in node.defaults:721 self.visit(arg)722 self.write(', ')723 self.write('), %s, 0)' % (call_frame.accesses_arguments and '1' or '0'))
236 unmodified lines
960 if isinstance(const, (int, long, float)):961 self.visit(node.node, frame)962 self.write('[%s]' % const)963 return963 self.write('subscribe(')964 self.write('environment.subscribe(')965 self.visit(node.node, frame)966 self.write(', ')967 if have_const:968 self.write(repr(const))
50 unmodified lines
1019 self.visit(node.expr2, frame)1020 self.write(')')10211022 def visit_Call(self, node, frame, extra_kwargs=None):1023 if self.environment.sandboxed:1024 self.write('environment.call(')1025 self.visit(node.node, frame)1023 self.write('(')1026 self.write(self.environment.sandboxed and ', ' or '(')1027 self.signature(node, frame, False, extra_kwargs)1028 self.write(')')10291030 def visit_Keyword(self, node, frame):
3 unmodified lines
modified:jinja2/defaults.py+4 added-6 removed
1# -*- coding: utf-8 -*-2"""3 jinja.defaults4 ~~~~~~~~~~~~~~3 jinja2.defaults4 ~~~~~~~~~~~~~~~56 Jinja default filters and tags.78 :copyright: 2007 by Armin Ronacher.8 :copyright: 2007-2008 by Armin Ronacher.9 :license: BSD, see LICENSE for more details.10"""11from jinja2.filters import FILTERS as DEFAULT_FILTERS12from jinja.tests import TESTS as DEFAULT_TESTS1314DEFAULT_NAMESPACE = {15 'range': xrange16}161718__all__ = ['DEFAULT_FILTERS', 'DEFAULT_TESTS', 'DEFAULT_NAMESPACE']
modified:jinja2/environment.py+75 added
10 unmodified lines
11from jinja2.lexer import Lexer12from jinja2.parser import Parser13from jinja2.optimizer import optimize14from jinja2.compiler import generate15from jinja2.runtime import Undefined16from jinja2.defaults import DEFAULT_FILTERS, DEFAULT_TESTS, DEFAULT_NAMESPACE171819class Environment(object):
3 unmodified lines
23 important shared variables like configuration, filters, tests,24 globals and others.25 """2627 #: if this environment is sandboxed. Modifying this variable won't make28 #: the environment sandboxed though. For a real sandboxed environment29 #: have a look at jinja2.sandbox30 sandboxed = False3132 def __init__(self,33 block_start_string='{%',34 block_end_string='%}',35 variable_start_string='{{',
2 unmodified lines
38 comment_end_string='#}',39 line_statement_prefix=None,40 trim_blocks=False,41 optimized=True,42 undefined=Undefined,43 loader=None):44 """Here the possible initialization parameters:4546 ========================= ============================================
14 unmodified lines
61 after a block is removed (block, not62 variable tag!). Defaults to ``False``.63 `optimized` should the optimizer be enabled? Default is64 ``True``.65 `undefined` a subclass of `Undefined` that is used to66 represent undefined variables.67 `loader` the loader which should be used.68 ========================= ============================================69 """70 assert issubclass(undefined, Undefined), 'undefined must be ' \71 'a subclass of undefined because filters depend on it.'7273 # lexer / parser information74 self.block_start_string = block_start_string75 self.block_end_string = block_end_string
2 unmodified lines
78 self.comment_start_string = comment_start_string79 self.comment_end_string = comment_end_string80 self.line_statement_prefix = line_statement_prefix81 self.trim_blocks = trim_blocks82 self.undefined = undefined83 self.optimized = optimized8485 # defaults86 self.filters = DEFAULT_FILTERS.copy()
11 unmodified lines
9899 # create lexer100 self.lexer = Lexer(self)101102 def subscribe(self, obj, argument):103 """Get an item or attribute of an object."""104 try:105 return getattr(obj, str(argument))106 except (AttributeError, UnicodeError):107 try:108 return obj[argument]109 except (TypeError, LookupError):110 return self.undefined(obj, argument)111112 def parse(self, source, filename=None):113 """Parse the sourcecode and return the abstract syntax tree. This tree114 of nodes is used by the compiler to convert the template into115 executable source- or bytecode.
91 unmodified lines
207 gen = self.root_render_func(context)208 # skip the first item which is a reference to the stream209 gen.next()210 return gen211212 def __repr__(self):213 return '<%s %r>' % (214 self.__class__.__name__,215 self.name216 )217218219class TemplateStream(object):220 """Wraps a genererator for outputing template streams."""221222 def __init__(self, gen):223 self._gen = gen224 self._next = gen.next225 self.buffered = False226227 def disable_buffering(self):228 """Disable the output buffering."""229 self._next = self._gen.next230 self.buffered = False231232 def enable_buffering(self, size=5):233 """Enable buffering. Buffer `size` items before yielding them."""234 if size <= 1:235 raise ValueError('buffer size too small')236 self.buffered = True237238 def buffering_next():239 buf = []240 c_size = 0241 push = buf.append242 next = self._gen.next243244 try:245 while 1:246 item = next()247 if item:248 push(item)249 c_size += 1250 if c_size >= size:251 raise StopIteration()252 except StopIteration:253 if not c_size:254 raise255 return u''.join(buf)256257 self._next = buffering_next258259 def __iter__(self):260 return self261262 def next(self):263 return self._next()
modified:jinja2/filters.py+1 added-2 removed
14 unmodified lines
15except ImportError:16 itemgetter = lambda a: lambda b: b[a]17from urllib import urlencode, quote18from jinja2.utils import escape, pformat19from jinja2.nodes import Undefined19from jinja2.runtime import Undefined20212222_striptags_re = re.compile(r'(<!--.*?-->|<[^>]*>)')232425def contextfilter(f):
830 unmodified lines
modified:jinja2/nodes.py+1 added-2 removed
14 unmodified lines
15import operator16from itertools import chain, izip17from collections import deque18from copy import copy19from jinja2.runtime import Undefined, subscribe192021_binop_to_func = {22 '*': operator.mul,
438 unmodified lines
461 def as_const(self):462 if self.ctx != 'load':463 raise Impossible()464 try:466 return subscribe(self.node.as_const(), self.arg.as_const())465 return environmen.subscribe(self.node.as_const(), self.arg.as_const())466 except:467 raise Impossible()468469 def can_assign(self):
105 unmodified lines
modified:jinja2/optimizer.py+1 added-1 removed
19 unmodified lines
20 :license: GNU GPL.21"""22from jinja2 import nodes23from jinja2.visitor import NodeVisitor, NodeTransformer24from jinja2.runtime import subscribe, LoopContext24from jinja2.runtime import LoopContext252627def optimize(node, environment, context_hint=None):28 """The context hint can be used to perform an static optimization
229 unmodified lines
modified:jinja2/runtime.py+49 added-30 removed
12 unmodified lines
13except ImportError:14 defaultdict = None151617__all__ = ['subscribe', 'LoopContext', 'StaticLoopContext', 'TemplateContext',18 'Macro', 'IncludedTemplate', 'Undefined', 'TemplateData']17__all__ = ['LoopContext', 'StaticLoopContext', 'TemplateContext',18 'Macro', 'IncludedTemplate', 'TemplateData']192021def subscribe(obj, argument):22 """Get an item or attribute of an object."""23 try:24 return getattr(obj, str(argument))25 except (AttributeError, UnicodeError):26 try:27 return obj[argument]28 except (TypeError, LookupError):29 return Undefined(obj, argument)303121class TemplateData(unicode):22 """Marks data as "coming from the template". This is used to let the23 system know that this data is already processed if a finalization is24 used."""
8 unmodified lines
33 update and other methods will not work as they seem (they don't update34 the exported variables for example).35 """3648 def __init__(self, globals, filename, blocks, standalone):37 def __init__(self, environment, globals, filename, blocks, standalone):38 dict.__init__(self, globals)39 self.environment = environment40 self.exported = set()41 self.filename = filename42 self.blocks = dict((k, [v]) for k, v in blocks.iteritems())43
9 unmodified lines
53 """Render a parent block."""54 try:55 func = self.blocks[block][-2]56 except LookupError:67 return Undefined('super', extra='there is probably no parent '68 'block with this name')57 return self.environment.undefined('super',58 extra='there is probably no parent block with this name')59 return SuperBlock(block, self, func)6061 def __setitem__(self, key, value):62 """If we set items to the dict we track the variables set so
14 unmodified lines
77 if defaultdict is None:78 def __getitem__(self, name):79 if name in self:80 return self[name]91 return Undefined(name)81 return self.environment.undefined(name)82 else:83 def __missing__(self, key):94 return Undefined(key)84 return self.environment.undefined(key)8586 def __repr__(self):87 return '<%s %s of %r>' % (88 self.__class__.__name__,
127 unmodified lines
216217class Macro(object):218 """Wraps a macro."""219230 def __init__(self, func, name, arguments, defaults, catch_all, caller):220 def __init__(self, environment, func, name, arguments, defaults, catch_all, caller):221 self._environment = environment222 self._func = func223 self.name = name224 self.arguments = arguments225 self.defaults = defaults
15 unmodified lines
241 except KeyError:242 try:243 value = self.defaults[idx - arg_count]244 except IndexError:254 value = Undefined(name, extra='parameter not provided')245 value = self._environment.undefined(name,246 extra='parameter not provided')247 arguments['l_' + name] = value248 if self.caller:249 caller = kwargs.pop('caller', None)250 if caller is None:259 caller = Undefined('caller', extra='The macro was called '260 'from an expression and not a call block.')251 caller = self._environment.undefined('caller',252 extra='The macro was called from an expression and not '253 'a call block.')254 arguments['l_caller'] = caller255 if self.catch_all:256 arguments['l_arguments'] = kwargs257 return self._func(**arguments)
5 unmodified lines
263 )264265266class Undefined(object):274 """The object for undefined values."""267 """The default undefined implementation. This undefined implementation268 can be printed and iterated over, but every other access will raise a269 `NameError`. Custom undefined classes must subclass this.270 """271272 def __init__(self, name=None, attr=None, extra=None):273 if attr is None:274 self._undefined_hint = '%r is undefined' % name
2 unmodified lines
277 % (attr, name)278 if extra is not None:279 self._undefined_hint += ' (' + extra + ')'280285 def fail(self, *args, **kwargs):281 def fail_with_error(self, *args, **kwargs):282 raise NameError(self._undefined_hint)287 __getattr__ = __getitem__ = __add__ = __mul__ = __div__ = \288 __realdiv__ = __floordiv__ = __mod__ = __pos__ = __neg__ = \289 __call__ = fail290 del fail283 __add__ = __radd__ = __mul__ = __rmul__ = __div__ = __rdiv__ = \284 __realdiv__ = __rrealdiv__ = __floordiv__ = __rfloordiv__ = \285 __mod__ = __rmod__ = __pos__ = __neg__ = __call__ = \286 __getattr__ = __getitem__ = fail_with_error287 del fail_with_error288289 def __unicode__(self):293 return ''290 return u''291292 def __str__(self):293 return self.__unicode__().encode('utf-8')294295 def __repr__(self):296 return 'Undefined'296 return 'undefined'297298 def __len__(self):299 return 0300301 def __iter__(self):302 if 0:303 yield None304305 def __nonzero__(self):306 return False307308309class DebugUndefined(Undefined):310 """An undefined that returns the debug info when printed."""311312 def __unicode__(self):313 return u'{{ %s }}' % self._undefined_hint314315316class StrictUndefined(Undefined):317 """An undefined that barks on print and iteration."""318319 def fail_with_error(self, *args, **kwargs):320 raise NameError(self._undefined_hint)321 __iter__ = __unicode__ = __len__ = fail_with_error322 del fail_with_error
added:jinja2/sandbox.py+87 added
1# -*- coding: utf-8 -*-2"""3 jinja2.sandbox4 ~~~~~~~~~~~~~~56 Adds a sandbox layer to Jinja as it was the default behavior in the old7 Jinja 1 releases. This sandbox is slightly different from Jinja 1 as the8 default behavior is easier to use.910 The behavior can be changed by subclassing the environment.1112 :copyright: Copyright 2008 by Armin Ronacher.13 :license: BSD.14"""15from types import FunctionType, MethodType16from jinja2.runtime import Undefined17from jinja2.environment import Environment181920#: maximum number of items a range may produce21MAX_RANGE = 100000222324def safe_range(*args):25 """A range that can't generate ranges with a length of more than26 MAX_RANGE items."""27 rng = xrange(*args)28 if len(rng) > MAX_RANGE:29 raise OverflowError('range too big')30 return rng313233def unsafe(f):34 """Mark a function as unsafe."""35 f.unsafe_callable = True36 return f373839class SandboxedEnvironment(Environment):40 """The sandboxed environment"""41 sandboxed = True4243 def __init__(self, *args, **kwargs):44 Environment.__init__(self, *args, **kwargs)45 self.globals['range'] = safe_range4647 def is_safe_attribute(self, obj, attr):48 """The sandboxed environment will call this method to check if the49 attribute of an object is safe to access. Per default all attributes50 starting with an underscore are considered private as well as the51 special attributes of functions and methods.52 """53 if attr.startswith('_'):54 return False55 if isinstance(obj, FunctionType):56 return not attr.startswith('func_')57 if isinstance(obj, MethodType):58 return not attr.startswith('im_')59 return True6061 def is_safe_callable(self, obj):62 """Check if an object is safely callable. Per default a function is63 considered safe unless the `unsafe_callable` attribute exists and is64 truish. Override this method to alter the behavior, but this won't65 affect the `unsafe` decorator from this module.66 """67 return not getattr(obj, 'unsafe_callable', False)6869 def subscribe(self, obj, arg):70 """Subscribe an object from sandboxed code."""71 try:72 return obj[arg]73 except (TypeError, LookupError):74 if not self.is_safe_attribute(obj, arg):75 return Undefined(obj, arg, extra='attribute unsafe')76 try:77 return getattr(obj, str(arg))78 except (AttributeError, UnicodeError):79 return Undefined(obj, arg)8081 def call(__self, __obj, *args, **kwargs):82 """Call an object from sandboxed code."""83 # the double prefixes are to avoid double keyword argument84 # errors when proxying the call.85 if not __self.is_safe_callable(__obj):86 raise TypeError('%r is not safely callable' % (__obj,))87 return __obj(*args, **kwargs)