Python Flask Export and Download CSV Error
Question: I am using Python Flask, and I need to export session data to a CSV file and
then prompt to download it

My code is

    
    
    from StringIO import StringIO
    import csv
    
    import web
    
    @app.route('/exportcsv')
    def export_csv():
        data = session
        csv_file = StringIO()
        csv_writer = csv.writer(csv_file)
        csv_writer.writerow(['Name', 'Age', 'Email'])
        for i in data :
            csv_writer.writerow([i[0],i[2],i[3]])
        web.header('Content-Type','text/csv')
        web.header('Content-disposition', 'attachment; filename=it_export.csv')
        return csv_file.getvalue()
    

When trying to export, I am getting this error message

    
    
    in export_csv
        web.header('Content-Type','text/csv')
      File "/Library/Python/2.7/site-packages/web.py-0.37-py2.7.egg/web/webapi.py", line 276, in header
        ctx.headers.append((hdr, value))
    

Which is caused by web.py library, I searched all over to find a solution but
was always getting irrelevant search results.

Any ideas?


Answer: Look at [send_file](http://flask.pocoo.org/docs/0.10/api/#flask.send_file)
function. You just need to create a file in the memory on the fly.

This [snippet](http://flask.pocoo.org/snippets/32/) should do the work for
your case!

Hope this will help.

