Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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
like image 727
camdenl Avatar asked Oct 22 '14 17:10

camdenl


1 Answers

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.

like image 187
Martijn Pieters Avatar answered Oct 22 '22 09:10

Martijn Pieters