= 20kb),则会抛出 IOError。 以下是读取并解压请求体的代码: @pos-6ren">
gpt4 book ai didi

python - Bottle/Python - 尝试解压缩请求正文时出现 "IOError: [Errno 9] read() on write-only GzipFile object"

转载 作者:行者123 更新时间:2023-11-30 23:06:58 25 4
gpt4 key购买 nike

我使用 Bottle 来接收压缩后的请求正文。当请求的大小很小时,一切都很好。但是,如果请求正文的大小稍大(例如,>= 20kb),则会抛出 IOError。

以下是读取并解压请求体的代码:

@post("/receive")
def receive():
try:
f = request.body
g_f = gzip.GzipFile(fileobj=f)
content = g_f.read()
# other stuff on the content...
except IOError, e:
# handle the error

错误信息是:

[2015-09-07 16:27:27,967][ERROR   ] Failed to decompress gzipped data: [Errno 9] read() on write-only GzipFile object
127.0.0.1 - - [07/Sep/2015 16:27:27] "POST /receive HTTP/1.1" 400 756

最佳答案

此问题是由于创建GzipFile对象所用的fileobj的读/写模式的继承导致的。

如果 request.body 的大小小于 20k,Bottle 会将整个二进制数据加载为 StringIO 对象。 GzipFile 处理 StringIO 非常好,一切正常。

另一方面,如果request.body的大小大于20k,Bottle将使用tempfile模块创建一个该请求体的临时文件,为了平台一致性,tempfile 创建的文件的默认模式是“w+b”。

但是,GzipFile 判断文件是否可读只能通过 hasattr(fileobj, 'mode') 获取的模式字符串,如果该字符串类似于 'rxx',GzipFile 认为它是可读的,反之亦然。如果调用不可读的GzipFileread()函数,将会抛出IOError

由于 GzipFile 将使用的文件模式为“w+b”,因此 GzipFile 仍会将其视为“不可读” ',所以,繁荣!抛出错误。要解决此问题,只需在创建 GzipFile 对象时添加 mode 参数即可:

try:
f = request.body
g_f = gzip.GzipFile(fileobj=f, mode='rb')
content = g_f.read()
# other stuff on the content...
except IOError, e:
# handle the error

关于python - Bottle/Python - 尝试解压缩请求正文时出现 "IOError: [Errno 9] read() on write-only GzipFile object",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32434352/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com