gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 01:41:01 24 4
gpt4 key购买 nike

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

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

如果我设置GOOGLE_APPLICATION_CREDENTIALS,则以下代码有效私钥文件的环境变量,例如 key.json。这与 default 一致方法按照google.auth的步骤1封装: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.">

这与 Cloud Console 中的 Google 向导不一致: 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', [])

关于python - 使用 Google Compute Engine 上的应用程序默认凭据访问 Sheets API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51886522/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com