Flask:如何向客户端发送动态生成的zipfile

时间:2022-06-21 09:34:28

I am looking for a way to send a zipfile to the client that is generated from a requests response. In this example, I send a JSON string to a url which returns a zip file of the converted JSON string.

我正在寻找一种方法将zipfile发送到客户端,该方法是从请求响应生成的。在此示例中,我将一个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'})

But my zip file is empty and the error returned by flask is

但是我的zip文件是空的,而烧瓶返回的错误是

Debugging middleware caught exception in streamed response at a point where response 
headers were already sent

1 个解决方案

#1


6  

You should return the file directly, not a ZipFile() object:

您应该直接返回文件,而不是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'})

The response you receive is indeed a zipfile, but there is no point in having Python parse it and give you unzipped contents, and Flask certainly doesn't know what to do with that object.

你收到的回复确实是一个zip文件,但没有必要让Python解析它并给你解压缩内容,而Flask肯定不知道如何处理该对象。

#1


6  

You should return the file directly, not a ZipFile() object:

您应该直接返回文件,而不是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'})

The response you receive is indeed a zipfile, but there is no point in having Python parse it and give you unzipped contents, and Flask certainly doesn't know what to do with that object.

你收到的回复确实是一个zip文件,但没有必要让Python解析它并给你解压缩内容,而Flask肯定不知道如何处理该对象。