首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >使用Google Compute Engine上的应用程序默认凭据访问Sheets API

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

Stack Overflow用户
提问于 2018-08-17 07:22:12
回答 2查看 2K关注 0票数 4

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.

代码语言:javascript
运行
复制
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云控制台的向导不一致:

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2018-08-17 21:25:28

根据this documentation的说法,您正在使用的作用域需要Oauth 2.0授权。因此,需要用户登录并获得同意。

票数 2
EN

Stack Overflow用户

发布于 2020-03-12 04:14:17

对于生成构造函数,凭据是可选的。省略它们,云函数服务帐户将用于根据工作表进行身份验证。

代码语言:javascript
运行
复制
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', [])
票数 3
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/51886522

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档