使用 Flask 发送多个 CSV 文件? [英] Send with multiple CSVs using Flask?

查看:32
本文介绍了使用 Flask 发送多个 CSV 文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个应用程序,它接收一些信息,使用 Pandas 执行一些计算,并将最终的 Pandas 数据帧转换为 CSV,然后使用 Flask 应用程序下载.如何在一个视图中下载多个 CSV?好像一次只能返回一个响应.

I have an app that takes in some information, performs some calculations using pandas, and turns the final pandas data frame into a CSV that is then downloaded using the Flask app. How do I download multiple CSVs within one view? It seems that I can only return a single response at a time.

示例片段:

def serve_csv(dataframe,filename):
    buffer = StringIO.StringIO()
    dataframe.to_csv(buffer, encoding='utf-8', index=False)
    buffer.seek(0)
    return send_file(buffer,
             attachment_filename=filename,
             mimetype='text/csv')

def make_calculation(arg1, arg2):
   '''Does some calculations.
   input: arg1 - string, arg2- string
   returns: a pandas data frame'''

@app.route('test_app', methods=['GET', 'POST'])
def test_app():
    form = Form1()
    if form.validate_on_submit():
    calculated_dataframe = make_calculation(str(form.input_1.data), str(form.input_2.data))
        return serve_csv(calculated_dataframe, 'Your_final_output.csv')
    return render_template('test_app.html', form=form)

所以让我们在上面的例子中说 make_calculation 返回两个 Pandas 数据帧.我如何将它们都打印到 CSV 文件中?

So let's say in that example above that make_calculation returned two pandas data frames. How would I print both of them to a CSV?

推荐答案

你可以返回一个 MIME Multipart 响应、zip 文件或 TAR 球(请注意链接的 RFC 有点过时,但更容易快速上手,因为它是 HTML 格式;官方是 此处).

You could return a MIME Multipart response, a zip file, or a TAR ball (please note the linked RFC is somewhat out of date, but is easier to quickly get up to speed with because it's in HTML; the official one is here).

如果您选择进行 MIME 多部分响应,一个好的起点可能是查看 MultipartEncoderMultipartDecoderrequests工具带;您可以直接使用它们,或者至少使用它们来创建子类/组合以获得您想要的行为.Zip 文件TAR balls 可以使用标准库模块实现.

If you choose to do a MIME multipart response, a good starting point might be to look at the MultipartEncoder and MultipartDecoder in requests toolbelt; you may be able to use them directly, or at least subclass/compose using those to get your desired behavior. Zip files and TAR balls can be implemented using standard library modules.

另一种方法是设计您的 API,以便您返回 JSON,使用标头(或 XML 元素或 JSON 字段)来指示可以通过另一个请求或类似请求获取其他 CSV.

An alternative would be to design your API so that you were returning JSON, use a header (or XML element or JSON field) to indicate that additional CSVs could be obtained by another request, or similar.

这篇关于使用 Flask 发送多个 CSV 文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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