我按照 Google API 快速入门 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()
刚刚遇到同样的问题。
如果您使用 Safari,它将尝试访问 https://localhost:xxxx/xxxx。
将 url 粘贴到其他浏览器(例如 Chrome)可以正常工作。
要停止 Safari 在本地主机上强制使用 HTTPS,请转至(Safari > 首选项 > 隐私 > 管理网站数据...)
搜索
localhost
并按删除。
再次尝试该脚本,看看它是否有效。
代码中以下语句中使用的端口:
flow.run_local_server(port=0)
应与您在该项目的同意屏幕中允许的完全相同。
确保 JS 重定向 URL 指向您将从本地提供服务的同一端口。
有关该模块的更多信息,请参阅 google_auth_oauthlib.flow。
对于遇到此问题的其他人。该问题与操作系统/操作系统上的软件有关。我在全新安装的 Mac 操作系统上运行此程序没有任何问题。
在我的 MacOS 设置中,我将默认浏览器更改为 Google Chrome,并且相同的身份验证流程开始工作。
使用 http://127.0.0.1:random-port 而不是 localhost:random-port 有效。