【问题标题】:Tornado: asynchronous endpointsTornado:异步端点
【发布时间】:2016-06-06 13:28:07
【问题描述】:

我有以下代码:

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

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

【问题讨论】:

    标签: python asynchronous tornado


    【解决方案1】:

    由于async_get 是协程,它返回Future 对象。为了获得“真实”的结果,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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-19
      • 2016-02-23
      • 2011-06-23
      相关资源
      最近更新 更多