使用Flask将Pandas数据框转换为CSV并提供下载 [英] Use Flask to convert a Pandas dataframe to CSV and serve a download

查看:131
本文介绍了使用Flask将Pandas数据框转换为CSV并提供下载的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Flask应用程序中有一个熊猫数据框,我想以CSV文件的形式返回.

I have a Pandas dataframe in my Flask app that I want to return as a CSV file.

return Response(df.to_csv())

问题是输出显示在浏览器中,而不是作为单独的文件下载.我该如何更改?

The problem is that the output appears in the browser instead of downloading as a separate file. How can I change that?

我也尝试了以下方法,但是它只给出了空的输出​​.

I tried the following as well but it just gave empty output.

response = make_response(df.to_csv())
response.headers['Content-Type'] = 'text/csv'
return Response(response)

推荐答案

设置Content-Disposition告诉浏览器下载文件,而不是在页面上显示其内容.

Set the Content-Disposition to tell the browser to download the file instead of showing its content on the page.

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

这篇关于使用Flask将Pandas数据框转换为CSV并提供下载的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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