Flask redirect page after response is complete

362 Views Asked by At

So I currently have button in my html script that calls the route /return-files. This route returns a response with a zipped file and I also disabled any caching since I had issue with trying to get a new file each time this response is made. This is working well, but since i cannot return multiple things ( a response and a redirect) I cannot refresh my current page after sending the user a the zip file. Now I have read many solutions such as using javascript to create consecutive responses. I am looking for the simplest technique. Source code bellow thanks for all help.

@app.route('/return-files')
def creareturn_files_tut():
    global itemsList
    global clientName
    try:
        if len(itemsList) <= 0:
            flash("The itemList was found to contain no items")
        else:
            taxPercent = 0.13
            ziped = FileHandler(clientName, itemsList, taxPercent)
            file = ziped.addToZip()
            os.remove(ziped.excelFileName)
            os.remove(ziped.wordFileName)
            # os.remove(file)
            itemsList = []
            clientName = None
            response = make_response(send_file(file, file, as_attachment=True))

            # remove cache for the file so that a new file can be sent each time
            response.headers["Cache-Control"] = "no-cache, no-store, must-revalidate"
            response.headers["Pragma"] = "no-cache"
            response.headers["Expires"] = "0"
            response.headers['Cache-Control'] = 'public, max-age=0'

            return response
        # return out
    except Exception as e:
        return str(e)
1

There are 1 best solutions below

0
On

You can use send_from_directory() or send_file() like this:

file = ziped.addToZip()
os.remove(ziped.excelFileName)
os.remove(ziped.wordFileName)
itemsList = []
clientName = None
return send_from_directory(directory='', filename=file, as_attachment=True, cache_timeout=0)

or

file = ziped.addToZip()
os.remove(ziped.excelFileName)
os.remove(ziped.wordFileName)
itemsList = []
clientName = None
return send_file(file, cache_timeout=0, as_attachment=True)

Note that caching is disabled by setting cache_timeout to 0.