我正在尝试获得一个非常简单的初始服务器,它获取一个 url(异步)来工作但它抛出:
Exception: DummyFuture does not support blocking for results
有这个 SO发布但答案不包括运行网络服务器并尝试将 future 添加到我的循环中,如图所示 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'
循环正在运行,返回一个 future 。什么问题?
python 2.7.10
Tornado ==4.4.2
请您参考如下方法:
要从 Future 中获取结果,请在 gen.coroutine 函数中yield,或者在 async 中 native 协程。因此,将 FetchSyncHandler 替换为:await def
class FetchSyncHandler(tornado.web.RequestHandler):
@gen.coroutine
def get(self):
data = yield fetch_coroutine(URL)
self.write(data)
有关详细信息,请参阅我的 Refactoring Tornado Coroutines或 Tornado coroutine guide .
