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

Flask send_file() returning correct .xlsx data but incorrect filename

我在 Google App Engine 标准实例中使用 Python 2.7 + flask 从存储桶中获取 .xlsx 文件。当我点击我的下载路径时,它 returns 是正确的数据,但文件名只是 "download" 并且文件未被识别为 .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",文件被命名为 "download",并且未被识别为 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")