generating a CSV file online on Google App Engine

前端 未结 3 1590
甜味超标
甜味超标 2021-02-09 22:36

I am using Google App Engine (python), I want my users to be able to download a CSV file generated using some data from the datastore (but I don\'t want them to download the who

相关标签:
3条回答
  • 2021-02-09 23:09
    import StringIO
    
    tmp = StringIO.StringIO()
    writer = csv.writer(tmp)
    
    writer.writerow(["foo", "foo,bar", "bar"])
    contents = tmp.getvalue()
    
    tmp.close()
    print contents
    
    0 讨论(0)
  • 2021-02-09 23:15

    Here is a complete example of using the Python CSV module in GAE. I typically use it for creating a csv file from a gql query and prompting 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 row labels

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

    iterate through query returning each instance as a row

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

    Add the appropriate mapping so that when a link is clicked, the file dialog opens

    ('/mydownloadhandler',MyDownloadHandler),
    
    0 讨论(0)
  • 2021-02-09 23:28

    I found a way to use the CSV module on GAE! Here it is:

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

    This way you don't need to write any files

    0 讨论(0)
提交回复
热议问题