Flask: send_from_directory

Question:

I am trying to convert json to csv and download a file from my flask application. The function does not work correctly, I always get the same csv, even if I delete the json file. Why?

button:

<a href="/download/wellness" class="btn btn-primary">Download</a>

My method:

@app.route("/download/<file_id>") 
def get_csv(file_id):
    try:
        file_id = f"{file_id}"
        filename_jsonl = f"{file_id}.jsonl"
        filename_csv = f"{file_id}.csv"

        file_id = ''

        with open(filename_jsonl, 'r') as f:
            for line in f.read():
                file_id += line

        file_id = [json.loads(item + 'n}') for item in file_id.split('}n')[0:-1]]

        with open(filename_csv, 'a') as f:
            writer = csv.DictWriter(f, file_id[0].keys(), delimiter=";")
            writer.writeheader()

            for profile in file_id:
                writer.writerow(profile)

        return send_from_directory(directory='', filename=filename_csv, as_attachment=True)
    except FileNotFoundError:
        abort(404)
Asked By: user13368804

||

Answers:

The problem you are having is that the first generated file has been cached.

Official documentation says that send_from_directory() send a file from a given directory with send_file(). send_file() sets the cache_timeout option.

You must configure this option to disable caching, like this:

return send_from_directory(directory='', filename=filename_csv, as_attachment=True, cache_timeout=0)
Answered By: Tobin
@app.route('/download')
def download():
    return send_from_directory('static', 'files/cheat_sheet.pdf')

Note: First parameter give it the directory name like static if your file is inside static (the file only could be in the project directory),
and for the second parameter write the right path of the file. The file will be automatically downloaded, if the route got download.

Answered By: Mohammad zrar
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.