In my Python3 program that uses the Gmail API, I want to re-instantiate the Gmail "service" instance every few hours for the purpose of enhanced reliability. I am not certain if this is required to better reliability, but I thought it would be useful.
So, when I start my program, I run the below function, which as you can see, builds the Gmail "service" instance. Then, after a few hours, I run the same code again. However, this results in socker.timeout errors. I know this because the socket.timeout errors occur every 6 hours in my log file, which is how often I re-initialize.
Why does this occur? Do I somehow need to disconnect my existing service, before reconnecting again? I did not find anything in the Gmail API Documentation or in other forum posts.
My other question is that do I even need to re-instantiate the service? Will the service instance be valid forever? (My program is intended to be continuous and run forever without touching it)
def gmailAPIInitialize(self):
try:
self.waitForInternet()
logging.info("Initializing the Gmail API Service")
creds = None
# The file token.pickle 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.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# 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())
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
else:
logging.error("Unable to find token.pickle file to initialize Gmail Service. Please provide 'token.pickle' file in current directory")
sys.exit(-1)
#flow = InstalledAppFlow.from_client_secrets_file(
#'credentials.json', SCOPES)
#creds = flow.run_local_server(port=0)
# Save the credentials for the next run
service = build('gmail', 'v1', credentials=creds, cache_discovery=False)
self.gmailAPIService = service
logging.info("Successfully initialized the Gmail API Service")
return True
except:
logging.error("An error was encountered while attempting to initialize the Gmail API")
tb = traceback.format_exc()
logging.exception(tb)
return False
Re-initializing code:
currentTime = datetime.datetime.now()
if currentTime > nextRefresh:
logging.info("Refreshing Gmail Connection")
nextRefresh = currentTime + timeDeltaResult
reinitalized = self.gmailAPIInitialize()
if reinitalized is True:
logging.error("Successfully Refreshed Gmail connection")
else:
logging.error("Failed to Refresh Gmail connection")
logging.info("Next Refresh time is at (" + nextRefresh.strftime("%d %b %Y %H:%M:%S") +")")
#RUN MY CALLS AS USUAL TO GMAIL SERVICE
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…