/usr/share/pyshared/z3c/pt/expressions.py is in python-z3c.pt 2.2.3-0ubuntu1.
This file is owned by root:root, with mode 0o644.
The actual contents of the file can be viewed below.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 | import re
import ast
import namespaces
import zope.event
from zope.traversing.adapters import traversePathElement
from zope.contentprovider.interfaces import IContentProvider
from zope.contentprovider.interfaces import ContentProviderLookupError
from zope.contentprovider.tales import addTALNamespaceData
from zope.traversing.interfaces import ITraversable
from zope.location.interfaces import ILocation
try:
from zope.contentprovider.interfaces import BeforeUpdateEvent
except ImportError:
BeforeUpdateEvent = None
from types import MethodType
from chameleon.tales import TalesExpr
from chameleon.tales import ExistsExpr as BaseExistsExpr
from chameleon.tales import PythonExpr as BasePythonExpr
from chameleon.tales import StringExpr
from chameleon.codegen import template
from chameleon.astutil import load
from chameleon.astutil import Symbol
from chameleon.astutil import Builtin
from chameleon.astutil import NameLookupRewriteVisitor
from chameleon.exc import ExpressionError
_marker = object()
def render_content_provider(econtext, name):
name = name.strip()
context = econtext.get('context')
request = econtext.get('request')
view = econtext.get('view')
cp = zope.component.queryMultiAdapter(
(context, request, view), IContentProvider, name=name)
# provide a useful error message, if the provider was not found.
if cp is None:
raise ContentProviderLookupError(name)
# add the __name__ attribute if it implements ILocation
if ILocation.providedBy(cp):
cp.__name__ = name
# Insert the data gotten from the context
addTALNamespaceData(cp, econtext)
# Stage 1: Do the state update.
if BeforeUpdateEvent is not None:
zope.event.notify(BeforeUpdateEvent(cp, request))
cp.update()
# Stage 2: Render the HTML content.
return cp.render()
def path_traverse(base, econtext, call, path_items):
if path_items:
request = econtext.get('request')
path_items = list(path_items)
path_items.reverse()
while len(path_items):
name = path_items.pop()
ns_used = ':' in name
if ns_used:
namespace, name = name.split(':', 1)
base = namespaces.function_namespaces[namespace](base)
if ITraversable.providedBy(base):
base = traversePathElement(
base, name, path_items, request=request)
# base = proxify(base)
continue
# special-case dicts for performance reasons
if isinstance(base, dict):
next = base.get(name, _marker)
else:
next = getattr(base, name, _marker)
if next is not _marker:
base = next
if ns_used and isinstance(base, MethodType):
base = base()
continue
else:
base = traversePathElement(
base, name, path_items, request=request)
# if not isinstance(base, (basestring, tuple, list)):
# base = proxify(base)
if call and getattr(base, '__call__', _marker) is not _marker:
return base()
return base
class ContextExpressionMixin(object):
"""Mixin-class for expression compilers."""
transform = None
def __call__(self, target, engine):
# Make call to superclass to assign value to target
assignment = super(ContextExpressionMixin, self).\
__call__(target, engine)
transform = template(
"target = transform(econtext, target)",
target=target,
transform=self.transform,
)
return assignment + transform
class PathExpr(TalesExpr):
path_regex = re.compile(
r'^(?:(nocall|not):\s*)*((?:[A-Za-z_][A-Za-z0-9_:]*)' +
r'(?:/[?A-Za-z_@\-+][?A-Za-z0-9_@\-\.+/:]*)*)$')
interpolation_regex = re.compile(
r'\?[A-Za-z][A-Za-z0-9_]+')
traverser = Symbol(path_traverse)
def translate(self, string, target):
"""
>>> from chameleon.tales import test
>>> test(PathExpr('')) is None
True
"""
string = string.strip()
if not string:
return template("target = None", target=target)
m = self.path_regex.match(string)
if m is None:
raise ExpressionError("Not a valid path-expression.", string)
nocall, path = m.groups()
# note that unicode paths are not allowed
parts = str(path).split('/')
components = []
for part in parts[1:]:
interpolation_args = []
def replace(match):
start, end = match.span()
interpolation_args.append(
part[start + 1:end])
return "%s"
while True:
part, count = self.interpolation_regex.subn(replace, part)
if count == 0:
break
if len(interpolation_args):
component = template(
"format % args", format=ast.Str(part),
args=ast.Tuple(
list(map(load, interpolation_args)),
ast.Load()
),
mode="eval")
else:
component = ast.Str(part)
components.append(component)
base = parts[0]
if not components:
if len(parts) == 1 and (nocall or base == 'None'):
return template("target = base", base=base, target=target)
else:
components = ()
call = template(
"traverse(base, econtext, call, path_items)",
traverse=self.traverser,
base=load(base),
call=load(str(not nocall)),
path_items=ast.Tuple(elts=components),
mode="eval",
)
return template("target = value", target=target, value=call)
class NocallExpr(PathExpr):
"""A path-expression which does not call the resolved object."""
def translate(self, expression, engine):
return super(NocallExpr, self).translate(
"nocall:%s" % expression, engine)
class ExistsExpr(BaseExistsExpr):
exceptions = AttributeError, LookupError, TypeError, KeyError, NameError
def __init__(self, expression):
super(ExistsExpr, self).__init__("nocall:" + expression)
class ProviderExpr(ContextExpressionMixin, StringExpr):
transform = Symbol(render_content_provider)
class PythonExpr(BasePythonExpr):
builtins = dict(
(name, template(
"tales(econtext, rcontext, name)",
tales=Builtin("tales"),
name=ast.Str(s=name),
mode="eval"))
for name in ('path', 'exists')
)
def __init__(self, expression):
self.expression = expression
def __call__(self, target, engine):
return self.translate(self.expression, target)
def rewrite(self, node):
builtin = self.builtins.get(node.id)
if builtin is not None:
return template(
"get(name) if get(name) is not None else builtin",
get=Builtin("get"),
name=ast.Str(s=node.id),
builtin=builtin,
mode="eval"
)
@property
def transform(self):
return NameLookupRewriteVisitor(self.rewrite)
|