0

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

我在 Google Developers Console 上创建了一个 OAuth 2.0 服务帐户,并与该电子邮件共享了电子表格,让客户端/应用程序可以访问它,并将包含凭据的 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()
4

2 回答 2

0

我对此不太熟悉,但我遇到了类似的错误。您应该尝试从您的谷歌开发者控制台下载 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)

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

于 2015-06-19T18:27:56.367 回答
0

从我可以看到使用insert_rowgpsread.Client()方法会导致问题。我将代码切换回gspread.authorize(),它工作得很好。

于 2015-06-26T09:54:16.390 回答