Flask 下载以前的文件版本作为响应

问题描述

我正在运行一个 Flask 应用程序,用于下载用户创建的 zip 文件

压缩文件删除/覆盖目录中用户的同名。

然后,当我获得下载链接时,它会下载旧的 zipfile,其中包含无法打开的已删除文件

链接在隐身模式下正常工作。

但是在常规的 chrome 中,请求在提供 zip 文件之前不会到达测试服务器。

有人知道可能是什么问题吗?

@page.route('/response/<id>')
def response(id):
    user = User.query.filter(User.spreadsheet_id.any(id)).first()
    print(user.spreadsheet_id)
    zip_name = f'{user.email}_zip.zip'
    path = ''
    root_dir = os.path.dirname(os.getcwd())
    print(os.path.join(root_dir,'app',zip_name))
    return send_file(os.path.join(root_dir,zip_name),mimetype='zip',attachment_filename=zip_name,as_attachment=True)

解决方法

就我而言,解决方案是将附件包装在 Response 对象中并添加缓存控制标头:

attachment = send_file(os.path.join(root_dir,'app',zip_name),mimetype='zip',attachment_filename=zip_name,as_attachment=True)
resp = make_response(attachment)
resp.cache_control.max_age = 120
return resp