首页 > 解决方案 > 使用烧瓶,第二次 send_file 以获取具有相同路径和名称的更改文件 - 缓存问题?

问题描述

在我们的烧瓶网站上,我们实现了一个“下载”按钮。此按钮调用烧瓶中的一个函数,该函数通过 send_file() 为用户提供一个压缩文件。第一次一切正常。第二次单击该按钮后,用户再次收到完全相同的文件。看起来不错,但是在再次单击按钮时,烧瓶应该发送的文件被更改,旧的文件不再存在。

我试图理解为什么 PyCharm 调试器会发生这种情况,并注意到,在第二次按下下载按钮后,甚至不再调用下载例程。所以我认为在后台进行了某种缓存。我什至删除了要从文件系统发送的文件,然后再次按下“下载”按钮......我找回了原始文件。

也许你们经历过类似的事情,可以帮助我了解您的知识。先感谢您。

下载代码:

@app.route('/download/<expID>')
def download(expID):

 experiment = dbc.getExperiment(int(expID))

# only execute, if owner of experiment calls it AND experiment is NOT running or in queue
 if experiment.getOwner() == cas.username and experiment.getStatus() != 1 and experiment.getStatus() != 2:
    ownerPath = dbc.getUser(experiment.getOwner()).getPath()
    fileName = cas.username + "_" + expID

    # remove old zip (if existing)
    try:
        os.remove(experiment.getPath() + "/" + fileName + ".zip")
    except FileNotFoundError:
        pass

    # create zip in owner folder to work around recursion problem
    make_archive(ownerPath + "/" + fileName, 'zip', root_dir=experiment.getPath(), base_dir=None)

    # move from owner folder to owner/experiment folder
    shutil.move(ownerPath + "/" + fileName + ".zip", experiment.getPath() + "/" + fileName + ".zip");

    # trigger download
    return send_file(
        experiment.getPath()+"/"+fileName + ".zip", as_attachment=True)
 return redirect('/dashboard')

按钮:

<form action="/download/{{experiments[i][0]}}">
                <input type="submit" id="download" value="download" />
            </form>

标签: pythonflask

解决方案


我在 send_file 的文档中找到了解决方案。Flask 确实缓存了您通过 send_file 发送的文件,并且在一定时间内不会访问您之前调用的函数。要限制此行为,您可以使用 cache_timeout 参数。对我来说,它看起来像这样:

return send_file(
            experiment.getPath()+"/"+fileName + ".zip", as_attachment=True, cache_timeout=0)

推荐阅读