1414
1515# [START sheets_quickstart]
1616from __future__ import print_function
17+ import pickle
18+ import os .path
1719from 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
2022
21- # If modifying these scopes, delete the file token.json .
23+ # If modifying these scopes, delete the file token.pickle .
2224SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly'
2325
2426# The ID and range of a sample spreadsheet.
@@ -29,15 +31,26 @@ def main():
2931 """Shows basic usage of the Sheets API.
3032 Prints values from a sample spreadsheet.
3133 """
32- # The file token.json stores the user's access and refresh tokens, and is
34+ creds = None
35+ # The file token.pickle stores the user's access and refresh tokens, and is
3336 # created automatically when the authorization flow completes for the first
3437 # time.
35- store = file .Storage ('token.json' )
36- creds = store .get ()
37- if not creds or creds .invalid :
38- flow = client .flow_from_clientsecrets ('credentials.json' , SCOPES )
39- creds = tools .run_flow (flow , store )
40- service = build ('sheets' , 'v4' , http = creds .authorize (Http ()))
38+ if os .path .exists ('token.pickle' ):
39+ with open ('token.pickle' , 'rb' ) as token :
40+ creds = pickle .load (token )
41+ # If there are no (valid) credentials available, let the user log in.
42+ if not creds or not creds .valid :
43+ if creds and creds .expired and creds .refresh_token :
44+ creds .refresh (Request ())
45+ else :
46+ flow = InstalledAppFlow .from_client_secrets_file (
47+ 'credentials.json' , SCOPES )
48+ creds = flow .run_local_server ()
49+ # Save the credentials for the next run
50+ with open ('token.pickle' , 'wb' ) as token :
51+ pickle .dump (creds , token )
52+
53+ service = build ('sheets' , 'v4' , credentials = creds )
4154
4255 # Call the Sheets API
4356 sheet = service .spreadsheets ()
0 commit comments