Python3.6で '_io.BytesIO' をバイトのようなオブジェクトに変換しますか? 質問する

Python3.6で '_io.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':
        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」をバイトのようなオブジェクトに変換するにはどうすればいいでしょうか?

ベストアンサー1

これはファイルのようなオブジェクトです。以下をお読みください:

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

入ってくるデータがbody大きすぎてメモリに読み込めない場合は、コードをリファクタリングしてzlib.decompressobjの代わりにzlib.decompress

おすすめ記事