Page Template Engines¶
Expression engine configuration and registration.
Each expression engine can have its own expression types and base names.
-
class
zope.pagetemplate.engine.
ZopePythonExpr
(name, expr, engine)[source]¶ Bases:
zope.tales.pythonexpr.PythonExpr
Parameters: - expr (str) – The Python expression.
- engine (ExpressionEngine) – The expression compiler that is creating us.
-
class
zope.pagetemplate.engine.
ZopeContextBase
(engine, contexts)[source]¶ Bases:
zope.tales.tales.Context
Base class for both trusted and untrusted evaluation contexts.
Parameters: - engine – A
ExpressionEngine
(azope.tal.interfaces.ITALExpressionCompiler
) - contexts – A mapping (namespace) of variables that forms the base variable scope.
- engine – A
-
class
zope.pagetemplate.engine.
ZopeContext
(engine, contexts)[source]¶ Bases:
zope.pagetemplate.engine.ZopeContextBase
Evaluation context for untrusted programs.
Parameters: - engine – A
ExpressionEngine
(azope.tal.interfaces.ITALExpressionCompiler
) - contexts – A mapping (namespace) of variables that forms the base variable scope.
-
evaluateMacro
(expr)[source]¶ evaluateMacro gets security-proxied macro programs when this is run with the zopeTraverser, and in other untrusted situations. This will cause evaluation to fail in zope.tal.talinterpreter, which knows nothing of security proxies. Therefore, this method removes any proxy from the evaluated expression.
>>> from zope.pagetemplate.engine import ZopeContext >>> from zope.tales.tales import ExpressionEngine >>> from zope.security.proxy import ProxyFactory >>> output = [('version', 'xxx'), ('mode', 'html'), ('other', 'things')] >>> def expression(context): ... return ProxyFactory(output) ... >>> zc = ZopeContext(ExpressionEngine, {}) >>> out = zc.evaluateMacro(expression) >>> type(out) is list True
The method does some trivial checking to make sure we are getting back a macro like we expect: it must be a sequence of sequences, in which the first sequence must start with ‘version’, and the second must start with ‘mode’.
>>> del output[0] >>> zc.evaluateMacro(expression) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ('unexpected result from macro evaluation.', ...)
>>> del output[:] >>> zc.evaluateMacro(expression) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ('unexpected result from macro evaluation.', ...)
>>> output = None >>> zc.evaluateMacro(expression) # doctest: +ELLIPSIS Traceback (most recent call last): ... ValueError: ('unexpected result from macro evaluation.', ...)
- engine – A
-
class
zope.pagetemplate.engine.
TrustedZopeContext
(engine, contexts)[source]¶ Bases:
zope.pagetemplate.engine.ZopeContextBase
Evaluation context for trusted programs.
Parameters: - engine – A
ExpressionEngine
(azope.tal.interfaces.ITALExpressionCompiler
) - contexts – A mapping (namespace) of variables that forms the base variable scope.
- engine – A
-
class
zope.pagetemplate.engine.
AdapterNamespaces
[source]¶ Bases:
object
Simulate tales function namespaces with adapter lookup.
When we are asked for a namespace, we return an object that actually computes an adapter when called:
To demonstrate this, we need to register an adapter:
>>> from zope.component.testing import setUp, tearDown >>> setUp() >>> from zope.component import provideAdapter >>> def adapter1(ob): ... return 1 >>> adapter1.__component_adapts__ = (None,) >>> from zope.traversing.interfaces import IPathAdapter >>> provideAdapter(adapter1, None, IPathAdapter, 'a1')
Now, with this adapter in place, we can try out the namespaces:
>>> ob = object() >>> from zope.pagetemplate.engine import AdapterNamespaces >>> namespaces = AdapterNamespaces() >>> namespace = namespaces['a1'] >>> namespace(ob) 1 >>> namespace = namespaces['a2'] >>> namespace(ob) Traceback (most recent call last): ... KeyError: 'a2'
Cleanup:
>>> tearDown()
-
class
zope.pagetemplate.engine.
ZopeBaseEngine
[source]¶ Bases:
zope.tales.tales.ExpressionEngine
-
getContext
(_ZopeBaseEngine__namespace=None, **namespace)[source]¶ Return a new expression engine.
The keyword arguments passed in kwcantexts become the default variable context for the returned engine. If contexts is given, it should be a mapping, and the values it contains will override the keyword arguments.
Return type: Context
-
-
class
zope.pagetemplate.engine.
ZopeEngine
[source]¶ Bases:
zope.pagetemplate.engine.ZopeBaseEngine
Untrusted expression engine.
This engine does not allow modules to be imported; only modules already available may be accessed:
>>> from zope.pagetemplate.engine import _Engine >>> modname = 'zope.pagetemplate.tests.trusted' >>> engine = _Engine() >>> context = engine.getContext(engine.getBaseNames()) >>> modname in sys.modules False >>> context.evaluate('modules/' + modname) Traceback (most recent call last): ... KeyError: 'zope.pagetemplate.tests.trusted'
(The use of
KeyError
is an unfortunate implementation detail; I think this should be aTraversalError
.)Modules which have already been imported by trusted code are available, wrapped in security proxies:
>>> m = context.evaluate('modules/sys') >>> m.__name__ 'sys' >>> m._getframe Traceback (most recent call last): ... ForbiddenAttribute: ('_getframe', <module 'sys' (built-in)>)
The results of Python expressions evaluated by this engine are wrapped in security proxies if the ‘untrusted’ extra is installed:
>>> r = context.evaluate('python: {12: object()}.values') >>> str(type(r).__name__) in ( ... ('_Proxy',) if HAVE_UNTRUSTED else ... ('builtin_function_or_method', 'method', 'instancemethod')) True >>> r = context.evaluate('python: {12: object()}[12].__class__') >>> str(type(r).__name__) == '_Proxy' or not HAVE_UNTRUSTED True
General path expressions provide objects that are wrapped in security proxies as well:
>>> from zope.component.testing import setUp, tearDown >>> from zope.security.checker import NamesChecker, defineChecker >>> @implementer(ITraversable) ... class Container(dict): ... def traverse(self, name, further_path): ... return self[name] >>> setUp() >>> defineChecker(Container, NamesChecker(['traverse'])) >>> d = engine.getBaseNames() >>> foo = Container() >>> foo.__name__ = 'foo' >>> d['foo'] = ProxyFactory(foo) >>> foo['bar'] = bar = Container() >>> bar.__name__ = 'bar' >>> bar.__parent__ = foo >>> bar['baz'] = baz = Container() >>> baz.__name__ = 'baz' >>> baz.__parent__ = bar >>> context = engine.getContext(d) >>> o1 = context.evaluate('foo/bar') >>> o1.__name__ 'bar' >>> type(o1) <type 'zope.security._proxy._Proxy'> >>> o2 = context.evaluate('foo/bar/baz') >>> o2.__name__ 'baz' >>> type(o2) <type 'zope.security._proxy._Proxy'> >>> o3 = o2.__parent__ >>> type(o3) <type 'zope.security._proxy._Proxy'> >>> o1 == o3 True >>> o1 is o2 False
Note that this engine special-cases dicts during path traversal: it traverses only to their items, but not to their attributes (e.g. methods on dicts), because of performance reasons:
>>> d = engine.getBaseNames() >>> d['adict'] = {'items': 123} >>> d['anotherdict'] = {} >>> context = engine.getContext(d) >>> context.evaluate('adict/items') 123 >>> context.evaluate('anotherdict/keys') Traceback (most recent call last): ... KeyError: 'keys'
This special-casing also applies to non-proxied dict subclasses:
>>> class TraverserDict(dict): ... def __init__(self): ... self.item_requested = None ... def __getitem__(self, item): ... self.item_requested = item ... return dict.__getitem__(self, item) >>> d = engine.getBaseNames() >>> foo = TraverserDict() >>> d['foo'] = foo >>> foo['bar'] = 'baz' >>> context = engine.getContext(d) >>> context.evaluate('foo/bar') 'baz' >>> foo.item_requested 'bar' >>> tearDown()
-
class
zope.pagetemplate.engine.
TrustedZopeEngine
[source]¶ Bases:
zope.pagetemplate.engine.ZopeBaseEngine
Trusted expression engine.
This engine allows modules to be imported:
>>> from zope.pagetemplate.engine import _TrustedEngine >>> modname = 'zope.pagetemplate.tests.trusted' >>> engine = _TrustedEngine() >>> context = engine.getContext(engine.getBaseNames()) >>> modname in sys.modules False >>> m = context.evaluate('modules/' + modname) >>> m.__name__ == modname True >>> modname in sys.modules True
Since this is trusted code, we can look at whatever is in the module, not just
__name__
or what’s declared in a security assertion:>>> m.x 42
Clean up after ourselves:
>>> del sys.modules[modname]