You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

81 lines
2.3 KiB

import datetime
from googleapiclient.discovery import build
from googleapiclient.errors import *
from oauth2client import client
from oauth2client import tools
from oauth2client.file import Storage
# from oauth2client.service_account import ServiceAccountCredentials
import httplib2
import os
import argparse
flags = argparse.ArgumentParser(parents=[tools.argparser]).parse_args()
HOUR = datetime.timedelta(seconds=60**2)
class API:
def __init__(
self,
service,
scopes,
app_name,
client_secret_file,
credentials_dir,
version='v3',
):
self.service_name = service
self.app_name = app_name
self.client_secret_file = client_secret_file
self.credentials_dir = credentials_dir
self.scopes = scopes
self._service = None
self._service_settime = None
self.version = version
def get_credentials(self):
credential_path = os.path.join(self.credentials_dir,
'token.json')
store = Storage(credential_path)
credentials = store.get()
if not credentials or credentials.invalid:
flow = client.flow_from_clientsecrets(
self.client_secret_file, self.scopes)
flow.user_agent = self.app_name
if flags:
credentials = tools.run_flow(flow, store, flags)
else:
credentials = tools.run(flow, store)
print('Storing credentials to ' + credential_path)
return credentials
def build_service(self):
credentials = self.get_credentials()
http = credentials.authorize(httplib2.Http())
service = build(self.service_name, self.version,
http=http, cache_discovery=False)
return service
def _needs_renewal(self):
now = datetime.datetime.today()
if self._service_settime:
return (now - self._service_settime) > HOUR
else:
return True
@property
def service(self):
if self._needs_renewal():
service = self.build_service()
self._service = service
self._service_settime = datetime.datetime.today()
return service
else:
return self._service