简体   繁体   English

Flask:send_from_directory

[英]Flask: send_from_directory

I am trying to convert json to csv and download a file from my flask application.我正在尝试将 json 转换为 csv 并从我的 flask 应用程序下载一个文件。 The function does not work correctly, I always get the same csv, even if I delete the json file. function 不能正常工作,我总是得到相同的 csv,即使我删除了 json 文件。 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_from_directory()使用send_file()从给定目录发送文件。 send_file() sets the cache_timeout option. send_file()设置cache_timeout选项。

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.注意:如果您的文件在 static 中(该文件只能在项目目录中),第一个参数给它的目录名称如 static,第二个参数写入文件的正确路径。 The file will be automatically downloaded, if the route got download.如果路由下载,文件将自动下载。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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