python - 从 '_io.BytesIO' 转换为 python3.6 中的类字节对象?

标签 python python-3.x typeerror zlib bytesio

如果使用 gzip、compress 或 deflate 压缩 HTTP 响应主体,我将使用此函数对其进行解压缩。

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

最佳答案

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

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

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

关于python - 从 '_io.BytesIO' 转换为 python3.6 中的类字节对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54137790/

相关文章:

python - 如何使用 bool 掩码在 pandas DataFrame 中用 nan 替换 'any strings'?

python - python源代码中的sys模块在哪里?

python - 伪序列对象 : Exception needed to terminate?

python - 使用 Python 进行 SSH 的最简单方法是什么?

python - 使用 gensim 加载经过训练的 fasttext 模型时出现问题

python - 如何在不重新定义的情况下提取 python 枚举子集?

Ruby 'is_a?' 需要类或模块 (TypeError)

python - TypeError:强制转换为 Unicode:需要字符串或缓冲区

python - 在 Python 中处理多个网络接口(interface)

javascript - react 类型错误未定义