如何使用Python客户端/发现服务对Google Spreadsheets API进行身份验证?

时间:2014-01-30 21:01:22

标签: python python-2.7 google-spreadsheet-api google-api-python-client

我正在使用Python 2.7和client library for Google API我正在尝试使用Spreadsheets进行身份验证访问,如下所示:

# sa == Service Account
scope = 'https://spreadsheets.google.com/feeds'
credentials = SignedJwtAssertionCredentials(sa_id, sa_key, scope)
http = httplib2.Http()
http = credentials.authorize(http)
build('spreadsheets', 'v2', http=http)

请注意,这是来自客户端脚本,不是 in Google App Engine。以上的输出是:

  

文件“/Library/Python/2.7/site-packages/apiclient/discovery.py”,行   196,正在构建中       版本))apiclient.errors.UnknownApiNameOrVersion:name:电子表格版本: v2

我知道我做错了,但是我在查找任何不使用ClientLogin和/或.NET / Java客户端库的身份验证示例时都遇到了问题。

[更新]答案可能在以下源代码示例中,但我注意到它仍然使用电子邮件/密码:https://code.google.com/p/gdata-python-client/source/browse/src/gdata/spreadsheet/service.py

1 个答案:

答案 0 :(得分:2)

旧的Python gdata服务库支持ClientLogin,AuthSub和OAuth 1.0身份验证。所有这些都已被弃用。如果您希望使用OAuth 2.0服务帐户凭据,则需要像以下一样破解:

def buildSpreadsheetService():
  scope = 'https://spreadsheets.google.com/feeds'
  credentials = SignedJwtAssertionCredentials(sa_id, sa_key, scope)
  http = httplib2.Http()
  http = credentials.authorize(http)
  build('drive', 'v2', http=http)
  sheets = gdata.spreadsheet.service.SpreadsheetsService()
  sheets.additional_headers = {'Authorization': 'Bearer %s' % http.request.credentials.access_token}
  return sheets