【问题标题】:Stackexchange API encodingStackexchange API 编码
【发布时间】:2016-06-06 12:51:24
【问题描述】:

我正在为 Stackexchange API 编写以下装饰器:

    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"
                with urllib.request.urlopen(url % look_up_pattern) as so_response:
                response = so_response.read()
            print(response)
            self.write(response)

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

作为response,我得到字节流:

b'\x1f\x8b\x08\x00\x00\x00\x00\x00\x04\x00\xb5\\\x0b\x93\xa3F\x92\xfe+u\xe...

问题是谁编码响应?什么是正确的 Unicode 来解码?我检查了 utf-8、utf-16、zlib.decompress 等。它没有帮助。

【问题讨论】:

标签: python encoding stackexchange-api


【解决方案1】:

Daniel Roseman 链接到的答案的相关部分是这样的:

if response.info().get('Content-Encoding') == 'gzip':
    buf = StringIO( response.read())
    f = gzip.GzipFile(fileobj=buf)
    data = f.read()

换句话说,编码应该是response.info().get('Content-Encoding')

【讨论】:

    猜你喜欢
    • 2014-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 1970-01-01
    • 2015-06-11
    • 2016-07-20
    • 1970-01-01
    相关资源
    最近更新 更多