
我的下载是使用Flask API的send_from_directory启动的.相关测试代码:
@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' 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 return send_from_directory(downloaddir,zfname,as_attachment=True) return render_template('download.HTML',error=error,download_List=download_List) 更新:作为解决方法,我现在正在加载一个新的页面与按钮单击,这让用户启动下载(使用send_from_directory),然后返回到更新的列表.
解决方法 您是否在前端Web服务器(如Nginx或apache)上运行烧瓶应用程序(这将是处理文件下载的最佳方式).如果您使用Nginx,您可以使用 ‘X-Accel-Redirect’标题.对于这个例子,我将使用目录/ srv / static / reports作为您正在创建zip文件的目录,并希望将它们提供给它们.Nginx.conf
在服务器部分
server { # add this to your current server config location /reports/ { internal; root /srv/static; }} 你的烧瓶方法
发送头到Nginx到服务器
from flask import make_response@app.route('/download','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',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 如果您使用apache,可以使用其sendfile指令http://httpd.apache.org/docs/2.0/mod/core.html#enablesendfile
总结以上是内存溢出为你收集整理的html – 在Flask中下载生成的文件的首选方法全部内容,希望文章能够帮你解决html – 在Flask中下载生成的文件的首选方法所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)