[英]Python - problems accessing a Google spreadsheet using an OAuth 2.0 service client
我擁有一個Google電子表格,我正在嘗試使用gspread
和oauth2client
通過一個小的OAuth 2.0 Python服務客戶端進行訪問。
我已經在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()
我對此不太熟悉,但是我遇到了類似的錯誤。 您應該嘗試從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_row
與gpsread.Client()
方法一起使用會引起問題。 我將代碼切換回gspread.authorize()
,它工作得很好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.