Flask send_file is sending old file instead of newest

大憨熊 提交于 2020-05-12 18:51:51

问题


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.

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.

The following is my app code:

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)

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

Thanks!!


回答1:


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



来源:https://stackoverflow.com/questions/55519452/flask-send-file-is-sending-old-file-instead-of-newest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!