]> git.cworth.org Git - turbot/blob - gsheets-authenticate.py
Initial implement of auto-creation of Google sheets
[turbot] / gsheets-authenticate.py
1 #!/usr/bin/env python3
2
3 import pickle
4 import os.path
5 from google_auth_oauthlib.flow import InstalledAppFlow
6 from google.auth.transport.requests import Request
7
8 # If modifying these scopes, delete the file token.pickle.
9 SCOPES = ['https://www.googleapis.com/auth/spreadsheets']
10
11 TOKEN_FILE = ".gsheets-token.pickle"
12
13 def main():
14     """Allows user to authenticate for the Sheets API.
15
16     Resulting authorization token is stored in token.pickle.
17     """
18     creds = None
19     # The file token.pickle stores the user's access and refresh tokens, and is
20     # created automatically when the authorization flow completes for the first
21     # time.
22     if os.path.exists(TOKEN_FILE):
23         with open(TOKEN_FILE, 'rb') as token:
24             creds = pickle.load(token)
25
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())
30         else:
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)
37
38     print("Token now saved in {}".format(TOKEN_FILE))
39
40 if __name__ == '__main__':
41     main()