tags:

views:

564

answers:

3

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
+6  A: 

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
+5  A: 

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
This helps, but the file has the name "suggest.csv.html" Any idea how to fix that?
Eric the Red
with both response headers (content type and content disposition) set properly? What browser is exhibiting this peculiar .html - appending behavior?
Alex Martelli
+2  A: 

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