generating a CSV file online on Google App Engine

前端 未结 3 1588
甜味超标
甜味超标 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: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),
    

提交回复
热议问题