1

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?

davidism
  • 121,510
  • 29
  • 395
  • 339
xyro
  • 465
  • 1
  • 6
  • 25

1 Answers1

1

Look at send_file function. You just need to create a file in the memory on the fly.

This snippet should do the work for your case!

Hope this will help.

Hett
  • 2,023
  • 3
  • 16
  • 19