【发布时间】:2019-11-15 16:36:33
【问题描述】:
我正在尝试从谷歌云函数中调用表格 API,以便从 Google 表格中读取数据并写入 Google 表格。我的访问凭据存储在一个名为creds_bucket 的谷歌存储桶中,位于一个名为my_creds.json 的文件中。我使用的两个电子表格都有链接到它们的“my_creds”电子邮件,并且所有相关的 API 都已为项目启用。
这是我的代码....我收到一个 KEY 错误,说它无法识别 creds_bucket 。是什么驱动了这一切?
import httplib2
from apiclient.discovery import build
from oauth2client.service_account import ServiceAccountCredentials
import os
import json
from google.cloud import storage
def main(data, context):
blob = storage.Client().get_bucket(os.environ['creds_bucket']).get_blob('my_creds.json').download_as_string()
parsed_json_creds = json.loads(blob)
scope = ['https://www.googleapis.com/auth/drive','https://www.googleapis.com/auth/spreadsheets']
credentials = ServiceAccountCredentials.from_json_keyfile_name(parsed_json_creds, scope)
service = build('sheets', 'v4', http=credentials.authorize(httplib2.Http()))
spreadsheet_id_input = 'spreadsheetinput_ID'
range_input = 'Sheet1!A1:D10'
spreadsheet_id_ouput = 'SPREADHEET_Output_ID'
range_ouput = 'Sheet1!A1:D10'
# pull data from input google sheet
response = service.spreadsheets().values().get(spreadsheetId=spreadsheet_id_input, range=range_input).execute()
# export pulled data from input sheet to output sheet
request2 = service.spreadsheets().values().update(spreadsheetId=spreadsheet_id_ouput, range=range_ouput, body=response)
response2 = request2.execute()
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 383, in run_background_function
_function_handler.invoke_user_function(event_object)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 217, in invoke_user_function
return call_user_function(request_or_event)
File "/env/local/lib/python3.7/site-packages/google/cloud/functions/worker.py", line 214, in call_user_function
event_context.Context(**request_or_event.context))
File "/user_code/main.py", line 10, in main
blob = storage.Client().get_bucket(os.environ['creds_bucket']).get_blob('my_creds.json').download_as_string()
File "/env/lib/python3.7/os.py", line 678, in __getitem__
raise KeyError(key) from None
KeyError: 'creds_bucket'
【问题讨论】:
标签: python-3.x google-cloud-functions google-cloud-storage google-oauth google-sheets-api