Google calendar - download all entries with Python
By andre
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.
client = gdata.calendar.client.CalendarClient(source="my_app/1.0")
client.ssl = True
client.ClientLogin(user, pwd, client.source)
query = gdata.calendar.client.CalendarEventQuery(max_results='99')
feed = client.GetCalendarEventFeed(q=query)
totalCount = int(feed.total_results.text.strip())
print 'Events on Primary Calendar: %s' % (feed.title.text,)
count = 0
entries = []
while feed is not None:
for event in feed.entry:
entries.append(event)
count += 1
if len(event.when) > 0:
when = "{0}-{1}".format(event.when[0].start, event.when[0].end)
else:
when = "<UNKNOWN>"
print '\t%s. %s: %s' % (count, when, event.title.text)
if feed.GetNextLink():
feed = client.GetCalendarEventFeed(uri=feed.GetNextLink().href)
else:
feed = None
print "Total results: predicted=%d, actual=%d" % (totalCount, count)
# Serialize
dest = "/path/to/calendar.json"
f = open(dest, "w")
f.write(jsonpickle.encode(entries))
f.flush()
f.close()