In my previous post I described how to use Google’s federated login to get an oAuth access token. Now that we’ve stored our access token, we’re going to want to use it in future requests to access the user’s data. Here’s how:
# set up service
gdata_service = gdata.service.GDataService()
gdata_service.SetOAuthInputParameters(gdata.auth.OAuthSignatureMethod.HMAC_SHA1, settings.GOOGLE_CONSUMER_KEY, settings.GOOGLE_CONSUMER_SECRET)
# build access_token object and signed request
scopes = [settings.GOOGLE_ANALYTICS_ACCOUNT_URI, settings.GOOGLE_ANALYTICS_DATA_URI]
oauth_input_params = gdata.auth.OAuthInputParams(gdata.auth.OAuthSignatureMethod.HMAC_SHA1, settings.GOOGLE_CONSUMER_KEY, settings.GOOGLE_CONSUMER_SECRET)
access_token = gdata.auth.OAuthToken(scopes=scopes, oauth_input_params=oauth_input_params)
gdata_service.current_token = access_token
# request feed
feed = data_service.GetFeed(settings.GOOGLE_ANALYTICS_ACCOUNT_URI)
feed is a GDataFeed object which can easily be iterated over, like so:
for entry in feed.entry:
To be honest, I’m not sure if the scopes are necessary but I included them for the sake of completeness. Setting
oauth_input_params for the oAuth token is essential and something that took me a while to figure out – I had assumed that setting the parameters for the Gdata service would be enough.
I am directly assigning the access token to the Gdata service. I had originally tried to use the setter –
gdata_service.SetOAuthToken(access_token) – but had problems and switched to direct assignment. However, my problem could very well have been somewhere else, so feel free to try using the method.
Finally, you may have noticed that I’m querying the Analytics Data API. I hope to have more to announce about that soon. In the meantime, I’ll note that
gdata-python-client doesn’t have specific Analytics support, which is why I’m using the generic Gdata service.