Python tar文件和flask应用程序下载

Python tar文件和flask应用程序下载,python,flask,Python,Flask,我有一个tex文件和三个图像,我希望用户可以点击一个按钮,下载所有这三个。如果这四个文件作为一个tar文件,那将是理想的。我的下载工作如下现在 @app.route('/download_tex', methods=['GET', 'POST']) @login_required def download_tex(): latext_text = render_template('get_lates.html') filename = 'test' response =

我有一个tex文件和三个图像,我希望用户可以点击一个按钮,下载所有这三个。如果这四个文件作为一个tar文件,那将是理想的。我的下载工作如下现在

@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
这对tex文件很好,但是如何在flask应用程序中对文件进行tar处理并发送tar文件呢

编辑:好的,感谢下面的评论,我想出了这个代码

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()
但是我现在如何用浏览器下载tar文件呢?

您应该使用Flask为此提供的方法=)这是您所做工作的最佳用例

您可以这样做:

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)
这将以干净的方式为您处理所有下载位。