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

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 

    return response


Add Comment




Are you human? + three = 10