carl carl - 4 months ago 21
Python Question

tar files and download with flask app

I have one tex file and three images and I want that the user can click a button and download all three of them. It would be ideal if the four files would be as one tar file. My download works as follows right now

@app.route('/download_tex', methods=['GET', 'POST'])
def download_tex():
latext_text = render_template('get_lates.html')

filename = 'test'
response = make_response(latext_text)
response.headers["Content-Disposition"] = "attachment; filename=%s.tex" % filename

return response

this works fine for the tex file, but how can I tar up files within the flask app and send the tar file instead?

EDIT: Ok thanks to the comment below I came up with this code

latext_text = render_template('get_latex.html')

latex_file = open(basedir + '/app/static/statistics/latex_%s.tex' % current_user.username, "w")

filename = 'tarfile_%s.tar.gz' % current_user.username
filepath = basedir + '/app/static/statistics/%s' % filename

tar =, "w:gz")
tar.add(basedir + '/app/static/statistics/image1.png')
tar.add(basedir + '/app/static/statistics/image2.png')
tar.add(basedir + '/app/static/statistics/image3.png')
tar.add(basedir + '/app/static/statistics/latex_%s.tex' % current_user.username)

but how can I now download that tar file with the browser?


You should use the send_from_directory method that Flask provides for this =) It is the perfect use case for what you're doing.

What you can do is something like this:

from flask import send_from_directory

# code here ...

filename = 'tarfile_%s.tar.gz' % current_user.username
filedir = basedir + '/app/static/statistics/'

# tar code here ...

return send_from_directory(filedir, filename, as_attachment=True)

That will handle all of the downloading bits for you in a clean way.