def _sub_channel(self, channel): """ Subscribe to a channel using a defer. This call will queue channel subscriptions. @param channel: the desired channel. """ if self._subscribed['subscribed'].get(channel): # already subcribed return defer.succeed(True) if self._subscribed['running']: # call it later, queue it d = self._subscribed['defer'] d.addCallback(self._get_sub_channel_cb(channel)) return d def set_subscribed(*args): ''' Called when channel was subscribed. ''' self._subscribed['running'] = False self._subscribed['subscribed'][channel] = True return True self._subscribed['running'] = True self.redis.subscribe(channel) d = defer.Deferred() self._subscribed['defer'] = d self._subscribed['running_for'] = channel return d.addCallback(set_subscribed)
def register_handler(self, evt, handler): """ Register a function to respond to feed events. Event types/handler params: - create handler(feedname) - newfeed handler(feedname) - delete handler(feedname) - delfeed handler(feedname) - feed.publish:[feed] handler(id, item) - feed.retract:[feed] handler(id) - feed.edit:[feed] handler(id, item) @param evt: The name of the feed event. @param handler: The function for handling the event. """ channel = self._evt2channel(evt) if not channel: return defer.succeed(None) def _register_callback(*args): """ Called when channel was subscribed. """ id_ = self._handlers['id_gen'].next() # store map id -> channel self._handlers['id2channel'][id_] = channel handlers = self._handlers['channel_handlers'].get(channel) if not handlers: handlers = self._handlers['channel_handlers'][channel] = OrderedDict() # store handler handlers[id_] = handler return id_ return self._sub_channel(channel).addCallback(_register_callback)