龙卷风:异步端点

时间:2016-06-06 13:28:08

标签: python asynchronous tornado

我有以下代码:

class StackOverflowHandler(tornado.web.RequestHandler):

    def get(self, look_up_pattern):
        url = "https://api.stackexchange.com/2.2/search?order=desc&sort=votes&intitle=%s&site=stackoverflow"
        response = self.async_get(url)
        print(response)
        self.write(response)

    @gen.coroutine
    def async_get(self, url):
        link = httpclient.AsyncHTTPClient()
        request = httpclient.HTTPRequest(url)
        response = yield link.fetch(request)
        data = response.body.decode('utf-8')
        data = json.loads(data)
        return data

application = tornado.web.Application([
    (r"/search/(.*)", StackOverflowHandler),
])

async_get返回的类型为tornado.concurrent.Future

例外是:

TypeError: write() only accepts bytes, unicode, and dict objects

我是异步编程的新手,请指出我的错误。

1 个答案:

答案 0 :(得分:3)

由于async_get是协程,因此返回Future个对象。为了得到“真实”的结果,必须解决未来 - 它需要屈服。必须将get处理程序的更多内容装饰为异步

class StackOverflowHandler(tornado.web.RequestHandler):

    @gen.coroutine
    def get(self, look_up_pattern):
        url = "https://api.stackexchange.com/2.2/search?order=desc&sort=votes&intitle=%s&site=stackoverflow"
        response = yield self.async_get(url)
        print(response)
        self.write(response)

    @gen.coroutine
    def async_get(self, url):
        link = httpclient.AsyncHTTPClient()
        request = httpclient.HTTPRequest(url)
        response = yield link.fetch(request)
        data = response.body.decode('utf-8')
        data = json.loads(data)
        return data