我在 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”,而是被命名为“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")
关于python - Flask send_file() 返回正确的 .xlsx 数据但文件名不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55601701/