2012-06-24 30 views

回答

9

Pyramid使用的事件系统与Signals系统完全相同的用例。您的应用程序可以定义任意事件并将订阅者附加到它们。

要创建一个新的事件,为它定义一个接口:

from zope.interface import (
    Attribute, 
    Interface, 
    ) 

class IMyOwnEvent(Interface): 
    foo = Attribute('The foo value') 
    bar = Attribute('The bar value') 

然后,您可以定义一个实际执行的事件:

from zope.interface import implementer 

@implementer(IMyOwnEvent) 
class MyOwnEvent(object): 
    def __init__(self, foo, bar): 
     self.foo = foo 
     self.bar = bar 

的接口是可选的,但是帮助文档并使其更容易提供多个实现。所以你完全可以省略接口定义和零件。

无论您想要通知此事件,请使用registry.notify方法;在这里我假设你有一个可用的请求到达注册表:

request.registry.notify(MyOwnEvent(foo, bar)) 

这将请求发送到您注册的任何用户;要么config.add_subscriperpyramid.events.subscriber

from pyramid.events import subscriber 
from mymodule.events import MyOwnEvent 

@subscriber(MyOwnEvent) 
def owneventsubscriber(event): 
    event.foo.spam = 'eggs' 

您还可以使用IMyOwnEvent接口,而不是MyOwnEvent类的,你的用户将被告知实现接口,不只是你的具体执行该事件的所有事件。

请注意,通知订阅者从不捕获异常(如Django中的send_robust)。