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

Dan*_*Dan 7 python zlib typeerror bytesio python-3.x

我正在使用此函数解压缩正文或HTTP响应(如果使用gzip对其进行了压缩,压缩或放气)。

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
Run Code Online (Sandbox Code Playgroud)

但是python抛出此错误消息。

TypeError: a bytes-like object is required, not '_io.BytesIO'
Run Code Online (Sandbox Code Playgroud)

在这条线上:

return zlib.decompress(body)
Run Code Online (Sandbox Code Playgroud)

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

谢谢

Ale*_*cha 28

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

>>> 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'
Run Code Online (Sandbox Code Playgroud)

或直接获取数据 getvalue

>>> b.getvalue()
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x06\xcf\x00\x00\x03W\x08\x02\x00'
Run Code Online (Sandbox Code Playgroud)


wim*_*wim 9

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

>>> b = io.BytesIO(b'hello')
>>> b.read()
b'hello'
Run Code Online (Sandbox Code Playgroud)

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


Nwa*_*ume 5

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 ...
Run Code Online (Sandbox Code Playgroud)

  • 请添加上下文来说明*为什么*这是一个答案。 (2认同)