0
votes

I have a unique constraint to connect to google analytics from app engine - retrieve the data do the calculations and change the data in website.

Everything has to be done automatically and no manual interactions. But there is a problem with google authentication.

I followed various tutorials to connect to GA from app engine but it seems authentication is the big problem.

eg: Followed the below tutorial and when i run the code in my local , it will open browser to authenticate and able to successfully retrieve the result. https://developers.google.com/analytics/devguides/reporting/core/v4/quickstart/service-py

Also, followed one of the good link http://www.marinamele.com/use-google-analytics-api-with-python but it seems authentication problem when we run in cloud.

Also tried storing credentials in client_secrets.json file and deployed to app engine and it was working for 60 mins, after that access_token expired and not able to reach analytics api and 500 error was thrown.

Any suggestions on how to connect to google analytics from google app engine via a crob job to get the analytics data, do the computation and change the database to show different content in website.

1
Why don't you just refresh the Access Token using Refresh Token after expiration ? - dikesh
how to do that ?? and we cannot save the token back to file in google app engine. Currently i am having credentials.dat file but you will not be able to write to the file again. - Rinsen S

1 Answers

0
votes

You should use offline access

First of all you need to generate the necesaries tokens (access token and refresh token): follow the step by step or see complete example

After obtaining the tokens you should have a json similar to this one:

{ 
    "access_token" : "XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX", 
    "token_type" : "Bearer", 
    "expires_in" : 3600, 
    "refresh_token" : "X/XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX" 
}

(With some values instead of X's)

You should use this json to do the authentication. Internally if the access token is expired the authentication will use the refresh token to generate a new one.

This whole protocol is called Auth 2.0, if you are interested in reading more about it, check here