6 from google_auth_oauthlib.flow import InstalledAppFlow
7 from google.auth.transport.requests import Request
9 TOKEN_FILE = ".gsheets-pickle.base64"
11 # If modifying these scopes, delete the token file
13 'https://www.googleapis.com/auth/spreadsheets',
14 'https://www.googleapis.com/auth/drive'
18 """Allows user to authenticate for the Sheets API.
20 Resulting authorization token is stored in token.pickle.
23 # The token file stores the user's access and refresh tokens, and is
24 # created automatically when the authorization flow completes for the first
26 if os.path.exists(TOKEN_FILE):
27 with open(TOKEN_FILE, 'rb') as token_file:
28 creds_base64 = token_file.read()
29 creds_pickle = base64.b64decode(creds_base64)
30 creds = pickle.loads(creds_pickle)
32 # If there are no (valid) credentials available, let the user log in.
33 if not creds or not creds.valid:
34 if creds and creds.expired and creds.refresh_token:
35 print("Token seems to have expired. Refreshing.")
36 creds.refresh(Request())
38 flow = InstalledAppFlow.from_client_secrets_file(
39 '.gsheets-creds.json', SCOPES)
40 creds = flow.run_local_server(port=0)
41 # Save the credentials for the next run
42 with open(TOKEN_FILE, 'wb') as token_file:
43 creds_pickle = pickle.dumps(creds)
44 creds_base64 = base64.b64encode(creds_pickle)
45 token_file.write(creds_base64)
46 print("Token now saved in {}".format(TOKEN_FILE))
48 print("Valid token in {} left unchanged.".format(TOKEN_FILE))
50 if __name__ == '__main__':