从“_io.BytesIO”转换为 python3.6 中的类似字节的对象?

Convert from '_io.BytesIO' to a bytes-like object in python3.6?

如果正文或 HTTP 响应是使用 gzip、compress 或 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

但是 python 抛出此错误消息。

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

这一行:

return zlib.decompress(body)

本质上,如何从“_io.BytesIO”转换为类似字节的对象?

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

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

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

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

>>> 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'
b = io.BytesIO()
image = PIL.Image.open(path_to_image) # ie 'image.png'
image.save(b, format='PNG')
b.getbuffer().tobytes() # b'\x89PNG\r\n\x1a\n\x00 ...