Created
June 25, 2013 17:59
-
-
Save fisadev/5860754 to your computer and use it in GitHub Desktop.
flask simple SSE example
This file contains hidden or 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
# python (flask) side: | |
import time | |
from flask import Response | |
app = Flask(__name__) | |
@app.route('/event_stream') | |
def stream(): | |
def event_stream(): | |
while True: | |
time.sleep(3) | |
yield 'data: %s\n\n' % 'hola mundo' | |
return Response(event_stream(), mimetype="text/event-stream") | |
######################## | |
# html side: | |
''' | |
<script> | |
var source = new EventSource('/event_stream'); | |
source.onmessage = function(event){ | |
alert(event.data); | |
}; | |
</script> | |
''' | |
# if you want to support older browsers, also include this in your html: | |
# https://github.com/remy/eventsource-h5d/blob/master/public/EventSource.js |
Para más info sobre este patrón http://flask.pocoo.org/docs/patterns/streaming/ y sobre sse http://www.html5rocks.com/en/tutorials/eventsource/basics/
acá una simple corrección a la versión django, para que funque con middlewares https://gist.github.com/mgaitan/5896086
btw: muestrenlé esto a cualquier empresa que quiera saber por qué tiene que ayudar a sus empleados a ir a conferencias y eventos como PyCamp
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Genial que en django sea igual de simple :)