关于使用 gspread API 读取 google sheet 和 Python 时范围值的问题

Q about scope value when using gspread API to read google sheet with Python

我是 google API 的新手。我希望通过 python 程序阅读 google 传播 sheet 并遵循此处的说明:

https://www.twilio.com/blog/2017/02/an-easy-way-to-read-and-write-to-a-google-spreadsheet-in-python.html

我正在使用一个名为 Legislators 2017 的 google sheet。

下面是从sheet.

中打印出一些内容的代码
import gspread
from oauth2client.service_account import ServiceAccountCredentials


scope = ['https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('google_drive_oct_6_2020.json', scope)
client = gspread.authorize(creds)

sheet = client.open("Legislators 2017").sheet1

list_of_hashes = sheet.get_all_records()
print(list_of_hashes)

以上作品。

一般情况下我倾向于使用尽可能小的范围,并且愿意使用

https://www.googleapis.com/auth/spreadsheets or 
https://www.googleapis.com/auth/spreadsheets.readonly

但它们不起作用,我收到以下消息的异常:

Insufficient Permission: Request had insufficient authentication scopes.

我错过了什么?

从 GCP 创建身份验证凭据时,您需要说明授予身份验证密钥的访问级别。 然后,您可以访问该级别或更低级别的访问权限。

根据您所指的指南:

Name the service account and grant it a Project Role of Editor.

使用client.open("Legislators 2017")时,使用DriveAPI中的“Files:list”的方法。 Ref 因此,需要使用驱动器 API 的范围。在您的脚本中,https://www.googleapis.com/auth/drivehttps://www.googleapis.com/auth/drive.readonly 是必需的。

当你不想使用Drive API的作用域而想使用the smallest scope possible in general时,下面的修改如何?

发件人:

scope = ['https://www.googleapis.com/auth/drive']
creds = ServiceAccountCredentials.from_json_keyfile_name('google_drive_oct_6_2020.json', scope)
client = gspread.authorize(creds)

sheet = client.open("Legislators 2017").sheet1

收件人:

scope = ['https://www.googleapis.com/auth/spreadsheets.readonly']
creds = ServiceAccountCredentials.from_json_keyfile_name('google_drive_oct_6_2020.json', scope)
client = gspread.authorize(creds)

sheet = client.open_by_key("###").sheet1
  • ###Legislators 2017 的电子表格 ID。
  • 本次修改,可以使用https://www.googleapis.com/auth/spreadsheets.readonly的作用域。另外,可以使用https://www.googleapis.com/auth/spreadsheets

参考文献: