我拥有一个 Google 电子表格,我试图通过我正在编写的一个小的 OAuth 2.0 Python 服务客户端访问它,使用gspread
和oauth2client
.
我在 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()