Last active
December 19, 2015 04:18
-
-
Save mgaitan/5896086 to your computer and use it in GitHub Desktop.
See http://stackoverflow.com/a/13429719 for an explanation on why uses StreamingHttpResponse
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 (django) side: | |
from django.http import StreamingHttpResponse | |
import time | |
def stream(request): | |
def event_stream(): | |
while True: | |
time.sleep(3) | |
yield 'data: %s\n\n' % 'hola mundo' | |
return StreamingHttpResponse(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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment