Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

excel download with Flask-RestPlus?

How to implement an API endpoint to download excel file using Flask-RestPlus?

Previously I had implemented similar function using Pyramid. However that method didn't work here. Here is the old code snippet:

workBook = openpyxl.Workbook()
fileName = 'Report.xls'
response = Response(content_type='application/vnd.ms-excel',
                            content_disposition='attachment; filename=%s' % fileName)
workBook.save(response)
return response

Thanks for the help.

like image 470
Navin Avatar asked Mar 10 '18 10:03

Navin


Video Answer


1 Answers

send_from_directory provides a secure way to quickly expose static files from an upload folder or something similar when using Flask-RestPlus

from flask import send_from_directory
import os

@api.route('/download')
class Download(Resource):
    def get(self):
        fileName = 'Report.xls'
        return send_from_directory(os.getcwd(), fileName, as_attachment=True)

I have assumed file is in current working directory. The path to download file can be adjusted accordingly.

like image 196
kashaziz Avatar answered Sep 22 '22 20:09

kashaziz