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
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
This is the complete code:
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
tornado==4.4.2
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)
For more information, see the my Refactoring Tornado Coroutines or the Tornado coroutine guide.