Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Pyramid have a Signal/Slot system

Django happens to have a Signals system built in and it would be quite useful for a project I'm working on.

I've been reading though the Pyramid docs and it does appear to have an Events system which is tied very closely to Signals, but not quite. Would something like this work for a general purpose signal system or should I roll my own?

like image 871
William Chambers Avatar asked Jun 24 '12 09:06

William Chambers


1 Answers

The events system used by Pyramid fulfils the exact same use-cases as the Signals system. Your application can define 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')

You then define an 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 documentation and makes it easier to provide multiple implementations. So you could get away with omitting the interface definition and @implementer parts altogether.

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

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

This'll send the request to any subscribers you've registered; 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, not just your specific implementation of that event.

Note that notifying subscribers never catches exceptions (like send_robust in Django would do).

like image 59
Martijn Pieters Avatar answered Oct 03 '22 12:10

Martijn Pieters