Flask: how to send a dynamically generate zipfile to the client

自闭症网瘾萝莉.ら 提交于 2019-12-21 04:28:22

问题


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.

@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

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

回答1:


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

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.



来源:https://stackoverflow.com/questions/26513542/flask-how-to-send-a-dynamically-generate-zipfile-to-the-client

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!