Skip to content

Instantly share code, notes, and snippets.

@SupermanScott
Created January 22, 2012 19:35
Show Gist options
  • Save SupermanScott/1658409 to your computer and use it in GitHub Desktop.
Save SupermanScott/1658409 to your computer and use it in GitHub Desktop.
Tornado Server-Sent Event handler
class SSEHandler(tornado.web.RequestHandler):
def initialize(self):
self.set_header('Content-Type', 'text/event-stream')
self.set_header('Cache-Control', 'no-cache')
def emit(self, data, event=None):
"""
Actually emits the data to the waiting JS
"""
response = u''
encoded_data = json.dumps(data)
if event != None:
response += u'event: ' + unicode(event).strip() + u'\n'
response += u'data: ' + encoded_data.strip() + u'\n\n'
self.write(response)
self.flush()
@TaylorSMarks
Copy link

If someone is looking for more help at making Server Side Events work, I found these two pages were useful:

https://gist.github.com/mivade/d474e0540036d873047f

https://developer.mozilla.org/en-US/docs/Web/API/Server-sent_events/Using_server-sent_events#event_stream_format

(I link directly to the Event Stream Format section of the above page because that's particularly important. If you don't follow it, it won't work.)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment