events |
UserPreferences |
The PEAK Developers' Center | FrontPage | RecentChanges | TitleIndex | WordIndex | SiteNavigation | HelpContents |
This module supports event sources, listeners, subscriptions, generator-based pseudothreads ("tasks"), scheduling, and I/O events. Using 'peak.events', you can write event-driven code in a more natural, sequential, "untwisted" style, but without giving up access to Twisted's many great features. 'peak.events' can use PEAK's built-in event loop, or adapt a Twisted reactor for use as an event loop. You can also use Twisted's "Deferred" objects as event sources, which means you can use them in your Tasks (pseudothreads).
To use PEAK's event system it's pretty straught forward. You create an event source, you subscribe to its event and then wait for the event to be triggered. The event source we are going to use is called Broadcaster, we'll talk about it more a bit further.
#!python from peak.events.api import * source = Broadcaster () def callback (source, event): print "Helo world!" canceller = subscribe (source, callback) source.send (None)
The canceller object is a reference to our subscription, once the reference is lost our subscrition os lost too. We can cancel our subscription explicitly by calling the canceller object.
Two event sources are called Distributer and Broadcaster. An event source it's what you have to subscribe to listen for the events they send.
The difference between Distributer and a Broadcaster is a very simple one. You may assign more then one listener (or callback) to an event source. When the event source generates a given event it will iterate over it's listeners, by the order they were subscribed, and send the event to each one. In the case of a Distributer when one of its listeners returns True the iteration stops.
#!python from peak.events.api import * source_dist = Distributer () source_bcst = Broadcaster () def callback1 (source, event): print "Hello from callback1" return True def callback2 (source, event): print "hello from callback2" c1 = subscribe (source_dist, callback1) c2 = subscribe (source_dist, callback2) c3 = subscribe (source_bcst, callback1) c4 = subscribe (source_bcst, callback2) source_dist.send (None) source_bcst.send (Nine)
The output of this snippet is going to be:
Hello from callback1 Hello from callback1 Hello from callback2