-
-
Save mehmetkose/6388401 to your computer and use it in GitHub Desktop.
Multiple Websocket Handler in Tornado
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
class UpdateHandler(tornado.websocket.WebSocketHandler,BaseHandler): | |
#cache = [] | |
brain = {} | |
cache_size = 200 | |
listenners = {} | |
def allow_draft76(self): | |
# for iOS 5.0 Safari | |
return True | |
@tornado.web.asynchronous | |
def open(self,url): | |
self.url = url | |
if not url == "me": | |
try: | |
UpdateHandler.listenners[url].append(self) | |
except KeyError, e: | |
UpdateHandler.listenners[url] = [] | |
UpdateHandler.listenners[url].append(self) | |
else: | |
for tag in self.current_user["tags"]: | |
try: | |
UpdateHandler.listenners[tag].append(self) | |
except KeyError, e: | |
UpdateHandler.listenners[tag] = [] | |
UpdateHandler.listenners[tag].append(self) | |
@tornado.web.asynchronous | |
def on_close(self): | |
if not self.url == "me": | |
UpdateHandler.listenners[self.url].remove(self) | |
else: | |
for tag in self.current_user["tags"]: | |
UpdateHandler.listenners[tag].remove(self) | |
@tornado.web.asynchronous | |
def update_cache(self, feed): | |
#self.cache.insert(0,feed) | |
for tag in feed["parsed_tags"]: | |
try: | |
UpdateHandler.brain[tag].insert(0,feed) | |
except KeyError, e: | |
UpdateHandler.brain[tag] = [] | |
UpdateHandler.brain[tag].insert(0,feed) | |
#if len(self.cache) > self.cache_size: | |
# self.cache = self.cache[-self.cache_size:] | |
@tornado.web.asynchronous | |
def send_updates(self, feed): | |
for tag in feed["parsed_tags"]: | |
try: | |
for waiter in self.listenners[tag]: | |
try: | |
waiter.write_message(feed) | |
except: | |
logging.error("Error sending message", exc_info=True) | |
except Exception, e: | |
pass | |
def on_message(self, message): | |
#logging.info("got message %r", message) | |
parsed = tornado.escape.json_decode(message) | |
feed = { | |
"id": str(uuid.uuid4()), | |
"body": parsed["body"], | |
"tag": parsed["tag"], | |
"parsed_tags": self.backend.tag_process(parsed["tag"]), | |
} | |
feed["html"] = self.render_string("message.html", message=feed) | |
UpdateHandler.update_cache(self, feed) | |
UpdateHandler.send_updates(self, feed) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment