【发布时间】:2020-04-16 11:27:50
【问题描述】:
我正在尝试使用我的本地凭据(即不是服务帐户)读取 Google 电子表格。我基本上在做:
from googleapiclient.discovery import build
service = build('sheets', 'v4')
request = sheet_service.spreadsheets().values().get(spreadsheetId=SPREADSHEET_ID, range='{}!A1:a4'.format(SHEET_NAME))
result = request.execute()
values = result.get('values', [])
但是我得到以下错误:
Traceback (most recent call last):
File "./update_incidents_tracker.py", line 54, in <module>
sys.exit(main())
File "./update_incidents_tracker.py", line 48, in main
result = request.execute()
File "/home/filip/.virtualenvs/monitoring-tools/lib/python3.6/site-packages/googleapiclient/_helpers.py", line 134, in positional_wrapper
return wrapped(*args, **kwargs)
File "/home/filip/.virtualenvs/monitoring-tools/lib/python3.6/site-packages/googleapiclient/http.py", line 898, in execute
raise HttpError(resp, content, uri=self.uri)
googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/1lTcQ3WknG_2oZvy9O9LEbgAzoykOWaheYSaDkkV21wE/values/Incidents%21A1%3Aa4?alt=json returned "Request had insufficient authentication scopes.">
我找不到为我的本地 (gcloud SDK) 凭据设置范围的方法。如何设置合适的范围?
作为基于服务帐户的身份验证的参考,我可以简单地运行:
credentials = service_account.Credentials.from_service_account_file(CREDENTIALS_FILE, scopes=SCOPES)
build('sheets', 'v4', credentials=credentials)
【问题讨论】:
-
如果您已经下载了凭证文件,您可以关注this quickstart。
-
我不想使用服务帐户,因为我正在编写一个脚本,多个用户将在他们的机器上运行。我不希望所有这些都经过 SA 代,这很麻烦。
-
我提供的快速入门不涉及服务帐户。每个用户都将使用自己的凭据。
标签: google-sheets google-cloud-platform google-oauth gcloud google-workspace