python - tornado 里面如何使用Future中的数据?
巴扎黑
巴扎黑 2017-04-17 15:16:30
0
1
297

tonado官方文档(http://www.tornadoweb.org/en/stable/gen.html)
可以通过定义以下方法获取异步返回值:
@gen.coroutine
def fetch_json(url):
response = yield AsyncHTTPClient().fetch(url)
raise gen.Return(json_decode(response.body))

但是以下代码调用fetch_json方法,得到一个数据(tornado.concurrent.Future),在get方法里面怎么获取返回的response.body的值?

class TestHandler(BaseHtHandler):
@asynchronous
def get(self):
log.info("TestHandler.get")
self.set_header("Access-Control-Allow-Origin", "*")
response=self.fetch_json("http://www.baidu.com")
self.finish()

巴扎黑
巴扎黑

reply all(1)
黄舟
from tornado.web import RequestHandler, Application, asynchronous
from tornado.ioloop import IOLoop
from tornado.httpserver import HTTPServer
from tornado import gen
from tornado.httpclient import AsyncHTTPClient

class IndexHandler(RequestHandler):
    @asynchronous
    @gen.coroutine
    def get(self):
        response = self.fetch_json('http://www.qq.com')
        result = yield response
        self.write(result)
        self.finish()

    @gen.coroutine
    def fetch_json(self, url):
        response = yield AsyncHTTPClient().fetch(url)
        raise gen.Return(response.body)

app = Application([('/', IndexHandler)], debug = True)
http_server = HTTPServer(app)
http_server.listen(1888)
IOLoop.instance().start()

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!