转换为'_io.BytesIO';到python3.6中类似字节的对象?
我使用这个函数来解压缩主体或HTTP响应(如果它是用gzip、compress或deflate压缩的)转换为'_io.BytesIO';到python3.6中类似字节的对象?,python,python-3.x,typeerror,zlib,bytesio,Python,Python 3.x,Typeerror,Zlib,Bytesio,我使用这个函数来解压缩主体或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':
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)
从本质上讲,如何将“\u io.BytesIO”转换为类似字节的对象?它是一个类似文件的对象。读一下:
>>> b = io.BytesIO(b'hello')
>>> b.read()
b'hello'
如果从
body
输入的数据太大,无法读入内存,则需要重构代码并使用而不是zlib。如果先写入对象,请确保在读取之前重置流:
>>> 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'
当你过度思考一个基本的解决方案时:D