首页 > 解决方案 > 如何正确使用范围 https://www.googleapis.com/auth/drive.file

问题描述

我尝试使用以下代码访问我的 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())

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

scope = ['https://www.googleapis.com/auth/drive.file']

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

File "/home/my_username/.local/lib/python3.6/site-packages/gspread/client.py", line 130, in open
    raise SpreadsheetNotFound
gspread.exceptions.SpreadsheetNotFound

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

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

gspread.exceptions.APIError: {
  "error": {
    "code": 403,
    "message": "The caller does not have permission",
    "status": "PERMISSION_DENIED"
  }
}

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

非常感谢任何提示!

哦,我还有一个更普遍的问题:服务帐户是否可以访问我的整个驱动器?还是只针对与服务帐户共享的所有内容?因为我只与它共享了一个电子表格,所以我对权限在这里的工作方式有点困惑。

标签: pythongoogle-sheets-apiservice-accountsgspread

解决方案


推荐阅读