Created
January 22, 2012 19:35
-
-
Save SupermanScott/1658409 to your computer and use it in GitHub Desktop.
Tornado Server-Sent Event handler
This file contains 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
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() |
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
(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
You can just inherit like so: