无法解压缩在 Flask 应用程序中使用 Requests 检索到的文件

Can't unzip file retrieved with Requests in Flask app

我正在 Flask 视图中从远程 url 获取一个 zip 文件并将其返回。当使用请求访问 Flask 视图并保存文件时,我在尝试打开文件时遇到错误。但是,如果我在终端中执行视图的操作,它似乎会起作用。为什么会出现此错误?

caution:  zipfile comment truncated
error [logFiles.zip]:  missing 3232528480 bytes in zipfile
(attempting to process anyway)

解压在 Flask 视图中构建的文件失败。

file_name = request.args.get('logFile')
log_file = requests.get(url, params=request_params, stream=True)
response = make_response(log_file.text)
response.headers['Content-Type'] = "application/octet-stream"
response.headers["Content-Disposition"] = "attachment; filename={0}".format(file_name)
return response

解压缩终端中内置的文件可以正常工作。

response = requests.get(url, params=request_params, stream=True)
with open('zipfile.zip', 'wb') as handle:
    handle.write(response.content)
return handle

我也试过将内容类型更改为 application/zip 但我得到了相同的结果。

在第一种情况下,您使用了 .text:

response = make_response(log_file.text)

在第二种情况下,您使用了 .content:

handle.write(response.content)

.content is "Content of the response, in bytes." .text 是“响应内容,采用 unicode。

既然要字节流,就用.content.