烧瓶 send_file() 返回正确的.xlsx数据,但文件名不正确



我在Google App Engine标准实例中使用Python 2.7 + flask从存储桶中获取.xlsx文件。当我点击下载路线时,它会返回正确的数据,但文件名只是简单的"下载",并且该文件无法识别为.xlsx文件。但是,我可以在Excel中打开该文件,并且数据确实正确显示。

我尝试将数据写入io。StringIO,然后使用该数据结构调用send_file,但它给了我与以前相同的问题。

这是我的路线。

@app.route('/download', methods=['GET'])
def download():
    run_id = request.args.get('run_id')
    fp = BucketHelper().get_report_fp(run_id)
    send_file(fp,
             as_attachment=True,
             mimetype='application/vnd.ms-excel',
             attachment_filename="test.xlsx")

这是获取cloudstorage.storage_api的函数。ReadBuffer 对象。

import cloudstorage
from google.appengine.api import app_identity
class BucketHelper:
    def __init__(self):
        self.bucket_path = '/my-bucket/path'
    def get_report_fp(self, run_id):
        filename = "{}/my_report_{}.xlsx".format(self.bucket_path, run_id)
        return cloudstorage.open(filename, mode='rb')

文件不是命名为"test.xlsx",而是名为"下载",并且不被识别为 Excel 文件。

任何帮助,不胜感激。

该文件

被调用download因为这是您设置的路径。

@app.route('/download', methods=['GET'])
def download():

如果您无法控制用户的请求,您应该能够使用重定向定义错误的文件名,否则只需使用定义的新下载路由。

尝试这样的事情?

...
from flask import redirect
...
@app.route('/download', methods=['GET'])
def download_redirect():
    redirect('/download/test.xlsx')
@app.route('/download/<filename>', methods=['GET'])
def download(filename):
    run_id = request.args.get('run_id')
    fp = BucketHelper().get_report_fp(run_id)
    send_file(fp,
             as_attachment=True,
             mimetype='application/vnd.ms-excel',
             attachment_filename="test.xlsx")

最新更新