Recently I've found that there's no reasonable simple and useful Redis pub sub examples around. So, here is my dead simple wrapper how to implement it without any unnecessary overhead.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class PubSub(object): | |
""" | |
Very simple Pub/Sub pattern wrapper | |
using simplified Redis Pub/Sub functionality. | |
Usage (publisher):: | |
import redis | |
r = redis.Redis() | |
q = PubSub(r, "channel") | |
q.publish("test data") | |
Usage (listener):: | |
import redis | |
r = redis.Redis() | |
q = PubSub(r, "channel") | |
def handler(data): | |
print "Data received: %r" % data | |
q.subscribe(handler) | |
""" | |
def __init__(self, redis, channel="default"): | |
self.redis = redis | |
self.channel = channel | |
def publish(self, data): | |
self.redis.publish(self.channel, json.dumps(data)) | |
def subscribe(self, handler): | |
redis = self.redis.pubsub() | |
redis.subscribe(self.channel) | |
for data_raw in redis.listen(): | |
if data_raw['type'] != "message": | |
continue | |
data = json.loads(data_raw["data"]) | |
handler(data) |
"This is not a class. It's looks like a class, the name is in noun, 'greeting', ok that's kind of class like. It takes arguments and stores data in __init__(), all right that's kind of class like. It has a method that uses that state to do something else, all right that feels like a class.
ReplyDeleteThis is not a class, or it shouldn't be a class."
You know where this is from? This is from a Python core developer. He said this in a talk called "Stop Writing Classes": https://www.youtube.com/watch?v=o9pEzgHorH0
Ahaha, yeah, indeed. It can be something like http://pastie.org/5980505
DeleteBut it rather looks like black magic. The one of purposes why I use classes is to keep my code easy readable. Concept of the classes fit my concern very well.
I think you misunderstod what the previous author meant.
DeleteThe point is, you have only two methods that share a redis connection and a string, so they can be just that: two functions without a class. No need to put them in a class and no need to emulate class behavior.
And of course god forbid you CamelName your functions :)
Thanks - this is a good example and one of the only ones I could find for this. Not sure why the redis.py folks gloss over pub/sub in their docs.
ReplyDelete