Skip to content

Instantly share code, notes, and snippets.

@mgaitan
Last active December 19, 2015 04:18
Show Gist options
  • Save mgaitan/5896086 to your computer and use it in GitHub Desktop.
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
# 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