Add on_connection_close hook to chat demo to clean up after closed connections.

Closes #354.
This commit is contained in:
Ben Darnell 2011-09-08 22:51:45 -07:00
parent 12c5699eb7
commit 1b5adf99e4
1 changed files with 11 additions and 4 deletions

View File

@ -62,7 +62,7 @@ class MainHandler(BaseHandler):
class MessageMixin(object): class MessageMixin(object):
waiters = [] waiters = set()
cache = [] cache = []
cache_size = 200 cache_size = 200
@ -77,7 +77,11 @@ class MessageMixin(object):
if recent: if recent:
callback(recent) callback(recent)
return return
cls.waiters.append(callback) cls.waiters.add(callback)
def cancel_wait(self, callback):
cls = MessageMixin
cls.waiters.remove(callback)
def new_messages(self, messages): def new_messages(self, messages):
cls = MessageMixin cls = MessageMixin
@ -87,7 +91,7 @@ class MessageMixin(object):
callback(messages) callback(messages)
except: except:
logging.error("Error in waiter callback", exc_info=True) logging.error("Error in waiter callback", exc_info=True)
cls.waiters = [] cls.waiters = set()
cls.cache.extend(messages) cls.cache.extend(messages)
if len(cls.cache) > self.cache_size: if len(cls.cache) > self.cache_size:
cls.cache = cls.cache[-self.cache_size:] cls.cache = cls.cache[-self.cache_size:]
@ -114,7 +118,7 @@ class MessageUpdatesHandler(BaseHandler, MessageMixin):
@tornado.web.asynchronous @tornado.web.asynchronous
def post(self): def post(self):
cursor = self.get_argument("cursor", None) cursor = self.get_argument("cursor", None)
self.wait_for_messages(self.async_callback(self.on_new_messages), self.wait_for_messages(self.on_new_messages,
cursor=cursor) cursor=cursor)
def on_new_messages(self, messages): def on_new_messages(self, messages):
@ -123,6 +127,9 @@ class MessageUpdatesHandler(BaseHandler, MessageMixin):
return return
self.finish(dict(messages=messages)) self.finish(dict(messages=messages))
def on_connection_close(self):
self.cancel_wait(self.on_new_messages)
class AuthLoginHandler(BaseHandler, tornado.auth.GoogleMixin): class AuthLoginHandler(BaseHandler, tornado.auth.GoogleMixin):
@tornado.web.asynchronous @tornado.web.asynchronous