python - Server sent events with Flask and Tornado -
i have been playing around sending server sent events flask , tornado. took @ blog article:
https://s-n.me/blog/2012/10/16/realtime-websites-with-flask/
i decided try writing own flask app send server sent events exercise. here code flask app called sse_server.py:
#! /usr/bin/python flask import flask, request, response, render_template tornado.wsgi import wsgicontainer tornado.httpserver import httpserver tornado.ioloop import ioloop app = flask(__name__) def event_stream(): count = 0 while true: print 'data: {0}\n\n'.format(count) yield 'data: {0}\n\n'.format(count) count += 1 @app.route('/my_event_source') def sse_request(): return response( event_stream(), mimetype='text/event-stream') @app.route('/') def page(): return render_template('index.html') if __name__ == '__main__': print "please open web browser http://127.0.0.1:5000." # spin app http_server = httpserver(wsgicontainer(app)) http_server.listen(5000) ioloop.instance().start()
in templates folder, have simple index.html page:
<!doctype html> <html> <head> <meta charset="utf-8" /> <title>test</title> <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script> <script type="text/javascript" src="../static/sse_client.js"></script> </head> <body> <h3>test</h3> <ul id="output"> </ul> </body> </html>
in static folder, have file called sse_client.js:
var queue = []; var interval = setinterval(function(){additem()}, 1000); function additem(){ if(queue.length > 0){ var item = queue[0]; queue.shift(); $('#output').append(item); } } $(document).ready( function() { var sse = new eventsource('/my_event_source'); console.log('blah'); sse.onmessage = function(event) { console.log('a message has arrived!'); var list_item = '<li>' + event.data + '</li>'; console.log(list_item); queue.push(list_item); }; })
basically, app's structure is
sse/ sse_server.py static/ sse_client.js templates/ index.html
the app displays index page, data not getting streamed it. have no idea doing wrong. think need set of eyes on this. i'm sure it's minor , stupid.
tornado's wsgicontainer not support streaming responses wsgi apps. can either use flask multi-threaded or greenlet-based wsgi server, or use tornado's native requesthandler interface, not when you're combining flask , tornado wsgicontainer.
combining flask , tornado not idea; see https://github.com/mitsuhiko/flask/issues/986
Comments
Post a Comment