python - 如何在 Tornado.WebSocket 类中异步运行循环函数?

标签 python asynchronous tornado

我正在使用 Tornado 运行 WebSocketHandler,并且我在处理程序中有一个 while 循环。这个循环阻止了一切——这非常糟糕。如何使 tailstream() 函数异步(又名非阻塞)? (就像现在一样,tailstream 会阻止所有内容,甚至无法建立新的 websocket 连接。我需要它为每个 websocket 连接运行。)

(...)
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)



    (...)       

最佳答案

我认为 while 不会阻止它。但是 time.sleep 可以!

将其替换为 yield gen.Task(IOLoop.instance().add_timeout, time.time() + 5) 来自 answer .

如果它没有帮助 - 我们可以考虑解决方案的整体结构。

关于python - 如何在 Tornado.WebSocket 类中异步运行循环函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12664306/

相关文章:

javascript - async.auto 中的竞争条件

iOS - Swift - 返回异步检索值的函数

python服务器和node.js web客户端连接

python - 设置为 numpy 数组切片时如何禁用大小更改广播?

python - 从 xml 文件中提取标签和属性

c++ - 未存储返回值时,std::async 不会产生新线程

python - 更新 tondb 连接时区而不生成新连接

python - 如何将 Peewee 与 Tornado 完美结合使用

python - 如何在 Tornado 中立即发送 GET 响应?

python - 忽略前 N 个命中的 pycharm 断点