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.
JavaScript
x
11
11
1
@app.route('/sendZip', methods=['POST'])
2
def sendZip():
3
content = '{"type": "Point", "coordinates": [-105.01621, 39.57422]}'
4
data = {'json' : content}
5
r = requests.post('http://ogre.adc4gis.com/convertJson', data = data)
6
if r.status_code == 200:
7
zipDoc = zipfile.ZipFile(io.BytesIO(r.content))
8
return Response(zipDoc,
9
mimetype='application/zip',
10
headers={'Content-Disposition':'attachment;filename=zones.zip'})
11
But my zip file is empty and the error returned by flask is
JavaScript
1
3
1
Debugging middleware caught exception in streamed response at a point where response
2
headers were already sent
3
Advertisement
Answer
You should return the file directly, not a ZipFile()
object:
JavaScript
1
6
1
r = requests.post('http://ogre.adc4gis.com/convertJson', data = data)
2
if r.status_code == 200:
3
return Response(r.content,
4
mimetype='application/zip',
5
headers={'Content-Disposition':'attachment;filename=zones.zip'})
6
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.