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
12 SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
15 """Allows user to authenticate for the Sheets API.
17 Resulting authorization token is stored in token.pickle.
20 # The token file stores the user's access and refresh tokens, and is
21 # created automatically when the authorization flow completes for the first
23 if os.path.exists(TOKEN_FILE):
24 with open(TOKEN_FILE, 'rb') as token_file:
25 creds_base64 = token_file.read()
26 creds_pickle = base64.b64decode(creds_base64)
27 creds = pickle.loads(creds_pickle)
29 # If there are no (valid) credentials available, let the user log in.
30 if not creds or not creds.valid:
31 if creds and creds.expired and creds.refresh_token:
32 print("Token seems to have expired. Refreshing.")
33 creds.refresh(Request())
35 flow = InstalledAppFlow.from_client_secrets_file(
36 '.gsheets-creds.json', SCOPES)
37 creds = flow.run_local_server(port=0)
38 # Save the credentials for the next run
39 with open(TOKEN_FILE, 'wb') as token_file:
40 creds_pickle = pickle.dumps(creds)
41 creds_base64 = base64.b64encode(creds_pickle)
42 token_file.write(creds_base64)
43 print("Token now saved in {}".format(TOKEN_FILE))
45 print("Valid token in {} left unchanged.".format(TOKEN_FILE))
47 if __name__ == '__main__':