Skip to content

Instantly share code, notes, and snippets.

@sharoonthomas
Created June 5, 2013 08:07
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sharoonthomas/5712336 to your computer and use it in GitHub Desktop.
Save sharoonthomas/5712336 to your computer and use it in GitHub Desktop.
Example of SSE using flask. The html template should be in the templates folder
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="//code.jquery.com/jquery-1.8.0.min.js"></script>
<script type="text/javascript">
$(document).ready(
function() {
sse = new EventSource('/my_event_source');
sse.onmessage = function(message) {
console.log('A message has arrived!');
$('#output').append('<li>'+message.data+'</li>');
}
})
</script>
</head>
<body>
<h2>Demo</h2>
<ul id="output">
</ul>
</body>
</html>
#!/usr/bin/env python
import gevent
import gevent.monkey
from gevent.pywsgi import WSGIServer
gevent.monkey.patch_all()
from flask import Flask, Response, render_template
import redis
app = Flask(__name__)
def event_stream():
rc = redis.Redis()
ps = rc.pubsub()
ps.subscribe(['chat:tarun'])
for item in ps.listen():
if item['type'] == 'message':
yield 'data: %s:%s\n\n' % (item['channel'], item['data'])
@app.route('/my_event_source')
def sse_request():
return Response(event_stream(), mimetype='text/event-stream')
@app.route('/')
def page():
return render_template('sse.html')
if __name__ == '__main__':
http_server = WSGIServer(('127.0.0.1', 8001), app)
http_server.serve_forever()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment