Flask: send_from_directory

Viewed 5224

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)
1 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)
Related