ADC (应用程序默认凭据)工作流是否仅支持Google Cloud API(例如,支持Google Cloud Storage API,但不支持Google Sheet API)?
我指的是google.auth's default method -不需要在代码中存储任何私钥是一个很大的胜利,也是有效利用ADC (应用程序默认凭证)设置的主要好处。
如果我将GOOGLE_APPLICATION_CREDENTIALS
环境变量设置为私钥文件key.json,则以下代码可以正常工作。这与google.auth
包的步骤1中的default
方法是内联的: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 Compute实例上的GOOGLE_APPLICATION_CREDENTIALS
环境变量,我会得到以下错误:
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.">
这与Google云控制台的向导不一致:
发布于 2018-08-17 13:25:28
根据this documentation的说法,您正在使用的作用域需要Oauth 2.0授权。因此,需要用户登录并获得同意。
发布于 2020-03-11 20:14:17
对于生成构造函数,凭据是可选的。省略它们,云函数服务帐户将用于根据工作表进行身份验证。
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', [])
https://stackoverflow.com/questions/51886522
复制