【问题标题】:Tornado @gen.coroutine closes long polling connectionTornado @gen.coroutine 关闭长轮询连接
【发布时间】:2014-12-13 05:24:13
【问题描述】:

您好,我在执行长轮询时遇到了 Tornado 框架的问题。 我的 requesthandler 的 post 方法用@asynchronous@gen.coroutine 装饰。当我让它挂起以调用回调以写回客户端时,连接立即关闭。我看到这与@gen.coroutine 的使用有关,当所有期货都产生时,它会自动调用self.finish()。 我需要这个装饰器,因为我使用的是 Mongo Motor。 下面是一个简短的例子:

@web.asynchronous
@gen.coroutine
def post(self):
  #mongo Motor yielding code  
  notifications.register_callback(self.on_message)

Notifications 是一个全局对象,它保存一组回调,并在接收到来自外部的消息时调用它们。 谢谢

【问题讨论】:

    标签: python tornado long-polling


    【解决方案1】:

    如果你想使用yield 来调用协程,你需要使用@gen.engine 而不是@gen.coroutine,而不是在处理程序结束时自动调用self.finish()@web.asynchronous 装饰器的代码中有一条注释说明了这一点:

    # If @asynchronous is used with @gen.coroutine, (but
    # not @gen.engine), we can automatically finish the
    # request when the future resolves.  Additionally,
    # the Future will swallow any exceptions so we need
    # to throw them back out to the stack context to finish
    # the request.
    

    所以,如果@asynchronous@gen.coroutine 一起使用,它会自动调用self.finish,但如果与@gen.engine 一起使用则会跳过它。

    【讨论】:

    • @Peterdeka 是的,您应该能够使用相同的语法调用motor
    猜你喜欢
    • 1970-01-01
    • 2013-06-12
    • 1970-01-01
    • 1970-01-01
    • 2014-01-22
    • 1970-01-01
    • 1970-01-01
    • 2012-10-11
    • 2012-12-10
    相关资源
    最近更新 更多