I’m running a WebSocketHandler with Tornado, and I have a while loop inside the Handler. This loop blocks everything – which is very bad. How can I make the tailstream() function asynchronous (a.k.a. non-blocking)? (As it is now, tailstream blocks everything, and makes even new websocket connections impossible. I need it to run for each websocket connection.)
(...)
class WSHandler(tornado.websocket.WebSocketHandler):
connections = []
filters = {}
def allow_draft76(self):
# for iOS 5.0 Safari
return True
def open(self):
self.write_message('open')
self.count = db.my_collection.count() - 1
self.cursor = coll.find(tailable=True, await_data=True, skip=self.count)
self.tailstream()
def on_message(self, message):
print message
def on_close(self):
self.connections.remove(self)
self.cb.stop()
print 'connection closed'
@tornado.web.asynchronous
def tailstream(self):
while self.cursor.alive:
try:
doc = self.cursor.next()
self.print2web(doc)
except StopIteration:
time.sleep(1)
(...)
I think
whilenot blocking it. Buttime.sleepdo!Replace it with
yield gen.Task(IOLoop.instance().add_timeout, time.time() + 5)from this answer.If it will not help – we can think about whole structure of solution.