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

PythonPython 3.xTypeerrorZlibBytesio

Python Problem Overview


I am using this function to uncompress the body or a HTTP response if it is compressed with gzip, compress or 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

However python throws this error message.

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

on this line:

return zlib.decompress(body)

Essentially, how do I convert from '_io.BytesIO' to a bytes-like object?

Python Solutions


Solution 1 - Python

It's a file-like object. Read them:

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

If the data coming in from body is too large to read into memory, you'll want to refactor your code and use zlib.decompressobj instead of zlib.decompress.

Solution 2 - Python

In case you write into the object first, make sure to reset the stream before reading:

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

or directly get the data with getvalue

>>> b.getvalue()
b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x06\xcf\x00\x00\x03W\x08\x02\x00'

Solution 3 - Python

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDanView Question on Stackoverflow
Solution 1 - PythonwimView Answer on Stackoverflow
Solution 2 - PythonAlexander PachaView Answer on Stackoverflow
Solution 3 - PythonNwawel A IroumeView Answer on Stackoverflow