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

原文由 Dan 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 889
2 个回答

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

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

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

原文由 wim 发布,翻译遵循 CC BY-SA 4.0 许可协议

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

 >>> 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'

原文由 Alexander Pacha 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题