Flask send_file正在发送旧文件,而不是最新文件 [英] Flask send_file is sending old file instead of newest

查看:213
本文介绍了Flask send_file正在发送旧文件,而不是最新文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个flask应用程序,其中使用一个Flask route服务器创建一个csv文件并将其保存到服务器.使用客户端页面上的生成按钮,将触发另一个Flask route来获取最新文件,将其移动到tmp文件夹,然后使用send_file将该文件发送给用户.

I have a flask app where using one Flask route the server creates a csv file and saves it to the server. Using a generated button on the client page, another Flask route is triggered to get the most recent file, move it to a tmp folder and send that file to the user using send_file.

现在,当我第一次运行该进程并下载文件时,所有操作都按预期进行.但是,第二次运行该过程时,它将为我提供旧的CSV而不是新生成的CSV.这一直持续到我点击浏览器上的刷新"按钮为止.

Right now, when I run the process the first time and download the file, all works as expected. However, the second time I run the process, it serves me the old CSV instead of the newly generated one. This continues until I hit the refresh button on my browser.

以下是我的应用代码:

from flask import Flask, render_template, flash, redirect, request, url_for, Response, send_file
import os
import time
import shutil
import glob

app = Flask(__name__)
app.config['SECRET_KEY'] = 'secret!'

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/downloadcsv')
def downloadcsv():
    current = os.getcwd()
    try:
        list = glob.glob('{}/*.csv'.format(current))
    except:
        print('No file found')
    basename = os.path.basename(os.path.normpath(max(list, key=os.path.getctime)))
    shutil.move(basename, './tmp/{}'.format(basename))
    return send_file('./tmp/{}'.format(basename), as_attachment=True)

如果需要,以下是生成"下载按钮的JS代码:

In case it is needed, the following is the JS code which "generates" the download button:

var download = '<div id="downloadsection" class="container-contact100-form-btn"><a href="/downloadcsv"><button id="download" class="contact100-form-btn"> <span>DOWNLOAD CSV</span></button></a></div>';

也请让我知道我是否在使下载过程复杂化...

Please also let me know if I am over complicating the download process...

谢谢!

推荐答案

send_file具有未配置的缓存超时.除非您告诉它不要像这样缓存文件,否则它将发送已缓存的文件:

send_file has a caching timeout that you are not configuring. It will send the same file that has been cached unless you tell it not to cache the file like so:

send_file('./tmp/{}'.format(basename), as_attachment=True, cache_timeout=0)

请参阅以下参考资料以获取更多信息:

See the following references for more information:

http://flask.pocoo.org/docs/1.0/api /#flask.send_file

http://flask.pocoo.org/docs/1.0 /api/#flask.Flask.get_send_file_max_age

http://flask.pocoo.org/docs/1.0/config/# SEND_FILE_MAX_AGE_DEFAULT

这篇关于Flask send_file正在发送旧文件,而不是最新文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆