Flask:如何将动态生成的zipfile发送到客户端 [英] Flask: how to send a dynamically generate zipfile to the client

查看:270
本文介绍了Flask:如何将动态生成的zipfile发送到客户端的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找一种将zipfile发送到由请求响应生成的客户端的方法.在此示例中,我将JSON字符串发送到url,该URL返回转换后的JSON字符串的zip文件.

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'})

但是我的zip文件为空,并且flask返回的错误是

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

推荐答案

您应直接返回文件 ,而不是ZipFile()对象:

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'})

您收到的响应确实是一个zipfile,但是让Python解析它并为您提供解压缩的内容毫无意义,而且Flask当然不知道该对象的用途.

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.

这篇关于Flask:如何将动态生成的zipfile发送到客户端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆