我从 Flask View 中的远程 URL 获取一个 zip 文件并将其返回。当使用请求访问 Flask View 并保存文件时,我尝试打开文件时收到错误。但是,如果我在终端中执行 View 的操作,那么它似乎可以工作。为什么我会收到此错误?
caution: zipfile comment truncated
error [logFiles.zip]: missing 3232528480 bytes in zipfile
(attempting to process anyway)
解压Flask View 中构建的文件失败。
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
是“响应内容,以字节为单位。”.text
是“响应内容,以 unicode 表示。”
由于您需要字节流,因此请使用.content
。
关于python - 无法解压通过 Flask 应用程序中的请求检索到的文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32485903/