金字塔有信号/插槽系统吗?



Django碰巧内置了一个信号系统,它对我正在从事的项目非常有用。

我一直在阅读金字塔文档,它似乎确实有一个与信号密切相关的事件系统,但不完全是。这样的东西适用于通用信号系统还是我应该自己滚动?

Pyramid 使用的事件系统满足与信号系统完全相同的用例。应用程序可以定义任意事件并将订阅者附加到这些事件。

要创建新事件,请为其定义接口:

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

该接口实际上是可选的,但有助于文档编制,并使其更容易提供多个实现。因此,您可以省略接口定义并完全@implementer部分。

无论您想在何处发出此事件的信号,请使用 registry.notify 方法;在这里,我假设您有一个可用于访问注册表的请求:

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

这会将请求发送给您注册的任何订阅者;无论是使用 config.add_subscriper 还是使用 pyramid.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那样)。

最新更新