Wednesday, 15 December 2021

Preventing Google API token expiry using Python and Google Drive API?

I have the below sample code that attempts to access files on my personal Google Drive account. The earlier version had an annoying problem, namely that Google required manual enabling of it every time it ran, via opening a link in the browser. This is why I modified the code by including Oauth2 and believed it would solve this problem for good. However today, I again found the following console message:

File "c:\...\site-packages\oauth2client\client.py", line 819, in _do_refresh_request
    raise HttpAccessTokenRefreshError(error_msg, status=resp.status)
oauth2client.client.HttpAccessTokenRefreshError: invalid_grant: Token has been expired or revoked.

I believed that the purpose of the if not credentials condition in the code below was specifically to renew the credentials automatically based on the client_secrets file and thus to prevent such manual enabling.

Full code is as follows:

from googleapiclient.discovery import build
from oauth2client import client, tools 
from oauth2client.file import Storage

api_client_secret = r"C:\...\client_secret_0123456789-abc123def456ghi789.apps.googleusercontent.com.json"
credential_file_path = r"C:\...\credential_sample.json"

class GoogleDriveAccess:

    def __init__(self):
        self.service = self.get_authenticated_service(api_client_secret, credential_file_path, 'drive', 'v3', ['https://www.googleapis.com/auth/drive'])

    def get_authenticated_service(self, client_secret_file_path, credential_file_path, api_name, api_version, scopes):
        store = Storage(credential_file_path)
        credentials = store.get()
        if not credentials or credentials.invalid:
            flow = client.flow_from_clientsecrets(client_secret_file_path, scopes)
            credentials = tools.run_flow(flow, store)
        return build(api_name, api_version, credentials=credentials)

if __name__ == '__main__':
    GoogleDriveAccess()

What am I missing here? How could I ensure that Google doesn't automaically revoke my access right on my own Google account?



from Preventing Google API token expiry using Python and Google Drive API?

No comments:

Post a Comment