Omi
Omi

Reputation: 75

Downloading csv attachment in flask (from dataframe)

So I want to download csv as attachment but I am able to see it on browser itself and not as attachment. Here is my flask code -

@app.route('/submit', methods=['POST'])
    *Some Code*
    df = calc.get_data(prdrop,fr_value,sumprfit,fitids) # got dataframe

    session["df"] = df.to_csv(index=False,header=True, sep=",")
   
   
    return render_template('plot.html',url=plot_url) #renders a plot from html

@app.route("/download", methods=["POST"])
def download():
    df=session["df"]
    return df if "df" in session else ""

the output that I get - enter image description here

I want to get this file as csv, could anyone help on this?

Upvotes: 0

Views: 642

Answers (2)

cizario
cizario

Reputation: 4269

may be you can use send_file() like

def download():
    if df in session:
        df = session["df"]
        return send_file(df,
                         attachment_filename="mycsv.csv",
                         mimetype="text/csv",
                         as_attachment=True)
    else:
        abort(404)

refer to this topic https://flask.palletsprojects.com/en/1.1.x/api/#flask.send_file

Upvotes: 1

Omi
Omi

Reputation: 75

I got the answer -

I should make get_response

def download():
    df = session["df"]
    response = make_response(df)
    cd = 'attachment; filename=mycsv.csv'
    response.headers['Content-Disposition'] = cd
    response.mimetype = 'text/csv'
    return response

Upvotes: 0

Related Questions