tar files and download with flask app
<p>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</p>

<pre><code>@app.route('/download_tex', methods=['GET', 'POST'])
@login_required
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
</code></pre>

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

<p>EDIT: Ok thanks to the comment below I came up with this code </p>

<pre><code>latext_text = render_template('get_latex.html')

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

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

tar = tarfile.open(filepath, "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)
tar.close()
</code></pre>

<p>but how can I now download that tar file with the browser?</p>

<p>You should use the <a href="http://flask.pocoo.org/docs/0.11/api/#flask.send_from_directory" rel="nofollow">send_from_directory</a> method that Flask provides for this =) It is the perfect use case for what you're doing.</p>

<p>What you can do is something like this:</p>

<pre><code>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)
</code></pre>

<p>That will handle all of the downloading bits for you in a clean way.</p>

python flask