import os.path from google.auth.transport.requests import Request from google.oauth2.credentials import Credentials from google_auth_oauthlib.flow import InstalledAppFlow from googleapiclient.discovery import build from googleapiclient.errors import HttpError from bedc import bedc class gservice(bedc): """docstring for gservice.""" def __init__(self): super(gservice, self).__init__() self.service = None self.creds = None def fetchToken(self, SCOPES): self.infoPrint("generate token",self.progress) flow = InstalledAppFlow.from_client_secrets_file( self.savePath+'/secret/client_secret.json', SCOPES) self.creds = flow.run_local_server(port=0) def generateToken(self,serviceType, SCOPES): ''' Start Tokenizing here is the way to get token link : https://developers.google.com/docs/api/quickstart/python ''' # 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.json.{}'.format(serviceType)): self.creds = Credentials.from_authorized_user_file('token.json.{}'.format(serviceType), SCOPES) self.infoPrint("token already exist",self.progress) # If there are no (valid) credentials available, let the user log in. if not self.creds or not self.creds.valid: if self.creds and self.creds.expired and self.creds.refresh_token: try: self.creds.refresh(Request()) except: self.fetchToken(SCOPES) self.infoPrint("refresh token",self.progress) else: self.fetchToken(SCOPES) # Save the credentials for the next run with open('token.json.{}'.format(serviceType), 'w') as token: token.write(self.creds.to_json()) def buildFormService(self, DISCOVERY_DOC): try: self.infoPrint("creating form service",self.progress) self.service = build('forms', 'v1', credentials=self.creds, discoveryServiceUrl=DISCOVERY_DOC, static_discovery=False) except HttpError as err: self.infoPrint("Error create service : {}".format(err),self.progress) print(err) pass def buildDocsService(self): try: self.infoPrint("creating service",self.progress) self.service = build('docs', 'v1', credentials=self.creds) except HttpError as err: print(err) pass