def authenticate_google(): creds = None 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()) else: flow = InstalledAppFlow.from_client_secrects_file( 'credentials.json', SCOPES) creds = flow.run_local_server(port=0) # save the credentials for the next run with open('token.pickle', 'wb') as token: pickle.dump(creds, token) service = build('calendar', 'v3', credentials=creds) return service