5 from google_auth_oauthlib.flow import InstalledAppFlow
6 from google.auth.transport.requests import Request
8 # If modifying these scopes, delete the file token.pickle.
9 SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
11 TOKEN_FILE = ".gsheets-token.pickle"
14 """Allows user to authenticate for the Sheets API.
16 Resulting authorization token is stored in token.pickle.
19 # The token file stores the user's access and refresh tokens, and is
20 # created automatically when the authorization flow completes for the first
22 if os.path.exists(TOKEN_FILE):
23 with open(TOKEN_FILE, 'rb') as token:
24 creds = pickle.load(token)
26 # If there are no (valid) credentials available, let the user log in.
27 if not creds or not creds.valid:
28 if creds and creds.expired and creds.refresh_token:
29 creds.refresh(Request())
31 flow = InstalledAppFlow.from_client_secrets_file(
32 'credentials.json', SCOPES)
33 creds = flow.run_local_server(port=0)
34 # Save the credentials for the next run
35 with open(TOKEN_FILE, 'wb') as token:
36 pickle.dump(creds, token)
38 print("Token now saved in {}".format(TOKEN_FILE))
40 if __name__ == '__main__':