我正在寻找一种方法来将压缩文件发送到从请求响应生成的客户端。在此示例中,我将 JSON 字符串发送到 URL,该 URL 返回转换后的 JSON 字符串的 zip 文件。
@app.route('/sendZip', methods=['POST'])
def sendZip():
content = '{"type": "Point", "coordinates": [-105.01621, 39.57422]}'
data = {'json' : content}
r = requests.post('http://ogre.adc4gis.com/convertJson', data = data)
if r.status_code == 200:
zipDoc = zipfile.ZipFile(io.BytesIO(r.content))
return Response(zipDoc,
mimetype='application/zip',
headers={'Content-Disposition':'attachment;filename=zones.zip'})
但是我的zip文件是空的,flask返回的错误是
Debugging middleware caught exception in streamed response at a point where response
headers were already sent
最佳答案
您应该直接返回文件,而不是 ZipFile()
对象:
r = requests.post('http://ogre.adc4gis.com/convertJson', data = data)
if r.status_code == 200:
return Response(r.content,
mimetype='application/zip',
headers={'Content-Disposition':'attachment;filename=zones.zip'})
您收到的响应确实是一个 zip 文件,但是让 Python 解析它并为您提供解压缩的内容是没有意义的,而且 Flask 当然不知道如何处理该对象。
关于python - 如何将动态生成的 zip 文件发送到客户端,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26513542/