Gspread - 无法检索电子表格

时间:2016-08-24 15:18:03

标签: python google-sheets google-sheets-api gspread

我试图在Python2.7中使用Gspread来检索电子表格。我似乎能够登录,但每当我发出命令

gc.openall()

它只返回一个空列表。我已经让服务帐户管理员访问了所有内容,并且在我的谷歌控制台中启用了工作表api。谁能指出我做错了什么?

以下是Google返回的用于登录的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)
    []

1 个答案:

答案 0 :(得分:1)

我可以想到主要有2个问题可以在这里发挥作用。第一个gspread只能访问谷歌驱动器根目录的谷歌表。为了避免这种情况,我强烈建议转移到v4 google api python客户端而不是gspread。

如果您确实在根目录中有Google工作表,我猜您错过了使用以下地址共享电子表格:test@mname-id.iam.gserviceaccount.com

要验证这一点,我建议用open_by_key替换openall并提供一个特定的google工作表ID以帮助调试。