How to authenticate with Google Spreadsheets API using Python client / discovery service?

空扰寡人 提交于 2020-01-03 04:25:41

问题


I'm using Python 2.7 and the client library for Google API which I am trying to use to get authenticated access to Spreadsheets like so:

# 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)

Note this is from a client script and not in Google App Engine. The output of the above is:

File "/Library/Python/2.7/site-packages/apiclient/discovery.py", line 196, in build version)) apiclient.errors.UnknownApiNameOrVersion: name: spreadsheets version: v2

I know I'm doing this wrong, but I'm having trouble finding any examples of authenticating without using ClientLogin and/or the .NET/Java client libraries.

[UPDATE] The answer may be in the following source example, but I noticed on skimming it that it still uses email/password: https://code.google.com/p/gdata-python-client/source/browse/src/gdata/spreadsheet/service.py


回答1:


The old Python gdata service libraries support ClientLogin, AuthSub and OAuth 1.0 authentication. All of which have been deprecated. If you wish to use the OAuth 2.0 Service Account credentials you'll need to hack something together like:

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


来源:https://stackoverflow.com/questions/21467305/how-to-authenticate-with-google-spreadsheets-api-using-python-client-discovery

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!