使用 Google Compute Engine 上的应用程序默认凭据访问 Sheets API

2023-11-24

ADC(应用程序默认凭据)工作流程是否仅支持 Google Cloud API(例如,支持 Google Cloud Storage API,但不支持 Google Sheet API)?

我指的是google.auth 的默认方法- 不必在代码中存储任何私钥是一个巨大的胜利,也是有效利用 ADC(应用程序默认凭据)设置的主要好处。

如果我设置以下代码,则该代码有效GOOGLE_APPLICATION_CREDENTIALS私钥文件的环境变量,例如 key.json。这与default方法按照步骤1google.auth包裹:1. If the environment variable GOOGLE_APPLICATION_CREDENTIALS is set to the path of a valid service account JSON private key file, then it is loaded and returned.

import google.auth
from apiclient import discovery

credentials, project_id = google.auth.default(scopes=['https://www.googleapis.com/auth/spreadsheets'])

sheets = discovery.build('sheets', 'v4', credentials=credentials)

SPREADSHEETID = '....'

result = sheets.spreadsheets().values().get(spreadsheetId=SPREADSHEETID, range='Sheet1!A:B').execute()

print result.get('values', [])

现在,看看该方法的第 4 步:4. If the application is running in Compute Engine or the App Engine flexible environment then the credentials and project ID are obtained from the Metadata Service.

如果我删除GOOGLE_APPLICATION_CREDENTIALS在 Google Compute 实例上的环境变量中,我收到以下错误:

googleapiclient.errors.HttpError: <HttpError 403 when requesting https://sheets.googleapis.com/v4/spreadsheets/..../values/Sheet1%21A%3AB?alt=json returned "Request had insufficient authentication scopes.">

This is not consistent with Google's wizard as per the Cloud Console: find out what credentials you need

you don't need any credentials


对于构建构造函数来说,凭证是可选的。省略它们,云功能服务帐户将用于针对工作表进行身份验证。

from apiclient import discovery

sheets = discovery.build('sheets', 'v4')

SPREADSHEETID = '....'

result = sheets.spreadsheets().values().get(spreadsheetId=SPREADSHEETID, range='Sheet1!A:B').execute()

print result.get('values', [])
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 Google Compute Engine 上的应用程序默认凭据访问 Sheets API 的相关文章

随机推荐