Home > Mobile >  Is there a workaround to prevent Gmail API for python from asking for a new token each time I run my
Is there a workaround to prevent Gmail API for python from asking for a new token each time I run my

Time:11-18

I have a python script that sends emails with attachments using GMAIL's API. Each time(mostly after a day) I run the script, I get an error that the token's invalid.

The only solution I have identified so far is to download the json file each time I run the script but I was expecting this to be done only once as I intend to convert the script to a desktop application.

CodePudding user response:

Google sends you an authToken and a RefreshToken, who need to be stored to refresh your token when he is no longer valid.

Check that : https://developers.google.com/identity/protocols/oauth2

CodePudding user response:

There are two types of tokens access tokens and refresh tokens.

Access tokens are only good for an hour. Refresh tokens are long lived and should work until the access has been removed. Or if your application is still in the testing phase then the token will only work for seven days. There is one other thing, if you are creating your tokens from google oauth2 playground I bleave they are only good for three hours give or take.

The best solution for all of the above is to ensure that your app is first off set to prodctuion, and second that you are properly storing your token after you have created it.

In the sample below the token is stored in the token.json for later use.

def Authorize(credentials_file_path, token_file_path):
    """Shows basic usage of authorization"""
    try:
        credentials = None
        # The file token.json stores the user's access and refresh tokens, and is
        # created automatically when the authorization flow completes for the first
        # time.
        if os.path.exists(token_file_path):
            try:
                credentials = Credentials.from_authorized_user_file(token_file_path, SCOPES)
                credentials.refresh(Request())
            except google.auth.exceptions.RefreshError as error:
                # if refresh token fails, reset creds to none.
                credentials = None
                print(f'An refresh authorization error occurred: {error}')
        # If there are no (valid) credentials available, let the user log in.
        if not credentials or not credentials.valid:
            if credentials and credentials.expired and credentials.refresh_token:
                credentials.refresh(Request())
            else:
                flow = InstalledAppFlow.from_client_secrets_file(
                    credentials_file_path, SCOPES)
                credentials = flow.run_local_server(port=0)
            # Save the credentials for the next run
            with open(token_file_path, 'w') as token:
                token.write(credentials.to_json())
    except HttpError as error:
        # Todo handle error
        print(f'An authorization error occurred: {error}')

    return credentials

if __name__ == '__main__':
    creds = Authorize('C:\\YouTube\\dev\\credentials.json', "token.json")
  • Related