python - Can't call result() on futures in tornado -
i want asynchronous http-requests using python library tornado (version 4.2). can not force future complete (using result()
) since exception: "dummyfuture not support blocking results".
i have python 3.4.3 therefore future support should part of standard library. documentation of concurrent.py
says:
tornado use
concurrent.futures.future
if available; otherwise use compatible class defined in module.
a minimal example trying provided below:
from tornado.httpclient import asynchttpclient; future = asynchttpclient().fetch("http://google.com") future.result()
if understand problem correctly occurs because import of concurrent.futures.future
somehow not used. relevant code in tornado appears in concurrent.py
not making progress on understanding problem lies.
try create future
, use add_done_callback
:
from tornado.concurrent import future def async_fetch_future(url): http_client = asynchttpclient() my_future = future() fetch_future = http_client.fetch(url) fetch_future.add_done_callback( lambda f: my_future.set_result(f.result())) return my_future
but still need solve future ioloop, this:
# -*- coding: utf-8 -*- tornado.concurrent import future tornado.httpclient import asynchttpclient tornado.ioloop import ioloop def async_fetch_future(): http_client = asynchttpclient() my_future = future() fetch_future = http_client.fetch('http://www.google.com') fetch_future.add_done_callback( lambda f: my_future.set_result(f.result())) return my_future response = ioloop.current().run_sync(async_fetch_future) print(response.body)
another way this, using tornado.gen.coroutine
decorator, this:
# -*- coding: utf-8 -*- tornado.gen import coroutine tornado.httpclient import asynchttpclient tornado.ioloop import ioloop @coroutine def async_fetch_future(): http_client = asynchttpclient() fetch_result = yield http_client.fetch('http://www.google.com') return fetch_result result = ioloop.current().run_sync(async_fetch_future) print(result.body)
coroutine
decorator causes function return future
.
Comments
Post a Comment