Gugmi
Gugmi

Reputation: 325

Flask send_file is sending old file instead of newest

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

Upvotes: 12

Views: 10925

Answers (2)

Ayush Goyal
Ayush Goyal

Reputation: 31

@ritlew pretty much answers the question, to add to his answer, After adding cache_timeout=0, clear the browser cache and hit the URL in incognito mode.

You can also try:

Disabling caching in Flask

Upvotes: 1

ritlew
ritlew

Reputation: 1682

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

Upvotes: 35

Related Questions