I am trying to write a Django app which creates events in a specific Google calendar. So far I have been successful. There is only a little problem:
I don't know how to obtain a refresh token with the google python client.
The result is that after my token expires the app does not work and I have to create a new token. If I understand the documentation correct that's where the refresh token comes in.
Access tokens have a limited lifetime and, in some cases, an application needs access to a Google API beyond the lifetime of a single access token. When this is the case, your application can obtain what is called a refresh token. A refresh token allows your application to obtain new access tokens.
Google Documentation (see "Basic Steps", Section 4)
My code
import gflags
import httplib2
from apiclient.discovery import build
from oauth2client.file import Storage
from oauth2client.client import OAuth2WebServerFlow
from oauth2client.tools import run
FLAGS = gflags.FLAGS
FLOW = OAuth2WebServerFlow(
client_id=GOOGLE_API_CLIENT_ID,
client_secret=GOOGLE_API_CLIENT_SECRET,
scope=GOOGLE_API_CALENDAR_SCOPE,
user_agent=GOOGLE_API_USER_AGENT)
storage = Storage(GOOGLE_API_CREDENTIAL_PATH)
credentials = storage.get()
if credentials is None or credentials.invalid == True:
credentials = run(FLOW, storage)
http = httplib2.Http()
http = credentials.authorize(http)
service = build(serviceName='calendar', version='v3', http=http,
developerKey=GOOGLE_API_DEVELOPER_KEY)
event = {
[... Dictionary with all the necessary data here ...]
}
created_event = service.events().insert(calendarId=GOOGLE_API_CALENDAR_ID, body=event).execute()
This is pretty much the example from the Google documentation. The interesting bit is the Storage. It's a file where some credential data is saved.
Content of my storage file:
{
"_module": "oauth2client.client",
"_class": "OAuth2Credentials",
"access_token": [redacted],
"token_uri": "https://accounts.google.com/o/oauth2/token",
"invalid": true,
"client_id": [redacted],
"client_secret": [redacted],
"token_expiry": "2011-12-17T16:44:15Z",
"refresh_token": null,
"user_agent": [redacted]
}
There should be a refresh token in there, but instead it's null. So I figure I can somehow request a refresh token.
I would appreciate any help on how I can get this to work. If you need more information, please tell me.