Push notifications with Flask, EventSource and Redis

  1. Save the file below as push_notifications.py
  2. Run python push_notifications.py
  3. Open a bunch of browsers pointing to http:localhost:5000/
  4. Open up each browser’s console window.
  5. Hit submit in one, the rest should update.


import flask, redis
app = flask.Flask(__name__)
red = redis.StrictRedis(host='localhost', port=6379, db=0)
def event_stream():
    pubsub = red.pubsub()
    for message in pubsub.listen():
        print message
        yield 'data: %snn' % message['data']
@app.route('/post', methods=['POST'])
def post():
    red.publish('notifications', 'Hello!')
    return flask.redirect('/')
def stream():
    return flask.Response(event_stream(),
def index():
    return '''
        var source = new EventSource('/stream');
        source.onmessage = function (event) {
    <form method="POST" action="/post">
        <input type="submit"/>
if __name__ == '__main__':
    app.debug = True

You need to have Flask and redis installed:

sudo apt-get install python-pip redis-server
sudo pip install flask redis