Google calendar - download all entries with Python

Google provides APIs to access its data using various languages. You can manipulate Google calendars, contacts, documents etc. Most of the time the usage is pretty straightforward, but sometimes it is not clear how to achieve a specific goal. For example, it took me some time to figure out how to download all events for a given calendar. The main reason behind the difficulty is the upper limit Google places on the number of calendar entries returned by a single query. There are API calls, which help you to overcome this constraint. Below is the relevant code for your enjoyment. It is in Python, but it can be very easily ported into Java or C#.

A note on serialization. For speed of development, I used jsonpickle module. However, you can use any other module or skip serialization altogether if you don't need it and process the events the way you need.

  1. client = gdata.calendar.client.CalendarClient(source="my_app/1.0")
  2. client.ssl = True
  3. client.ClientLogin(user, pwd, client.source)
  4. query = gdata.calendar.client.CalendarEventQuery(max_results='99')
  5. feed = client.GetCalendarEventFeed(q=query)
  6. totalCount = int(feed.total_results.text.strip())
  7. print 'Events on Primary Calendar: %s' % (feed.title.text,)
  8. count = 0
  9. entries = []
  10. while feed is not None:
  11.     for event in feed.entry:
  12.         entries.append(event)
  13.         count += 1
  14.         if len(event.when) > 0:
  15.             when = "{0}-{1}".format(event.when[0].start, event.when[0].end)
  16.         else:
  17.             when = "<UNKNOWN>"
  18.         print '\t%s. %s: %s' % (count, when, event.title.text)
  19.     if feed.GetNextLink():
  20.         feed = client.GetCalendarEventFeed(uri=feed.GetNextLink().href)
  21.     else:
  22.         feed = None
  23.  
  24. print "Total results: predicted=%d, actual=%d" % (totalCount, count)
  25.  
  26. # Serialize
  27. dest = "/path/to/calendar.json"
  28. f = open(dest, "w")
  29. f.write(jsonpickle.encode(entries))
  30. f.flush()
  31. f.close()

Add new comment