玩蛇网提供最新Python编程技术信息以及Python资源下载!
您现在的位置: 玩蛇网首页 > Python问题解答 > 正文内容

tornado内使用Future中数据用什么方法

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()

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()

玩蛇网文章,转载请注明出处和文章网址:http://www.iplaypy.com/wenda/wd18550.html

相关文章 Recommend

玩蛇网Python互助QQ群,欢迎加入-->: 106381465 玩蛇网Python新手群
修订日期:2017年06月05日 - 19时12分02秒 发布自玩蛇网

我要分享到:

必知PYTHON教程 Must Know PYTHON Tutorials

必知PYTHON模块 Must Know PYTHON Modules