Skip to content

Instantly share code, notes, and snippets.

@stevenewey
Created June 15, 2015 16:44
Show Gist options
  • Save stevenewey/fea5c9f224e50ada7f82 to your computer and use it in GitHub Desktop.
Save stevenewey/fea5c9f224e50ada7f82 to your computer and use it in GitHub Desktop.
Redis pubsub to Server Sent Events (EventSource)
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