首页 > 解决方案 > 从 Flask 下载数据帧为 csv

问题描述

我正在尝试使用按钮单击将数据框下载为 csv,但无法弄清楚如何 - 请帮助我,因为我是烧瓶的新手

这是代码 -

df是我要下载为 csv 的 pandas 数据框

烧瓶代码

@app.route('/submit',methods=['POST'])
def submit():
    
    ** So here is some code for manipulation ** 
    

    df = calc.get_data(prdrop,fr_value,sumprfit,fitids)

    

    return render_template('plot.html',url=plot_url)

Plot.html - 它提供了一些图表和一个按钮,可以将数据表下载为 csv

<body>
    <img src="data:image/png;base64,{{url}}" alt="Chart" height="auto" width="80%">
      <form action="/download" method="POST">
        <input type="Submit" value="Download excel" >
      </form>
</body>

现在我知道我需要一个新的 url 路由来获取那个 df 然后允许用户下载它,请你帮我解决我将如何访问新 url 中的数据框并允许用户将其下载为 csv

标签: pythonpandascsvflask

解决方案


你可以使用会话。例如:

Python 文件

第一部分:

import io
from flask import Flask, render_template, session, send_file
import pandas as pd


app = Flask(__name__)

# Set the secret key to some random bytes and keep it secret.
# A secret key is needed in order to use sessions.
app.secret_key = b"_j'yXdW7.63}}b7"

提交功能:

@app.route("/submit", methods=["GET", "POST"])
def submit():    
    # Example dataframe 
    df = pd.DataFrame(
        data={
            "city": ["Seville", "London", "Berlin"],
            "country": ["Spain", "United Kingdom", "Germany"]
        }
    )
    
    # Store the CSV data as a string in the session
    session["df"] = df.to_csv(index=False, header=True, sep=";")

    return render_template("plot.html")

下载功能:

@app.route("/download", methods=["POST"])
def download():
    # Get the CSV data as a string from the session
    csv = session["df"] if "df" in session else ""
    
    # Create a string buffer
    buf_str = io.StringIO(csv)

    # Create a bytes buffer from the string buffer
    buf_byt = io.BytesIO(buf_str.read().encode("utf-8"))
    
    # Return the CSV data as an attachment
    return send_file(buf_byt,
                     mimetype="text/csv",
                     as_attachment=True,
                     attachment_filename="data.csv")

最后部分:

if __name__ == "__main__":
    app.run()

HTML 文件(模板/plot.html

<body>
    <form action="/download" method="POST">
        <input type="Submit" value="Download CSV" >
    </form>
</body>

推荐阅读