python - 无法解压通过 Flask 应用程序中的请求检索到的文件

标签 python flask zip python-requests

我从 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/

相关文章:

python - 如何在 Python 中得到 10**20 + 10**-20 的精确结果?它给了我 1e+20

javascript - Flask + Celery + socketio 运行时错误 : Working outside of request context

actionscript-3 - AS3 Air — 检查 Zip 以获取音频文件

java - 如何在写入文件时压缩文件?

Python scrapy ReactorNotRestartable 替代品

amazon-web-services - S3 存储桶策略使特定的子文件夹公开而其他所有内容都是私有(private)的?

python - pyapns - hexlified_token_str

python - Pandas /pyplot 散点图 : set axis labels not working

python - 使用 TaskFlowAPI 在 Apache Airflow 中进行分支

python - Flask-SQLAlchemy - 按关注者数量显示顺序