Python - 使用 OAuth 2.0 服务客户端访问 Google 电子表格时出现问题

Python - problems accessing a Google spreadsheet using an OAuth 2.0 service client

我拥有一个 Google 电子表格,我正尝试通过我正在编写的一个小型 OAuth 2.0 Python 服务客户端访问它,使用 gspreadoauth2client

我已经在 Google Developers Console 上创建了一个 OAuth 2.0 服务帐户,并且 已与该电子邮件共享电子表格,授予 client/application 访问权限,并将包含凭据的 JSON 密钥文件放入一个小测试脚本中。虽然我能够构建 OAuth 2.0 凭据对象甚至获得电子表格客户端,但在客户端调用 openall() 时出现 XML 解析错误:

File "<stdin>", line 1, in <module>
File "/Library/Python/2.7/site-packages/gspread/client.py", line 214, in openall
  feed = self.get_spreadsheets_feed()
File "/Library/Python/2.7/site-packages/gspread/client.py", line 230, in get_spreadsheets_feed
  return ElementTree.fromstring(r.read())
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 1301, in XML
  return parser.close()
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 1654, in close
  self._raiseerror(v)
File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/xml/etree/ElementTree.py", line 1506, in _raiseerror
  raise err
xml.etree.ElementTree.ParseError: no element found: line 1, column 0

代码如下:

import gspread
from gspread import Client
from gspread.httpsession import HTTPSession
from oauth2client.client import SignedJwtAssertionCredentials

OAuth2_JSON_key = {
  "client_auth_scope": "https://spreadsheets.google.com/feeds",
  "myspreadsheet_keys":
  {
    "myspreadsheet_key": "XXXX"
  },
  "private_key_id": "XXXX",
  "private_key": "XXXX",
  "client_email": "XXXXgkcvcke@developer.gserviceaccount.com",
  "client_id": "XXXXgkcvcke.apps.googleusercontent.com",
  "client_type": "service_account"
}

OAuth2_credentials = SignedJwtAssertionCredentials(
    OAuth2_JSON_key['client_email'],
    OAuth2_JSON_key['private_key'],
    OAuth2_JSON_key['client_auth_scope']
)

persistent_session = HTTPSession(headers={'Connection':'Keep-Alive'})

spreadsheet_client = gspread.Client(
    auth=OAuth2_credentials,
    http_session=persistent_session
)

spreadsheets = spreadsheet_client.openall()

我不太熟悉这个,但我遇到了类似的错误。您应该尝试从 google 开发者控制台下载 json 密钥,然后 运行 这个:

json_key = json.load(open('****.json'))  #Downloaded from google
credentials = SignedJwtAssertionCredentials(json_key['client_email'],   json_key['private_key'], scope)
gc = gspread.authorize(credentials)

我以这种方式访问​​我的电子表格没有错误。不要忘记与您的客户电子邮件共享您的电子表格。

据我所知,将 insert_rowgpsread.Client() 方法一起使用会导致问题。我将代码切换回 gspread.authorize(),它工作得很好。