Tech and travel

Workout

2008-04-23

My Google App Engine application is a workout followup utility. You can enter your times or distances, and the results are shown in list. Graphs were added using the Google Chart API. The URL is http://workoutfollowup.appspot.com/ (note : you will have to login with your Google ID).

One of the things added recently is the ability to download the results as a csv file. The following code snippet shows how to do this. The key thing is setting the Content-Disposition header, this tells the browser that a csv file is coming. The browser will then show a dialog box, where you can specify where you want to save the file. Otherwise the code is pretty standard Python : the standard csv module is used to create a csv file in memory in the StringIO object.

class CsvPage(webapp.RequestHandler):
    def get(self):
      user = users.get_current_user()
      if user:
        output = StringIO.StringIO()
        writer=csv.writer(output, dialect='excel')
        query = db.GqlQuery("""SELECT *
                                 FROM Workout
                                WHERE added_by = :1
                                ORDER BY date DESC """,
                            users.get_current_user())

        writer.writerow(['date', 'minutes', 'distance', 'calories'])
        for workout in query:
            row=[workout.date.strftime("%x"), workout.minutes, \
                     workout.distance, workout.calories]
            writer.writerow(row)

        self.response.headers["Content-Type"] = "application/x-csv"
        self.response.headers['Content-Disposition'] = 'attachment;' \
                                       'filename=workouts.csv'
        self.response.out.write(output.getvalue())
        output.close()
      else:
        self.redirect(users.create_login_url(self.request.uri))

Lines with \ at the end are continued on the next line, in the standard Python fashion.

Copyright (c) 2024 Michel Hollands