python - Subscribe and unsubscribe to channels after the connection has been made with txredisapi -
working python, twisted, redis , txredisapi.
how can subscriberprotocol subscribe , unsubscribe channels after connection has been made?
i guess need instance of subscriberprotocol , can use "subscribe" , "unsubscribe" methods don't know how it.
code example:
import txredisapi 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 outside of these classes:
# need sub/unsub here! (not inside de protocol) protocolinstance = redislistenerprotocol # here problem protocolinstance.subscribe("newchannelname") protocolinstance.unsubscribe("channelname")
any suggestion?
thanks!
the next code solves problem:
@defer.inlinecallbacks def subunsub(): deferred = yield clientcreator(reactor, redislistenerprotocol).connecttcp(host, port) deferred.subscribe("newchannelname") deferred.unsubscribe("channelname")
explanation: use "clientcreator" instance of subscriberprotocol inside function flag "@defer.inlinecallbacks" , don't forget "yield" keyword wait complete deferred data. can use deferred suscribe , unsubscribe.
in case forgot yield keyword, deferred wasn't complete , method suscribe , unsubscribe didn't work.
connecting = clientcreator(reactor, redislistenerprotocol).connecttcp(host, port) def connected(listener): listener.subscribe("newchannelname") listener.unsubscribe("channelname") connecting.addcallback(connected)
Comments
Post a Comment