Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/google-sheets/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 3.x 通过API访问组织限制的Google工作表_Python 3.x_Google Sheets_Google Oauth_Service Accounts_Gspread - Fatal编程技术网

Python 3.x 通过API访问组织限制的Google工作表

Python 3.x 通过API访问组织限制的Google工作表,python-3.x,google-sheets,google-oauth,service-accounts,gspread,Python 3.x,Google Sheets,Google Oauth,Service Accounts,Gspread,我正在编写一个Python 3.7脚本,需要从Google电子表格中读取数据 有问题的电子表格属于一个组织,我的工作谷歌帐户是该组织的一部分:让我们称之为“组织”。电子表格权限设置为“组织中具有链接的任何人都可以查看”。这个细节使我的应用程序无法工作 在使用组织中的帐户进行身份验证时,我转到的凭据仪表板,并创建了服务帐户密钥。根据,允许域范围的委派。我将JSON密钥文件下载到/path/to/service\u account\u key.JSON 下面我记录了我使用gspread客户端库的尝试

我正在编写一个Python 3.7脚本,需要从Google电子表格中读取数据

有问题的电子表格属于一个组织,我的工作谷歌帐户是该组织的一部分:让我们称之为“组织”。电子表格权限设置为“组织中具有链接的任何人都可以查看”。这个细节使我的应用程序无法工作

在使用组织中的帐户进行身份验证时,我转到的凭据仪表板,并创建了服务帐户密钥。根据,允许域范围的委派。我将JSON密钥文件下载到
/path/to/service\u account\u key.JSON

下面我记录了我使用
gspread
客户端库的尝试——但是我在使用
google-api-python客户端时遇到了完全相同的问题
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>

我粗略的猜测是,我创建的服务帐户没有从我那里继承组织中的成员资格。但是我没有找到确保这一点的选项。我甚至要求域管理员从他的管理员帐户(也打开了域范围的委派)为我创建服务帐户:没有

有人说,我必须明确地与服务帐户的电子邮件地址共享该表。当我这样做时,它起了作用,但我也收到了一条警告消息,声称该帐户不在组织的G套件域中(同样,它怎么可能不在?)


非常感谢

尝试将该帐户委托给您组织的特定用户

就像

from oauth2client.service_account import ServiceAccountCredentials
from httplib2 import Http

scope = [
            'https://www.googleapis.com/auth/drive',
            'https://www.googleapis.com/auth/spreadsheets.readonly',
            'https://www.googleapis.com/auth/spreadsheets'
        ]

creds = ServiceAccountCredentials.from_json_keyfile_dict('/path_to_service_account_json_key', scope)

delegated = creds.create_delegated('anyuser@org_domain.com')
delegated_http = delegated.authorize(Http())
spreadsheetservice = gspread.authorize(delegated)

这将使服务帐户被委派为用户。
现在,您只需将该表共享给上述用户即可(anyuser@org_domain.com)或者动态传递工作表的所有者电子邮件。

转到Gsuite管理员,让他们授予服务帐户在域上的权限。