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

问题描述 投票:1回答:1

我在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”,而不是名为“test.xlsx”的文件,不会被识别为Excel文件。

任何帮助表示赞赏。

python flask mime-types
1个回答
1
投票

该文件被称为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")
© www.soinside.com 2019 - 2024. All rights reserved.