问题描述
我按照Google API quickstart Python上的说明进行操作,以便快速入门。我下载了具有默认名称的JSON文件集并作为桌面应用程序下载。确保每个Python库都是最新的之后,我在页面上粘贴并运行了代码。
经过多次尝试后,会发生以下情况:
- 浏览器选项卡将打开
- 将要求我选择一个帐户
- 然后我得到要求允许访问的屏幕
查看您的Google电子表格
- 我点击允许并等待
- 然后我得到一个告诉我的屏幕
Safari无法打开页面localhost:random_port ... &scope = https://www.googleapis.com/auth/spreadsheets.readonly
为确保没有问题,我将客户端ID添加到admin.google.com上的允许连接列表中,但这似乎无济于事。
有人知道什么可能导致此问题吗?
在admin.google.com上还有其他需要做的事情吗?
我在Mac上使用VS Code。我的图书馆版本是
google-api-core 1.23.0
google-api-python-client 1.12.4
google-auth 1.22.1
google-auth-httplib2 0.0.4
google-auth-oauthlib 0.4.1
googleapis-common-protos 1.52.0
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 = '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms'
SAMPLE_RANGE_NAME = 'Class Data!A2:E'
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(port=0)
# 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[4]))
if __name__ == '__main__':
main()
解决方法
您在代码中的以下语句中使用的端口:
flow.run_local_server(port=0)
应该与您在该项目的同意屏幕中所允许的完全相同。
确保JS重定向URL指向您将在本地提供服务的端口。
有关该模块的更多信息,请参见google_auth_oauthlib.flow。
,对于遇到此问题的其他人。该问题与操作系统上的操作系统/软件有关。我在全新安装的 Mac OS 上运行它没有任何问题。
,刚遇到同样的问题。
如果您使用 Safari,它将尝试访问 https://localhost:xxxx/xxxx。
将网址粘贴到其他浏览器(例如 Chrome)可以正常工作。
要停止 Safari 在本地主机上不断强制使用 HTTPS,请转到(Safari > 首选项 > 隐私 > 管理网站数据...)
搜索 localhost
并按删除。
再次尝试脚本,看看它是否有效。