Preferred method for downloading a file generated on the fly in Flask
Are you running the flask app behind a front end web server such as nginx or apache (which would be the best way to handle the downloading of files). If you're using nginx you can use the 'X-Accel-Redirect' header. For this example I'll use the directory /srv/static/reports
as the directory you're creating the zipfiles in and wanting to serve them out of.
nginx.conf
in the server
section
server { # add this to your current server config location /reports/ { internal; root /srv/static; }}
your flask method
send the header to nginx to server
from flask import make_response@app.route('/download', methods=['GET','POST'])def download(): error=None # .. if request.method == 'POST': if download_list == None or len(download_list) < 1: error = 'No files to download' return render_template('download.html', error=error, download_list=download_list) else: timestamp = dt.now().strftime('%Y%m%d:%H%M%S') zfname = 'reports-' + str(timestamp) + '.zip' zf = zipfile.ZipFile(downloaddir + zfname, 'a') for f in download_list: zf.write(downloaddir + f, f) zf.close() # TODO: remove zipped files, move zip to archive # tell nginx to server the file and where to find it response = make_response() response.headers['Cache-Control'] = 'no-cache' response.headers['Content-Type'] = 'application/zip' response.headers['X-Accel-Redirect'] = '/reports/' + zf.filename return response
If you're using apache, you can use their sendfile directive http://httpd.apache.org/docs/2.0/mod/core.html#enablesendfile