Monday, September 21, 2009

Google Calendar API python with Appengine and AuthSub Token.

Connecting to the Google Calendar API using AuthSub and AppEngine took me way too long .. I wish there was more doc on the web :/

First read a lot about this : http://code.google.com/apis/accounts/docs/AuthSub.html  then have a look at this code http://code.google.com/apis/gdata/authsub.html . Read them like .. 3 or 4 times to make sure you feel the Google vibez xD

Once you've done that, you kind of understand a bit more the process of contacting the Google Calendar API using gdata. Yeah .. now you know it's going to be painful !!

This being said, that piece of code should help you a bit :)

The hardest part is not to actually get the token. There are plenty of docs about that. The pain is to turn this token into a Session Token, and understand how AppEngine re-uses it.

All you have to do is add this line to let AppEngine know that the token is stored in the DataStore. This is the MOST important part of the process:
gdata.alt.appengine.run_on_appengine(
self.calendar_client)

With self.calendar_client as a gdata.calendar.service.CalendarService(). Then you get the token info from your url.
    auth_token = gdata.auth.extract_auth_sub_token_from_url(
self.request.uri)

if auth_token:
self.calendar_client.SetAuthSubToken(
self.calendar_client.upgrade_to_session_token(auth_token))

What does this mean ? Please pay attention because this is the important part =)
It turns your one-shot token into a Session Token and stores it into AppEngine in an Entity called TokenCollection.  You cannot access this token as you would access one of your models. You need to add the line showed above : (gdata.alt.appengine.run_on_appengine(
self.calendar_client)
).

Then each time you can just manipulate your calendar without having to worry about your token anymore. AppEngine will manipulate it on its own !

Feel free to contact me if you have any question. This took me a long time to find out so I'd be happy to help if I can.

Cheers,
Martin