Skip to content

Commit 1b5adf9

Browse files
committed
Add on_connection_close hook to chat demo to clean up after closed connections.
Closes tornadoweb#354.
1 parent 12c5699 commit 1b5adf9

File tree

1 file changed

+11
-4
lines changed

1 file changed

+11
-4
lines changed

demos/chat/chatdemo.py

Lines changed: 11 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -62,7 +62,7 @@ def get(self):
6262

6363

6464
class MessageMixin(object):
65-
waiters = []
65+
waiters = set()
6666
cache = []
6767
cache_size = 200
6868

@@ -77,7 +77,11 @@ def wait_for_messages(self, callback, cursor=None):
7777
if recent:
7878
callback(recent)
7979
return
80-
cls.waiters.append(callback)
80+
cls.waiters.add(callback)
81+
82+
def cancel_wait(self, callback):
83+
cls = MessageMixin
84+
cls.waiters.remove(callback)
8185

8286
def new_messages(self, messages):
8387
cls = MessageMixin
@@ -87,7 +91,7 @@ def new_messages(self, messages):
8791
callback(messages)
8892
except:
8993
logging.error("Error in waiter callback", exc_info=True)
90-
cls.waiters = []
94+
cls.waiters = set()
9195
cls.cache.extend(messages)
9296
if len(cls.cache) > self.cache_size:
9397
cls.cache = cls.cache[-self.cache_size:]
@@ -114,7 +118,7 @@ class MessageUpdatesHandler(BaseHandler, MessageMixin):
114118
@tornado.web.asynchronous
115119
def post(self):
116120
cursor = self.get_argument("cursor", None)
117-
self.wait_for_messages(self.async_callback(self.on_new_messages),
121+
self.wait_for_messages(self.on_new_messages,
118122
cursor=cursor)
119123

120124
def on_new_messages(self, messages):
@@ -123,6 +127,9 @@ def on_new_messages(self, messages):
123127
return
124128
self.finish(dict(messages=messages))
125129

130+
def on_connection_close(self):
131+
self.cancel_wait(self.on_new_messages)
132+
126133

127134
class AuthLoginHandler(BaseHandler, tornado.auth.GoogleMixin):
128135
@tornado.web.asynchronous

0 commit comments

Comments
 (0)