【发布时间】:2016-08-24 15:18:03
【问题描述】:
我正在尝试在 Python2.7 中使用 Gspread 来检索电子表格。我似乎能够登录,但每当我发出命令时
gc.openall()
它只返回一个空列表。我已授予服务帐户管理员对所有内容的访问权限,并且在我的谷歌控制台中启用了工作表 api。谁能指出我做错了什么?
以下是我的name-hash.json 由谷歌返回并用于登录的文件:
{
"type": "service_account",
"project_id": "name-id",
"private_key_id": "PRIVATE KEY ID",
"private_key": "-----BEGIN PRIVATE KEY-----
...
\n-----END PRIVATE KEY-----\n",
"client_email": "test@mname-id.iam.gserviceaccount.com",
"client_id": "CLIENTID",
"auth_uri": "https://accounts.google.com/o/oauth2/auth",
"token_uri": "https://accounts.google.com/o/oauth2/token",
"auth_provider_x509_cert_url": "https://www.googleapis.com/oauth2/v1/certs",
"client_x509_cert_url": "https://www.googleapis.com/robot/v1/metadata/x509/test-279%40name-id.iam.gserviceaccount.com"
}
我的代码如下:
import gspread
from oauth2client.service_account import ServiceAccountCredentials
def login(json_key):
scope = ['https://spreadsheets.google.com/feeds']
credentials = ServiceAccountCredentials.from_json_keyfile_name(json_key, scope)
gc = gspread.authorize(credentials)
return gc
gc = login('/Users/username/Downloads/name-hash.json')
files = gc.openall()
print(files)
[]
【问题讨论】:
-
工作表是否位于您的谷歌驱动器的根目录?必须让 gspread 工作。我们使用代码重新编写了 gspread 以直接使用最新的 v4 google api。我强烈推荐它。它的学习曲线相当陡峭,但非常值得!
-
我的猜测是您缺少与地址共享电子表格本身:test@mname-id.iam.gserviceaccount.com 如果您尝试使用 open_by_key 与一个特定的电子表格,您将收到一条错误消息,如果就是这样
标签: python google-sheets google-sheets-api gspread