簡體   English   中英

從 Flask 下載 dataframe 作為 csv

[英]Download dataframe as csv from Flask

我正在嘗試使用按鈕單擊將 dataframe 下載為 csv 但無法弄清楚如何 - 請幫助我,因為我是 flask 的新手

這是代碼 -

df是 pandas dataframe 我想下載為 csv

Flask碼

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

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)

你可以使用會話。 例如:

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"

提交 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")

下載 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")

最后部分:

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

HTML 文件(模板/plot.html

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM