【问题标题】:Using flask to return multiple dataframes as csv使用烧瓶将多个数据帧返回为 csv
【发布时间】:2023-04-04 19:57:01
【问题描述】:

我有 多个 数据帧,我想使用烧瓶返回 多个 可下载的 CSV 文件。

我尝试了以下代码,但它只能返回 一个 可下载的 CSV 文件。

resp = make_response(df.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=export.csv"
resp.headers["Content-Type"] = "text/csv"
return resp

我尝试返回多个响应 (return resp1, resp2) 但收到以下错误:

TypeError: %d format: a number is required, not Response

任何帮助将不胜感激,谢谢!

【问题讨论】:

  • 你不能只用烧瓶做到这一点。您可以压缩文件并返回一个文件。或者你需要编写前端 javascript 代码来下载它们。
  • @Tristan 我使用 zip 文件尝试过它并且它工作正常。谢谢!

标签: python python-3.x pandas csv flask


【解决方案1】:

我得到了答案,实际上没有办法只使用烧瓶一次返回所有文件,所以我制作了一个包含所有 CSV 的 zip 文件,然后返回它。

import zipfile

with zipfile.ZipFile('main_code/output.zip', 'w') as csv_zip:
    csv_zip.writestr("data1.csv", data1.to_csv())
    csv_zip.writestr("data2.csv", data2.to_csv())

return send_file('output.zip',
                 mimetype='zip',
                 attachment_filename='output.zip',
                 as_attachment=True)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-02-22
    • 2018-05-11
    • 2022-01-26
    • 2022-08-06
    • 1970-01-01
    • 2019-03-23
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多