Home > Software engineering >  How to download a file from Flask with send_from_directory?
How to download a file from Flask with send_from_directory?

Time:12-20

Hi I am having trouble downloading a csv file in Flask which is stored in csv_files folder. The structure of the files is as below. I am getting requested url is not found on server error. Please help I am a novice Flask user.

enter image description here

I have an export file route which generates the excel file with a random name. It then redirects to download route. fname is the name of the file. I have made it as global

@app.route("/exportfile",methods=["GET","POST"])
def exportfile():


    if request.method=='GET':

        export_list=End_list.query.all()
        print(export_list)
        global fname
        fname = str(uuid.uuid4())

        outfile = open(f'./csv_files/{fname}.csv', 'w',newline='')
        outcsv = csv.writer(outfile)
        outcsv.writerow(["Sr Number","SK","Quantity","Length","ToolCode","Description"])
        for x in export_list:

             outcsv.writerow([x.srnuml,x.sk,x.quantity,x.length,x.toolcode,x.description.strip()])

        outfile.close()

        return redirect(url_for("download"))

I have a route handling the download. There's a download button in the html which does a POST request.

@app.route("/download",methods=["GET","POST"])
def download():

    if request.method=="GET":
        return render_template("download.html")

    elif request.method=="POST":
        
        return send_from_directory(app.config['UPLOAD_FOLDER'], filename=fname, as_attachment=True, cache_timeout=0)

In my controllers, I have defined the upload folder as below.

import os

basedir = os.path.abspath(os.path.dirname(__file__))


class Config:
    DEBUG = False
    SQLITE_DB_DIR = None
    SQLALCHEMY_DATABASE_URI = None
    SQLALCHEMY_TRACK_MODIFICATIONS = False
    UPLOAD_FOLDER = None

class LocalDevelopmentConfig(Config):
    SQLITE_DB_DIR = os.path.join(basedir)
    SQLALCHEMY_DATABASE_URI = "sqlite:///"   os.path.join(SQLITE_DB_DIR, "toolcodes.sqlite3")
    UPLOAD_FOLDER = basedir "/csv_files"
    DEBUG = True

My download.html is as below:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>

        Download will happen here
        <br><br>
        <form method="POST" action="/download">

            <input name="Download" type="submit" value="Download">

        </form>
        <br>
        <a href="{{url_for('dashboard')}}"> Go to dashboard</a>

</body>
</html>

CodePudding user response:

from flask import send_file

@app.route('/download',methods=["GET","POST"])
def downloadFile(csvFileName): #In your case fname is your filename
    try:
       path = f'./csv_files/{csvFileName}'
       return send_file(path,mimetype='text/csv', attachment_filename=csvFileName, as_attachment=True)
    except Exception as e:
        return str(e)

CodePudding user response:

@app.route("/exportfile",methods=["GET","POST"])
def exportfile():


    if request.method=='GET':

        export_list=End_list.query.all()
        print(export_list)
        global fname
        fname = str(uuid.uuid4())
        session['fname'] = fname # change here

        outfile = open(f'./csv_files/{fname}.csv', 'w',newline='')
        outcsv = csv.writer(outfile)
        outcsv.writerow(["Sr Number","SK","Quantity","Length","ToolCode","Description"])
        for x in export_list:

             outcsv.writerow([x.srnuml,x.sk,x.quantity,x.length,x.toolcode,x.description.strip()])

        outfile.close()

        return redirect(url_for("download"))

retrieve session data in download()

@app.route("/download",methods=["GET","POST"])
def download():


    if request.method=="GET":
        return render_template("download.html")

    elif request.method=="POST":
        if 'fname' in session:
            csvFileName = session['fname']
            return send_from_directory(app.config['UPLOAD_FOLDER'], filename=csvFileName , as_attachment=True, cache_timeout=0)
  • Related