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() |
You can just inherit like so:
class EventHandler(SSEHandler):
def get(self):
self.emit("hello")
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
How do I use this? should it be inherited?
When I create a EventSource javascript object it request a GET, what to put in the get?