diff --git a/sheets/quickstart/quickstart.py b/sheets/quickstart/quickstart.py index 8d27a713..878249d7 100644 --- a/sheets/quickstart/quickstart.py +++ b/sheets/quickstart/quickstart.py @@ -15,7 +15,8 @@ # [START sheets_quickstart] from __future__ import print_function import pickle -import os.path +from sys import exit as sysexit +from os.path import exists from googleapiclient.discovery import build from google_auth_oauthlib.flow import InstalledAppFlow from google.auth.transport.requests import Request @@ -32,21 +33,40 @@ def main(): Prints values from a sample spreadsheet. """ creds = None + updated_creds = False + + # Check to see if the program can obtain credentials for authorizing api, + # either from previous token.pickle or from credentials.json + if not (exists('token.pickle') or exists('credentials.json')): + print('\nPrerequisite - \'credentials.json\' - file not found. Before' + ' running again, please follow the Quickstart to' + ' download the \'credentials.json\' file here: \n\n' + 'https://developers.google.com/sheets/api/quickstart/' + 'python#step_1_turn_on_the\n') + sysexit() + # 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'): + # time. First, try to read the token.pickle from prior login attempt. + elif 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 no token.pickle, try to create creds from the credentials.json file + else: + flow = InstalledAppFlow.from_client_secrets_file( + 'credentials.json', SCOPES) + creds = flow.run_local_server() + updated_creds = True + + # If the credentials are not valid, let the user log in. + if not creds.valid: if creds and creds.expired and creds.refresh_token: creds.refresh(Request()) - else: - flow = InstalledAppFlow.from_client_secrets_file( - 'credentials.json', SCOPES) - creds = flow.run_local_server() - # Save the credentials for the next run + updated_creds = True + + # If updated the credentials, save for next run + if updated_creds: with open('token.pickle', 'wb') as token: pickle.dump(creds, token) @@ -64,7 +84,7 @@ def main(): print('Name, Major:') for row in values: # Print columns A and E, which correspond to indices 0 and 4. - print('%s, %s' % (row[0], row[4])) + print('\n%s, %s' % (row[0], row[4])) if __name__ == '__main__': main()