"Fossies" - the Fresh Open Source Software Archive  

Source code changes of the file "roundup/cgi/PageTemplates/Expressions.py" between
roundup-1.6.1.tar.gz and roundup-2.0.0.tar.gz

About: Roundup is an highly customisable issue-tracking system with command-line, web and e-mail interfaces (written in Python).

Expressions.py  (roundup-1.6.1):Expressions.py  (roundup-2.0.0)
skipping to change at line 26 skipping to change at line 26
# 2. removed all Acquisition # 2. removed all Acquisition
# 3. removed blocking of leading-underscore URL components # 3. removed blocking of leading-underscore URL components
"""Page Template Expression Engine """Page Template Expression Engine
Page Template-specific implementation of TALES, with handlers Page Template-specific implementation of TALES, with handlers
for Python expressions, string literals, and paths. for Python expressions, string literals, and paths.
""" """
import re, sys import re, sys
from TALES import Engine, CompilerError, _valid_name, NAME_RE, \ try:
from collections.abc import Callable
except ImportError:
from collections import Callable
from .TALES import Engine, CompilerError, _valid_name, NAME_RE, \
Undefined, Default, _parse_expr Undefined, Default, _parse_expr
_engine = None _engine = None
def getEngine(): def getEngine():
global _engine global _engine
if _engine is None: if _engine is None:
from PathIterator import Iterator from .PathIterator import Iterator
_engine = Engine(Iterator) _engine = Engine(Iterator)
installHandlers(_engine) installHandlers(_engine)
return _engine return _engine
def installHandlers(engine): def installHandlers(engine):
reg = engine.registerType reg = engine.registerType
pe = PathExpr pe = PathExpr
for pt in ('standard', 'path', 'exists', 'nocall'): for pt in ('standard', 'path', 'exists', 'nocall'):
reg(pt, pe) reg(pt, pe)
reg('string', StringExpr) reg('string', StringExpr)
reg('python', PythonExpr) reg('python', PythonExpr)
reg('not', NotExpr) reg('not', NotExpr)
reg('defer', DeferExpr) reg('defer', DeferExpr)
from PythonExpr import getSecurityManager, PythonExpr from .PythonExpr import getSecurityManager, PythonExpr
guarded_getattr = getattr guarded_getattr = getattr
try: try:
from zExceptions import Unauthorized from zExceptions import Unauthorized
except ImportError: except ImportError:
class Unauthorized(BaseException): class Unauthorized(BaseException):
pass pass
def acquisition_security_filter(orig, inst, name, v, real_validate): def acquisition_security_filter(orig, inst, name, v, real_validate):
if real_validate(orig, inst, name, v): if real_validate(orig, inst, name, v):
return 1 return 1
raise Unauthorized, name raise Unauthorized(name)
def call_with_ns(f, ns, arg=1): def call_with_ns(f, ns, arg=1):
if arg==2: if arg==2:
return f(None, ns) return f(None, ns)
else: else:
return f(ns) return f(ns)
class _SecureModuleImporter: class _SecureModuleImporter:
"""Simple version of the importer for use with trusted code.""" """Simple version of the importer for use with trusted code."""
__allow_access_to_unprotected_subobjects__ = 1 __allow_access_to_unprotected_subobjects__ = 1
skipping to change at line 88 skipping to change at line 93
def render(ob, ns): def render(ob, ns):
""" """
Calls the object, possibly a document template, or just returns it if Calls the object, possibly a document template, or just returns it if
not callable. (From DT_Util.py) not callable. (From DT_Util.py)
""" """
if hasattr(ob, '__render_with_namespace__'): if hasattr(ob, '__render_with_namespace__'):
ob = call_with_ns(ob.__render_with_namespace__, ns) ob = call_with_ns(ob.__render_with_namespace__, ns)
else: else:
base = ob base = ob
if callable(base): if isinstance(base, Callable):
try: try:
if getattr(base, 'isDocTemp', 0): if getattr(base, 'isDocTemp', 0):
ob = call_with_ns(ob, ns, 2) ob = call_with_ns(ob, ns, 2)
else: else:
ob = ob() ob = ob()
except AttributeError as n: except AttributeError as n:
if str(n) != '__call__': if str(n) != '__call__':
raise raise
return ob return ob
class SubPathExpr: class SubPathExpr:
def __init__(self, path): def __init__(self, path):
self._path = path = path.strip().split('/') self._path = path = path.strip().split('/')
self._base = base = path.pop(0) self._base = base = path.pop(0)
if base and not _valid_name(base): if base and not _valid_name(base):
raise CompilerError, 'Invalid variable name "%s"' % base raise CompilerError('Invalid variable name "%s"' % base)
# Parse path # Parse path
self._dp = dp = [] self._dp = dp = []
for i in range(len(path)): for i in range(len(path)):
e = path[i] e = path[i]
if e[:1] == '?' and _valid_name(e[1:]): if e[:1] == '?' and _valid_name(e[1:]):
dp.append((i, e[1:])) dp.append((i, e[1:]))
dp.reverse() dp.reverse()
def _eval(self, econtext, def _eval(self, econtext,
list=list, isinstance=isinstance, StringType=type('')): list=list, isinstance=isinstance, StringType=type('')):
skipping to change at line 195 skipping to change at line 200
return ob return ob
# Return the rendered object # Return the rendered object
return render(ob, econtext.vars) return render(ob, econtext.vars)
def __call__(self, econtext): def __call__(self, econtext):
if self._name == 'exists': if self._name == 'exists':
return self._exists(econtext) return self._exists(econtext)
return self._eval(econtext) return self._eval(econtext)
def __str__(self): def __str__(self):
return '%s expression %s' % (self._name, `self._s`) return '%s expression %s' % (self._name, repr(self._s))
def __repr__(self): def __repr__(self):
return '%s:%s' % (self._name, `self._s`) return '%s:%s' % (self._name, repr(self._s))
_interp = re.compile(r'\$(%(n)s)|\${(%(n)s(?:/[^}]*)*)}' % {'n': NAME_RE}) _interp = re.compile(r'\$(%(n)s)|\${(%(n)s(?:/[^}]*)*)}' % {'n': NAME_RE})
class StringExpr: class StringExpr:
def __init__(self, name, expr, engine): def __init__(self, name, expr, engine):
self._s = expr self._s = expr
if '%' in expr: if '%' in expr:
expr = expr.replace('%', '%%') expr = expr.replace('%', '%%')
self._vars = vars = [] self._vars = vars = []
if '$' in expr: if '$' in expr:
skipping to change at line 221 skipping to change at line 226
if parts: parts.append('$') if parts: parts.append('$')
m = _interp.search(exp) m = _interp.search(exp)
while m is not None: while m is not None:
parts.append(exp[:m.start()]) parts.append(exp[:m.start()])
parts.append('%s') parts.append('%s')
vars.append(PathExpr('path', m.group(1) or m.group(2), vars.append(PathExpr('path', m.group(1) or m.group(2),
engine)) engine))
exp = exp[m.end():] exp = exp[m.end():]
m = _interp.search(exp) m = _interp.search(exp)
if '$' in exp: if '$' in exp:
raise CompilerError, ( raise CompilerError(
'$ must be doubled or followed by a simple path') '$ must be doubled or followed by a simple path')
parts.append(exp) parts.append(exp)
expr = ''.join(parts) expr = ''.join(parts)
self._expr = expr self._expr = expr
def __call__(self, econtext): def __call__(self, econtext):
vvals = [] vvals = []
for var in self._vars: for var in self._vars:
v = var(econtext) v = var(econtext)
# I hope this isn't in use anymore. # I hope this isn't in use anymore.
## if isinstance(v, Exception): ## if isinstance(v, Exception):
## raise v ## raise v
vvals.append(v) vvals.append(v)
return self._expr % tuple(vvals) return self._expr % tuple(vvals)
def __str__(self): def __str__(self):
return 'string expression %s' % `self._s` return 'string expression %s' % repr(self._s)
def __repr__(self): def __repr__(self):
return 'string:%s' % `self._s` return 'string:%s' % repr(self._s)
class NotExpr: class NotExpr:
def __init__(self, name, expr, compiler): def __init__(self, name, expr, compiler):
self._s = expr = expr.lstrip() self._s = expr = expr.lstrip()
self._c = compiler.compile(expr) self._c = compiler.compile(expr)
def __call__(self, econtext): def __call__(self, econtext):
# We use the (not x) and 1 or 0 formulation to avoid changing # We use the (not x) and 1 or 0 formulation to avoid changing
# the representation of the result in Python 2.3, where the # the representation of the result in Python 2.3, where the
# result of "not" becomes an instance of bool. # result of "not" becomes an instance of bool.
return (not econtext.evaluateBoolean(self._c)) and 1 or 0 return (not econtext.evaluateBoolean(self._c)) and 1 or 0
def __repr__(self): def __repr__(self):
return 'not:%s' % `self._s` return 'not:%s' % repr(self._s)
class DeferWrapper: class DeferWrapper:
def __init__(self, expr, econtext): def __init__(self, expr, econtext):
self._expr = expr self._expr = expr
self._econtext = econtext self._econtext = econtext
def __str__(self): def __str__(self):
return str(self()) return str(self())
def __call__(self): def __call__(self):
skipping to change at line 277 skipping to change at line 282
class DeferExpr: class DeferExpr:
def __init__(self, name, expr, compiler): def __init__(self, name, expr, compiler):
self._s = expr = expr.lstrip() self._s = expr = expr.lstrip()
self._c = compiler.compile(expr) self._c = compiler.compile(expr)
def __call__(self, econtext): def __call__(self, econtext):
return DeferWrapper(self._c, econtext) return DeferWrapper(self._c, econtext)
def __repr__(self): def __repr__(self):
return 'defer:%s' % `self._s` return 'defer:%s' % repr(self._s)
class TraversalError: class TraversalError:
def __init__(self, path, name): def __init__(self, path, name):
self.path = path self.path = path
self.name = name self.name = name
def restrictedTraverse(object, path, securityManager, def restrictedTraverse(object, path, securityManager,
get=getattr, has=hasattr, N=None, M=[], get=getattr, has=hasattr, N=None, M=[],
TupleType=type(()) ): TupleType=type(()) ):
skipping to change at line 307 skipping to change at line 312
if isinstance(name, TupleType): if isinstance(name, TupleType):
object = object(*name) object = object(*name)
continue continue
if not name: if not name:
# Skip directly to item access # Skip directly to item access
o = object[name] o = object[name]
# Check access to the item. # Check access to the item.
if not validate(object, object, name, o): if not validate(object, object, name, o):
raise Unauthorized, name raise Unauthorized(name)
object = o object = o
continue continue
# Try an attribute. # Try an attribute.
o = guarded_getattr(object, name, M) o = guarded_getattr(object, name, M)
if o is M: if o is M:
# Try an item. # Try an item.
try: try:
# XXX maybe in Python 2.2 we can just check whether # XXX maybe in Python 2.2 we can just check whether
# the object has the attribute "__getitem__" # the object has the attribute "__getitem__"
 End of changes. 14 change blocks. 
14 lines changed or deleted 19 lines changed or added

Home  |  About  |  Features  |  All  |  Newest  |  Dox  |  Diffs  |  RSS Feeds  |  Screenshots  |  Comments  |  Imprint  |  Privacy  |  HTTP(S)