Created
June 15, 2015 16:44
-
-
Save stevenewey/fea5c9f224e50ada7f82 to your computer and use it in GitHub Desktop.
Redis pubsub to Server Sent Events (EventSource)
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
import json | |
import redis | |
from flask import Flask, g, stream_with_context, Response | |
r = redis.StrictRedis() | |
app = Flask(__name__) | |
@app.teardown_request | |
def teardown_request(exception): | |
if 'pubsub' in g: | |
g.pubsub.close() | |
def event_stream(): | |
for message in g.pubsub.listen(): | |
yield 'data: {}\n\n'.format(json.dumps({ | |
'channel': message['channel'], | |
'data': message['data'], | |
})) | |
@app.route('/subscribe/<match>') | |
def subscribe(match): | |
g.pubsub = r.pubsub() | |
if match == 'all': | |
g.pubsub.psubscribe('*') | |
elif match == 'events': | |
g.pubsub.psubscribe('*_events') | |
elif match == 'rbevents': | |
g.pubsub.psubscribe('*_rbevents') | |
else: | |
g.pubsub.subscribe(match) | |
return Response( | |
stream_with_context(event_stream()), mimetype='text/event-stream') | |
if __name__ == '__main__': | |
app.run('0.0.0.0', debug=True) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment