Eric
Eric

Reputation: 85

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

I'm using Python 2.7 + flask in a Google App Engine standard instance to get .xlsx files from a bucket. When I hit my download route it returns the correct data but the file name is just simply "download" and the file is not recognized as a .xlsx file. I can open the file in Excel and the data does show correctly, however.

I've tried writing the data to a io.StringIO and then calling send_file with that data structure but it gave me the same problems as before.

This is my route.

@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")

This is the function which fetches the cloudstorage.storage_api.ReadBuffer object.

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')

Instead of the file being named "test.xlsx" the file is named "download" and isn't recognized as an Excel file.

Any help is appreciated.

Upvotes: 3

Views: 6769

Answers (1)

BenDog
BenDog

Reputation: 386

the file is being called download because that's the path you have set.

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

If you don't have the ability to control the users' requests you should be able to define a false filename by using a redirect, otherwise just use the new route for download as defined.

Try something like this?

...
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")

Upvotes: 2

Related Questions