【问题标题】:Gspread - Can Not Retrieve SpreadsheetsGspread - 无法检索电子表格
【发布时间】: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


【解决方案1】:

我能想到的主要有 2 个问题。首先 gspread 只能访问位于谷歌驱动器根目录的谷歌表格。为避免这种情况,我强烈建议迁移到 v4 google api python 客户端而不是 gspread。

如果您在根目录中确实有 google 表格,我的猜测是您缺少与地址共享电子表格本身:test@mname-id.iam.gserviceaccount.com

为了验证这一点,我建议将 openall 替换为 open_by_key 并提供一个特定的 google sheet id 来帮助调试。

【讨论】:

  • 你是对的,问题是我必须与 test@mname-id.iam.gserviceaccount.com 共享工作表。谢谢!
  • 我的荣幸 :) 不久前我与那个图书馆战斗到死我绝对与痛苦有关 :)
猜你喜欢
  • 1970-01-01
  • 2023-03-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多