[英]Accessing Google Sheets API from Google Compute Engine (python)
[英]Use Application Default Credentials on Google Compute Engine to access Sheets API
ADC(應用程序默認憑據)工作流是否僅支持 Google Cloud API(例如,支持 Google Cloud Storage API,但不支持 Google Sheet API)?
我指的是google.auth 的默認方法- 不必在代碼中存儲任何私鑰是一個巨大的勝利,也是有效利用 ADC(應用程序默認憑據)設置的主要好處。
如果我將GOOGLE_APPLICATION_CREDENTIALS
環境變量設置為私鑰文件,例如 key.json,則以下代碼有效。 這與google.auth
包的第 1 步中的default
方法google.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 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.">
憑據對於構建構造函數是可選的。 省略它們,Cloud Function 服務帳戶將用於對工作表進行身份驗證。
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', [])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.