2012-06-24 26 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)。