Last active
March 13, 2018 19:26
-
-
Save mklymyshyn/4674091 to your computer and use it in GitHub Desktop.
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) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment