Skip to content

Commit 1987467

Browse files
committed
Switch sheets/quickstart to from oauth2client to google-auth
1 parent 6e92563 commit 1987467

2 files changed

Lines changed: 24 additions & 11 deletions

File tree

sheets/quickstart/README.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ requests to the Google Sheets API.
88
## Install
99

1010
```
11-
pip install --upgrade google-api-python-client oauth2client
11+
pip install --upgrade google-api-python-client google-auth-httplib2 google-auth-oauthlib pickle
1212
```
1313

1414

sheets/quickstart/quickstart.py

Lines changed: 23 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -14,11 +14,13 @@
1414

1515
# [START sheets_quickstart]
1616
from __future__ import print_function
17+
import pickle
18+
import os.path
1719
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
2022

21-
# If modifying these scopes, delete the file token.json.
23+
# If modifying these scopes, delete the file token.pickle.
2224
SCOPES = '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

Comments
 (0)