Tornado:DummyFuture 不支持阻塞结果 [英] Tornado: DummyFuture does not support blocking for results

查看:18
本文介绍了Tornado:DummyFuture 不支持阻塞结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图获得一个非常简单的初始服务器,它获取一个 url(异步)工作,但它抛出:

I am trying to get a very simple initial server which fetches a url (asynchronously) to work but it throws:

Exception: DummyFuture does not support blocking for results

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

There's this SO post but the answers do not include running a web server and trying to add the future to my loop as shown here throws:

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'

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

The loop is running, a future is returned. What is the issue?

Python 2.7.10
龙卷风==4.4.2

推荐答案

要从 Future 获得结果,yieldgen.coroutine 函数中,或 awaitasync def 原生协程中.因此,将您的 FetchSyncHandler 替换为:

To get a result from a Future, yield it in a gen.coroutine function, or await it in an async def native coroutine. So replace your FetchSyncHandler with:

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

有关更多信息,请参阅我的重构 Tornado 协程Tornado 协程指南.

For more information, see the my Refactoring Tornado Coroutines or the Tornado coroutine guide.

这篇关于Tornado:DummyFuture 不支持阻塞结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆