|
14 | 14 |
|
15 | 15 | # [START admin_sdk_reports_quickstart] |
16 | 16 | from __future__ import print_function |
| 17 | +import pickle |
| 18 | +import os.path |
17 | 19 | from googleapiclient.discovery import build |
18 | | -from httplib2 import Http |
19 | | -from oauth2client import file, client, tools |
| 20 | +from google_auth_oauthlib.flow import InstalledAppFlow |
| 21 | +from google.auth.transport.requests import Request |
20 | 22 |
|
21 | | -# If modifying these scopes, delete the file token.json. |
| 23 | +# If modifying these scopes, delete the file token.pickle. |
22 | 24 | SCOPES = 'https://www.googleapis.com/auth/admin.reports.audit.readonly' |
23 | 25 |
|
24 | 26 | def main(): |
25 | 27 | """Shows basic usage of the Admin SDK Reports API. |
26 | 28 | Prints the time, email, and name of the last 10 login events in the domain. |
27 | 29 | """ |
28 | | - # The file token.json stores the user's access and refresh tokens, and is |
| 30 | + creds = None |
| 31 | + # The file token.pickle stores the user's access and refresh tokens, and is |
29 | 32 | # created automatically when the authorization flow completes for the first |
30 | 33 | # time. |
31 | | - store = file.Storage('token.json') |
32 | | - creds = store.get() |
33 | | - if not creds or creds.invalid: |
34 | | - flow = client.flow_from_clientsecrets('credentials.json', SCOPES) |
35 | | - creds = tools.run_flow(flow, store) |
36 | | - service = build('admin', 'reports_v1', http=creds.authorize(Http())) |
| 34 | + if os.path.exists('token.pickle'): |
| 35 | + with open('token.pickle', 'rb') as token: |
| 36 | + creds = pickle.load(token) |
| 37 | + # If there are no (valid) credentials available, let the user log in. |
| 38 | + if not creds or not creds.valid: |
| 39 | + if creds and creds.expired and creds.refresh_token: |
| 40 | + creds.refresh(Request()) |
| 41 | + else: |
| 42 | + flow = InstalledAppFlow.from_client_secrets_file( |
| 43 | + 'credentials.json', SCOPES) |
| 44 | + creds = flow.run_local_server() |
| 45 | + # Save the credentials for the next run |
| 46 | + with open('token.pickle', 'wb') as token: |
| 47 | + pickle.dump(creds, token) |
| 48 | + |
| 49 | + service = build('admin', 'reports_v1', credentials=creds) |
37 | 50 |
|
38 | 51 | # Call the Admin SDK Reports API |
39 | 52 | print('Getting the last 10 login events') |
|
0 commit comments