在 Pyramid 中使用对象事件

警告

此代码仅适用于Pyramid1.1a4+。它也会让你的大脑爆炸。

Zope的组件体系结构支持“对象事件”的概念,即使用上下文对象调用订户的事件。 and 事件对象。

下面是一个通过 @subscriber 装饰师:

 1from zope.component.event import objectEventNotify
 2from zope.component.interfaces import ObjectEvent
 3
 4from pyramid.events import subscriber
 5from pyramid.view import view_config
 6
 7class ObjectThrownEvent(ObjectEvent):
 8    pass
 9
10class Foo(object):
11  pass
12
13@subscriber([Foo, ObjectThrownEvent])
14def objectevent_listener(object, event):
15    print object, event
16
17@view_config(renderer='string')
18def theview(request):
19    objectEventNotify(ObjectThrownEvent(Foo()))
20    objectEventNotify(ObjectThrownEvent(None))
21    objectEventNotify(ObjectEvent(Foo()))
22    return 'OK'
23
24if __name__ == '__main__':
25    from pyramid.config import Configurator
26    from paste.httpserver import serve
27    config = Configurator(autocommit=True)
28    config.hook_zca()
29    config.scan('__main__')
30    serve(config.make_wsgi_app())

这个 objectevent_listener 只有当 object 对象的所有者属于类 Foo . 我们可以这么说,因为只有第一次调用objecteventnotify实际调用订户。第二次和第三次调用ObjectEventNotify时不调用订阅服务器。第二个调用不调用订阅服务器,因为其对象类型为 None (而不是) Foo )第三个调用不调用订阅服务器,因为它的ObjectEvent类型是ObjectEvent(而不是 ObjectThrownEvent )清澈如泥?