Question

Working with Python, Twisted, Redis and txredisapi.

How can I get the SubscriberProtocol for subscribe and unsubscribe to channels after the connection has been made?

I guess I need to get the instance of the SubscriberProtocol and then I can use "subscribe" and "unsubscribe" methods but don't know how to get it.

Code example:

import txredisapi as redis

class RedisListenerProtocol(redis.SubscriberProtocol):
    def connectionMade(self):
        self.subscribe("channelName")
    def messageReceived(self, pattern, channel, message):
        print "pattern=%s, channel=%s message=%s" %(pattern, channel, message)
    def connectionLost(self, reason):
        print "lost connection:", reason

class RedisListenerFactory(redis.SubscriberFactory):
    maxDelay = 120
    continueTrying = True
    protocol = RedisListenerProtocol

Then from outside of these classes:

# I need to sub/unsub from here! (not from inside de protocol)
protocolInstance = RedisListenerProtocol  # Here is the problem
protocolInstance.subscribe("newChannelName")
protocolInstance.unsubscribe("channelName")

Any suggestion?

Thanks!


The next code solves the problem:

@defer.inlineCallbacks
def subUnsub():
    deferred = yield ClientCreator(reactor, RedisListenerProtocol).connectTCP(HOST, PORT)
    deferred.subscribe("newChannelName")
    deferred.unsubscribe("channelName")

Explanation: Use "ClientCreator" to get an instance of SubscriberProtocol inside a function with the flag "@defer.inlineCallbacks" and don't forget the "yield" keyword for wait to complete the deferred data. Then you can use this deferred to suscribe and unsubscribe.

In my case I forgot the yield keyword, so the deferred wasn't complete and the method suscribe and unsubscribe didn't work.

Was it helpful?

Solution

connecting = ClientCreator(reactor, RedisListenerProtocol).connectTCP(HOST, PORT)
def connected(listener):
    listener.subscribe("newChannelName")
    listener.unsubscribe("channelName")
connecting.addCallback(connected)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top