简体   繁体   中英

Download dataframe as csv from Flask

I am trying to download the dataframe as csv using button click but unable to figure it out how - Please help me as I am new to flask

here is the code -

df is the pandas dataframe that i want to download as csv

Flask code

@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 - it gives some graph and a button to download the datasheet as 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>

Now I understand that I need a new url route to get that df into that and then allow user to download it, could you please help me out regarding how will I access the dataframe in new url and allow user to download it as csv

Flask:

html: <a href="{{url_for('get_csv', filename= 'some_csv')}}" id="download" class="btn btn-outline-info">Download</a>

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

    df = calc.get_data(prdrop,fr_value,sumprfit,fitids)
    session["some_csv"] = df.to_csv(index=False)
    
    return render_template('plot.html',url=plot_url)
    
    
@app.route("/get_csv/<filename>", methods=['GET', 'POST'])
def get_csv(filename):

    df = session["some_csv"]
    try:
        return send_file(df,
                         mimetype='"text/csv"',
                         as_attachment=True,
                         attachment_filename=filename
                         )

    except FileNotFoundError:
        abort(404)

You could use sessions. For example:

Python file

First part:

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"

Submit function:

@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")

Download function:

@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")

Last part:

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

HTML file ( templates/plot.html )

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM