52

I am using this function to uncompress the body or a HTTP response if it is compressed with gzip, compress or deflate.

def uncompress_body(self, compression_type, body):
    if compression_type == 'gzip' or compression_type == 'compress':
        return zlib.decompress(body)
    elif compression_type == 'deflate':
        compressor = zlib.compressobj(9, zlib.DEFLATED, -zlib.MAX_WBITS)
        compressed = compressor.compress(body)
        compressed += compressor.flush()
        return base64.b64encode(compressed)

    return body

However python throws this error message.

TypeError: a bytes-like object is required, not '_io.BytesIO'

on this line:

return zlib.decompress(body)

Essentially, how do I convert from '_io.BytesIO' to a bytes-like object?

4

2 回答 2

63

它是一个类似文件的对象。阅读它们:

>>> b = io.BytesIO(b'hello')
>>> b.read()
b'hello'

如果来自的数据body太大而无法读入内存,您将需要重构代码并zlib.decompressobj使用zlib.decompress.

于 2019-01-10T22:28:50.123 回答
40

如果您先写入对象,请确保在读取之前重置流:

>>> b = io.BytesIO()
>>> image = PIL.Image.open(path_to_image)
>>> image.save(b, format='PNG')
>>> b.seek(0)
>>> b.read()
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x06\xcf\x00\x00\x03W\x08\x02\x00'

或直接获取数据getvalue

>>> b.getvalue()
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x06\xcf\x00\x00\x03W\x08\x02\x00'
于 2019-09-19T07:46:33.687 回答