【问题标题】:Tornado: DummyFuture does not support blocking for resultsTornado:DummyFuture 不支持阻止结果
【发布时间】:2017-02-23 20:13:36
【问题描述】:

我正在尝试获取一个非常简单的初始服务器,它可以(异步)获取一个 url 来工作,但它会抛出:

Exception: DummyFuture does not support blocking for results

有这个SO 帖子,但答案不包括运行网络服务器并尝试将未来添加到我的循环中,如here 所示:

RuntimeError: IOLoop is already running

这是完整的代码:

import tornado.web
import tornado.gen
from tornado.httpclient import AsyncHTTPClient
from tornado.ioloop import IOLoop

URL = 'http://stackoverflow.com'


@tornado.gen.coroutine
def fetch_coroutine(url):
    http_client = AsyncHTTPClient()
    response = yield http_client.fetch(url)
    raise tornado.gen.Return(response.body)  # Python2


class MainHandler(tornado.web.RequestHandler):
    def get(self):
        self.write("Hello, world")


class FetchSyncHandler(tornado.web.RequestHandler):
    def get(self):
        data = fetch_coroutine(URL)
        print type(data)  # <class 'tornado.concurrent.Future'>
        self.write(data.result())


def make_app():
    return tornado.web.Application([
        (r"/", MainHandler),
        (r"/async", FetchSyncHandler),
    ])

if __name__ == "__main__":
    app = make_app()
    app.listen(9999)
    print 'starting loop'
    IOLoop.current().start()
    print 'loop stopped'

循环正在运行,返回一个未来。有什么问题?

Python 2.7.10
龙卷风==4.4.2

【问题讨论】:

    标签: python tornado


    【解决方案1】:

    要从 Future 获得结果,yield 它在 gen.coroutine 函数中,或 await 它在 async def 原生协程中。因此,将您的 FetchSyncHandler 替换为:

    class FetchSyncHandler(tornado.web.RequestHandler):
        @gen.coroutine
        def get(self):
            data = yield fetch_coroutine(URL)
            self.write(data)
    

    有关详细信息,请参阅我的Refactoring Tornado CoroutinesTornado coroutine guide

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-11-03
      • 2015-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-08-21
      • 1970-01-01
      • 2014-02-18
      相关资源
      最近更新 更多