我正在编写一个 Python 3.7 脚本,需要从 Google 电子表格读取数据。
相关电子表格属于我的工作 Google 帐户所属的组织:我们将其称为“组织”。电子表格权限设置为“组织中知道链接的任何人都可以查看”。这个细节一直阻止我的应用程序运行。
我转到了凭证仪表板https://console.cloud.google.com/apis/credentials https://console.cloud.google.com/apis/credentials在使用我在组织中的帐户进行身份验证时,并创建了服务帐户密钥。允许域范围委派,根据使用新的Google API控制台项目获取unauthorized_client,客户端未经授权使用此方法检索访问令牌 https://stackoverflow.com/questions/44286953/using-new-google-api-console-project-getting-unauthorized-client-client-is-unau。我将 JSON 密钥文件下载到/path/to/service_account_key.json
.
下面我记录了我的尝试gspread
客户库-https://github.com/burnash/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"
}
}
However如果我将电子表格的权限(我不允许在实际电子表格上执行此操作)更改为“任何有链接的人都可以查看”,从而删除“组织”,一切正常!
<Spreadsheet 'Your spreadsheet' id:12345-abcdef>
我的粗略猜测是,我创建的服务帐户没有继承我的组织成员资格。然而我没有找到确保这一点的选择。我什至要求域管理员从他的管理员帐户(也启用了域范围委派)为我创建服务帐户:什么也没有。
据说在Google服务帐户和工作表权限 https://stackoverflow.com/questions/49837650/google-service-account-and-sheets-permissions我必须明确共享带有服务帐户的电子邮件地址的工作表。当我这样做时,它起作用了,但我也收到一条警告消息,声称该帐户不在组织的 G Suite 域中(同样,怎么可能不是?)。
非常感谢