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
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.
If you have data in pandas DataFrame then you can use . to_csv() function from pandas to export your data in CSV .
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 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'
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With