简体   繁体   中英

Flask: send_from_directory

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM