Google API: getting Credentials from refresh token with oauth2client.client
I use: oauth2client.client.GoogleCredentials
cred = oauth2client.client.GoogleCredentials(access_token,client_id,client_secret, refresh_token,expires_at,"https://accounts.google.com/o/oauth2/token",some_user_agent) http = cred.authorize(httplib2.Http()) cred.refresh(http) self.gmail_service = discovery.build('gmail', 'v1', credentials=cred)
You can construct an OAuth2Credentials
instance directly like this:
import httplib2from oauth2client import GOOGLE_REVOKE_URI, GOOGLE_TOKEN_URI, clientCLIENT_ID = '<client_id>'CLIENT_SECRET = '<client_secret>'REFRESH_TOKEN = '<refresh_token>'credentials = client.OAuth2Credentials( access_token=None, # set access_token to None since we use a refresh token client_id=CLIENT_ID, client_secret=CLIENT_SECRET, refresh_token=REFRESH_TOKEN, token_expiry=None, token_uri=GOOGLE_TOKEN_URI, user_agent=None, revoke_uri=GOOGLE_REVOKE_URI)credentials.refresh(httplib2.Http()) # refresh the access token (optional)print(credentials.to_json())http = credentials.authorize(httplib2.Http()) # apply the credentials
I solved this quite easily (you certainly miss this documentation). This is a snippet of my code that tries to use Picasa API to get all of album from active user:
http = httplib2.Http(ca_certs=os.environ['REQUESTS_CA_BUNDLE']) try: http = self.oauth.credentials.authorize(http) response, album_list = http.request(Picasa.PHOTOS_URL, 'GET') if response['status'] == '403': self.oauth.credentials.refresh(http) response, album_list = http.request(Picasa.PHOTOS_URL, 'GET') album_list = json.load(StringIO(album_list)) except Exception as ex: Logger.debug('Picasa: error %s' % ex) return {}
Use the refresh
method coming from oauth2client.client.OAuth2Credentials. I think it's even okay to use if response['status'] != '200'
. Got to check that!