如何正确使用范围 https://www.googleapis.com/auth/drive.file

jan*_*son 6 python service-accounts gspread google-sheets-api

我尝试使用以下代码访问 Google Drive 中的 Google Sheets 文件:

import gspread
from oauth2client.service_account import ServiceAccountCredentials

scope = ['https://www.googleapis.com/auth/drive']
credentials = ServiceAccountCredentials.from_json_keyfile_name('credentials.json', scope)

gc = gspread.authorize(credentials)

wks = gc.open('my_test').sheet1

print(wks.get_all_records())
Run Code Online (Sandbox Code Playgroud)

然后,我在我的驱动器中创建了一个名为my_test的电子表格,并将其与credentials.json 中的电子邮件共享。然后它起作用了。但是,范围太广,我想使用

scope = ['https://www.googleapis.com/auth/drive.file']
Run Code Online (Sandbox Code Playgroud)

反而。但是如果我改变范围,它就找不到工作表:

File "/home/my_username/.local/lib/python3.6/site-packages/gspread/client.py", line 130, in open
    raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound
Run Code Online (Sandbox Code Playgroud)

这是为什么?我怎样才能改变它?我在谷歌上搜索了很多,对于大多数人来说,共享或重新共享电子表格是有效的。就我而言,问题仍然存在。

在使用 drive.file 范围解决方案为 Drive 元数据添加范围的解决方案执行查询时,我也尝试了此错误 500,但这会导致此权限错误,这可以看作是进度(因为它找到了文件):

gspread.exceptions.APIError: {
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,即使我将电子表格访问权限设置为“公开”,此错误仍然存​​在。

任何提示非常感谢!

哦,我还有一个更普遍的问题:服务帐户是否可以访问我的整个驱动器?还是仅适用于与服务帐户共享的所有内容?因为我只与它共享了一个电子表格,所以我对这里的权限究竟是如何工作感到有些困惑。

Žil*_*nis 1

auth/drive.file允许对您拥有的单个文件进行操作fileId。此范围旨在与 Google 文件选择器 API 配合使用,以便您能够fileId使用文件选择器获取这些内容,然后执行您的操作。

在您的情况下,fileId当您仅指定文件名时,SDK 客户端会尝试列出文件,但没有得到任何结果,因此会抛出 404 错误。

对于部分:

但是,即使我将电子表格访问权限设置为“公共”,此错误仍然存​​在。

可能会出现这种情况:可以通过https://www.googleapis.com/auth/spreadsheets.readonly范围访问此工作表。