Tornado:DummyFuture不支持阻止结果

时间:2017-02-23 20:13:37

标签: python tornado

我正在尝试获取一个非常简单的初始服务器,该服务器获取一个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

1 个答案:

答案 0 :(得分:1)

要从Future获取结果,yieldgen.coroutine函数中,或awaitasync 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