在python3.6中,如何将'\io.BytesIO'转换为类似字节的对象?

2024-05-29 05:14:00 发布

您现在位置:Python中文网/ 问答频道 /正文

如果用gzip、compress或deflate压缩body或HTTP响应,我将使用此函数来解压缩它。

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'转换为类似字节的对象?

谢谢


Tags: 函数iohttpreturntypebodycompressorcompress
2条回答

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

>>> 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(b'hello')
>>> b.read()
b'hello'

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

相关问题 更多 >

    热门问题