Handle refresh token error
This commit is contained in:
19
robocyp.py
19
robocyp.py
@@ -5,6 +5,7 @@ import os
|
||||
import sys
|
||||
|
||||
from google.auth.transport.requests import Request
|
||||
from google.auth.exceptions import RefreshError
|
||||
from google.oauth2.credentials import Credentials
|
||||
from google_auth_oauthlib.flow import InstalledAppFlow
|
||||
from googleapiclient.discovery import build
|
||||
@@ -43,11 +44,21 @@ def get_yt_creds():
|
||||
if os.path.exists(token_file):
|
||||
creds = Credentials.from_authorized_user_file(token_file, scopes)
|
||||
|
||||
# If there are no (valid) credentials available, let the user log in.
|
||||
if not creds or not creds.valid:
|
||||
# Valid credentials
|
||||
if creds and creds.valid:
|
||||
return creds
|
||||
|
||||
# Expired credentials
|
||||
if creds and creds.expired and creds.refresh_token:
|
||||
try:
|
||||
creds.refresh(Request())
|
||||
else:
|
||||
with open(token_file, "w") as token:
|
||||
token.write(creds.to_json())
|
||||
return creds
|
||||
except RefreshError as err:
|
||||
print(f'Error refreshing token: {err}')
|
||||
|
||||
# No credentials or cannot refresh
|
||||
if not os.path.exists(client_secrets_file):
|
||||
print(f'Client secrets file {client_secrets_file} not found')
|
||||
sys.exit(1)
|
||||
@@ -55,10 +66,8 @@ def get_yt_creds():
|
||||
client_secrets_file, scopes
|
||||
)
|
||||
creds = flow.run_local_server(port=0)
|
||||
# Save the credentials for the next run
|
||||
with open(token_file, "w") as token:
|
||||
token.write(creds.to_json())
|
||||
|
||||
return creds
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user