【发布时间】:2018-10-17 11:36:53
【问题描述】:
我正在编写一个需要从 Google 电子表格读取数据的 Python 3.7 脚本。
有问题的电子表格属于我的工作 Google 帐户所属的组织:我们姑且称其为“组织”。电子表格权限设置为“组织中知道链接的任何人都可以查看”。这个细节一直在阻止我的应用程序工作。
在使用我在组织中的帐户进行身份验证时,我访问了https://console.cloud.google.com/apis/credentials 的凭据仪表板,并创建了一个服务帐户密钥。根据Using New Google API Console project getting unauthorized_client ,Client is unauthorized to retrieve access tokens using this method,允许域范围的委派。我将 JSON 密钥文件下载到 /path/to/service_account_key.json。
下面我记录了我使用 gspread 客户端库 - https://github.com/burnash/gspread 的尝试 - 但是我在使用 google-api-python-client 1.7.4 时遇到了完全相同的问题:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
scopes = ['https://www.googleapis.com/auth/spreadsheets.readonly']
credentials = ServiceAccountCredentials.from_json_keyfile_name('/path/to/service_account_key.json', scopes)
gc = gspread.authorize(credentials)
# spreadhseet ID below obfuscated, it's actually the one you get from its URL
sheet = gc.open_by_key('12345-abcdef')
gspread 的响应与普通的 Google API v4 具有相同的 HTTP 代码和消息:
gspread.exceptions.APIError: {
"error": {
"code": 403,
"message": "The caller does not have permission",
"status": "PERMISSION_DENIED"
}
}
但是如果我将电子表格上的权限(我不会被允许在实际的电子表格上执行)更改为“任何拥有链接的人都可以查看”,从而删除组织“,一切有效!
<Spreadsheet 'Your spreadsheet' id:12345-abcdef>
我的粗略猜测是,我创建的服务帐户没有从我那里继承组织的成员身份。但是,我没有找到确保这一点的选择。我什至要求域管理员从他的管理员帐户(也启用域范围委派)为我创建服务帐户:没有。
Google service account and sheets permissions 已经说过,我必须明确地与服务帐户的电子邮件地址共享工作表。当我这样做时,它起作用了,但我还收到一条警告消息,声称该帐户不在组织的 G Suite 域中(再说一遍,怎么可能不呢?)。
非常感谢
【问题讨论】:
-
转到 Gsuite 管理员,让他们授予服务帐户对域的权限。
标签: python-3.x google-sheets google-oauth service-accounts gspread