问:当使用gspreadapi阅读带有Python的google工作表时,范围值是多少

问:当使用gspreadapi阅读带有Python的google工作表时,范围值是多少,python,google-sheets-api,gspread,Python,Google Sheets Api,Gspread,我是谷歌API的新手。我希望通过python程序阅读google电子表格,并在此处找到以下说明: 我有一张名为Legitors 2017的谷歌表格,我正在使用它 以下是打印工作表中某些内容的代码 import gspread from oauth2client.service_account import ServiceAccountCredentials scope = ['https://www.googleapis.com/auth/drive'] creds = ServiceAc

我是谷歌API的新手。我希望通过python程序阅读google电子表格,并在此处找到以下说明:

我有一张名为Legitors 2017的谷歌表格,我正在使用它

以下是打印工作表中某些内容的代码

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(“Legitors 2017”)
时,使用驱动API中的“文件:列表”方法。因此,需要使用驱动器API的范围。在脚本中,
https://www.googleapis.com/auth/drive
https://www.googleapis.com/auth/drive.readonly
是必需的

如果您不想使用驱动器API的作用域,并且希望使用
通常可能的最小作用域
,那么下面的修改如何

发件人: 致:
  • ###
    是2017年立法者的电子表格ID
  • 在此修改中,
    https://www.googleapis.com/auth/spreadsheets.readonly
    可以使用。另外,
    https://www.googleapis.com/auth/spreadsheets
    可以使用
参考资料:
    • 似乎
      get\u all\u records()
      使用了“spreadsheets.values.get”的方法

我已经这样做了,但仍然存在问题。谢谢你的回复!多谢!这对我有用。不过,我还有一个问题。我看到您提到:通过这一点,需要使用驱动API的范围。但是,我在您引用的代码中没有直接提到这一点。这是不是源于代码注释:驱动器使用不同的术语?非常感谢您的回复@谢谢你的回复。我很高兴你的问题解决了。我不得不为我糟糕的英语水平道歉。不幸的是,关于您的附加问题,我无法理解
,但是,在您引用的代码中,我没有看到直接提到这一点。这是不是出自代码注释:驱动器使用不同的术语?
。我能问一下细节吗?不客气@Tanaike。你的英语对我来说似乎很好:)我想问的是,你是如何发现驱动器API中使用了“文件:列表”的?@SuB谢谢你的回答。为了从文件名中检索文件ID,需要使用驱动器API的files.list方法。在这种情况下,至少,
https://www.googleapis.com/auth/drive.metadata.readonly需要使用驱动器API的
。但在您的问题中,您希望使用
https://www.googleapis.com/auth/spreadsheets.readonly
。所以我建议直接使用文件ID。在这种情况下,gspread中似乎没有使用驱动器API。如果我误解了你的回答,我道歉。
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