11

I'm trying to return a CSV from an action in my webapp, and give the user a prompt to download the file or open it from a spreadsheet app. I can get the CSV to spit out onto the screen, but how do I change the type of the file so that the browser recognizes that this isn't supposed to be displayed as HTML? Can I use the csv module for this?

import csv

def results_csv(self):

    data = ['895', '898', '897']

    return data
Eric the Red
  • 5,364
  • 11
  • 49
  • 63

3 Answers3

12

To tell the browser the type of content you're giving it, you need to set the Content-type header to 'text/csv'. In your Pylons function, the following should do the job:

response.headers['Content-type'] = 'text/csv'

PAG
  • 1,836
  • 1
  • 18
  • 19
9

PAG is correct, but furthermore if you want to suggest a name for the downloaded file you can also set response.headers['Content-disposition'] = 'attachment; filename=suggest.csv'

Alex Martelli
  • 854,459
  • 170
  • 1,222
  • 1,395
8

Yes, you can use the csv module for this:

import csv
from cStringIO import StringIO

...

def results_csv(self):
    response.headers['Content-Type'] = 'text/csv'
    s = StringIO()
    writer = csv.writer(s)
    writer.writerow(['header', 'header', 'header'])
    writer.writerow([123, 456, 789])
    return s.getvalue()
Marius Gedminas
  • 11,010
  • 4
  • 41
  • 39