Create an online CSV file in Google App Engine

I use the Google App Engine (python), I want my users to be able to download a CSV file generated using some data from the data store (but I do not want them to download all this, order columns and more).

I need to use the csv module because there may be cells containing commas. But the problem is that if I do this, I will need to write a file that is not allowed in the Google App Engine

I currently have something like this:

tmp = open("tmp.csv", 'w') writer = csv.writer(tmp) writer.writerow(["foo", "foo,bar", "bar"]) 

So, I think what I would like to do is either process cells with commas, or use the csv module without writing a file, since this is not possible in GAE ..

+4
source share
3 answers

I found a way to use the CSV module for GAE! There he is:

 self.response.headers['Content-Type'] = 'application/csv' writer = csv.writer(self.response.out) writer.writerow(["foo", "foo,bar", "bar"]) 

This way you do not need to write any files

+15
source

Here is a complete example of using the Python CSV module in GAE. I usually use it to create a csv file from a gql request and ask the user to save or open it.

 import csv class MyDownloadHandler(webapp2.RequestHandler): def get(self): q = ModelName.gql("WHERE foo = 'bar' ORDER BY date ASC") reqs = q.fetch(1000) self.response.headers['Content-Type'] = 'text/csv' self.response.headers['Content-Disposition'] = 'attachment; filename=studenttransreqs.csv' writer = csv.writer(self.response.out) 

create line shortcuts

  writer.writerow(['Date', 'Time','User' ]) 

repeat query returning each instance as a string

  for req in reqs: writer.writerow([req.date,req.time,req.user]) 

Add the appropriate mapping so that clicking on the link opens a file dialog box

 ('/mydownloadhandler',MyDownloadHandler), 
+6
source
 import StringIO tmp = StringIO.StringIO() writer = csv.writer(tmp) writer.writerow(["foo", "foo,bar", "bar"]) contents = tmp.getvalue() tmp.close() print contents 
+3
source

All Articles