Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I return a CSV from a Pylons app?

Tags:

python

csv

pylons

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
like image 715
Eric the Red Avatar asked Apr 26 '09 00:04

Eric the Red


People also ask

How do I save a response to a CSV file in Python?

Use the pandas. read_csv() Function to Download a CSV File From a URL in Python. The read_csv() function from the Pandas module can read CSV files from different sources and store the result in a Pandas DataFrame.

How do I export a CSV file in Jupyter notebook?

If you have data in pandas DataFrame then you can use . to_csv() function from pandas to export your data in CSV .


2 Answers

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'

like image 197
PAG Avatar answered Oct 19 '22 19:10

PAG


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'

like image 31
Alex Martelli Avatar answered Oct 19 '22 19:10

Alex Martelli