【发布时间】:2019-05-16 02:48:01
【问题描述】:
Google API 新手,按照 Python Quickstart 中的说明进行基本程序。决定使用我自己的 API 项目使程序运行,并且可以使用新凭据访问他们的示例表,但不能访问我自己的工作表。我要更改的只是 SAMPLE_SPREADSHEET_ID,不太清楚为什么我无法访问自己的电子表格。甚至将它们公之于众。为相关帐户启用 Sheets API。
我收到此错误:
{
"error": {
"code": 403,
"message": "The request is missing a valid API key.",
"status": "PERMISSION_DENIED"
}
}
这是程序:(我知道它很长,我只是出于绝望而询问,因为几天的谷歌搜索和折磨无法解决我的问题)
from __future__ import print_function
import pickle
import os.path
from googleapiclient.discovery import build
from google_auth_oauthlib.flow import InstalledAppFlow
from google.auth.transport.requests import Request
# If modifying these scopes, delete the file token.pickle.
SCOPES = ['https://www.googleapis.com/auth/spreadsheets.readonly']
# The ID and range of a sample spreadsheet.
SAMPLE_SPREADSHEET_ID = '1V7reDgXa4AuIa0hmf7cpr9SLxL0aZ0LuUXy3kBtR1uM'
SAMPLE_RANGE_NAME = 'Class Data!A1:C'
def main():
"""Shows basic usage of the Sheets API.
Prints values from a sample spreadsheet.
"""
creds = None
# The file token.pickle stores the user's access and refresh tokens, and is
# created automatically when the authorization flow completes for the first
# time.
if os.path.exists('token.pickle'):
with open('token.pickle', 'rb') as token:
creds = pickle.load(token)
# If there are no (valid) credentials available, let the user log in.
if not creds or not creds.valid:
if creds and creds.expired and creds.refresh_token:
creds.refresh(Request())
else:
flow = InstalledAppFlow.from_client_secrets_file(
'credentials.json', SCOPES)
creds = flow.run_local_server()
# Save the credentials for the next run
with open('token.pickle', 'wb') as token:
pickle.dump(creds, token)
service = build('sheets', 'v4', credentials=creds)
# Call the Sheets API
sheet = service.spreadsheets()
result = sheet.values().get(spreadsheetId=SAMPLE_SPREADSHEET_ID,
range=SAMPLE_RANGE_NAME).execute()
values = result.get('values', [])
if not values:
print('No data found.')
else:
print('Name, Major:')
for row in values:
# Print columns A and E, which correspond to indices 0 and 4.
print('%s, %s' % (row[0], row[2]))
if __name__ == '__main__':
main()
【问题讨论】:
标签: python google-api google-oauth google-sheets-api google-api-python-client