Does Pyramid have a Signal / Slot system

Django has a built-in Signals system, and that would be very useful for the project I'm working on.

I read, although the Pyramid docs seem to have an Events system that is very closely related to signals, but not quite. Will there be something like this work for a general purpose alarm system or should I roll?

+7
source share
1 answer

The event system used by Pyramid fulfills the same use cases as the Signals system. Your application can detect arbitrary events and attach subscribers to them.

To create a new event, define an interface for it:

from zope.interface import ( Attribute, Interface, ) class IMyOwnEvent(Interface): foo = Attribute('The foo value') bar = Attribute('The bar value') 

Then you determine the actual implementation of the event:

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

The interface is actually optional, but helps to document and simplifies the implementation of several implementations. This way you can get away with a lack of interface definition and @implementer parts.

Wherever you want to signal this event, use the registry.notify method; here, I assume that you have a request to access the registry:

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

This will send a request to all registered subscribers; either with config.add_subscriper or with pyramid.events.subscriber :

 from pyramid.events import subscriber from mymodule.events import MyOwnEvent @subscriber(MyOwnEvent) def owneventsubscriber(event): event.foo.spam = 'eggs' 

You can also use the IMyOwnEvent interface instead of the MyOwnEvent class, and your subscriber will be notified of all events that implement the interface, and not just your specific implementation of this event.

Note that notifying subscribers never catches exceptions (e.g. send_robust in Django).

+9
source

All Articles