【问题标题】:Flask: how to send a dynamically generate zipfile to the clientFlask:如何将动态生成的 zipfile 发送到客户端
【发布时间】:2014-12-18 06:17:52
【问题描述】:

我正在寻找一种向客户端发送从请求响应生成的压缩文件的方法。在此示例中,我将 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

【问题讨论】:

标签: python json flask zipfile


【解决方案1】:

您应该直接返回文件,而不是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 肯定不知道如何处理该对象。

【讨论】:

    猜你喜欢
    • 2013-02-12
    • 2015-03-26
    • 2021-12-27
    • 1970-01-01
    • 2018-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多