Handle refresh token error
This commit is contained in:
parent
cbe23bd0f7
commit
6c3f9c870f
39
robocyp.py
39
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,22 +44,30 @@ 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:
|
||||
if creds and creds.expired and creds.refresh_token:
|
||||
creds.refresh(Request())
|
||||
else:
|
||||
if not os.path.exists(client_secrets_file):
|
||||
print(f'Client secrets file {client_secrets_file} not found')
|
||||
sys.exit(1)
|
||||
flow = InstalledAppFlow.from_client_secrets_file(
|
||||
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())
|
||||
# Valid credentials
|
||||
if creds and creds.valid:
|
||||
return creds
|
||||
|
||||
# Expired credentials
|
||||
if creds and creds.expired and creds.refresh_token:
|
||||
try:
|
||||
creds.refresh(Request())
|
||||
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)
|
||||
flow = InstalledAppFlow.from_client_secrets_file(
|
||||
client_secrets_file, scopes
|
||||
)
|
||||
creds = flow.run_local_server(port=0)
|
||||
with open(token_file, "w") as token:
|
||||
token.write(creds.to_json())
|
||||
return creds
|
||||
|
||||
|
||||
|
||||
Loading…
Reference in New Issue
Block a user