How to Download a CSV File in Flask

To get Flask to download a CSV file to the user, we pass a CSV string to the make_response function, which returns a response object. Then we add a header which tells the browser to accept the file as a download. The mimetype also must be set to text/csv in order to get the web browser to save it in something other than an HTML document.

from flask import Flask, make_response  
app = Flask(__name__)

@app.route('/csv/')  
def download_csv():  
    csv = 'foo,bar,baz\nhai,bai,crai\n'  
    response = make_response(csv)
    cd = 'attachment; filename=mycsv.csv'
    response.headers['Content-Disposition'] = cd 
    response.mimetype='text/csv'

    return response

Comments

Add Comment

Name

Email

Comment

Are you human? * ten = 40


Name: vinod

Creation Date: 2018-08-14

does it work for an SPA frontend?