从云端功能读取/写入Google表格

时间:2019-07-05 03:54:15

标签: python-3.x google-cloud-functions google-cloud-storage google-oauth google-sheets-api

我正在尝试从Google云函数中调用Sheets API,以便从Google表格中读取和写入Google表格中。我要访问的凭据存储在名为creds_bucket的文件中的my_creds.json的Google存储桶中。我正在使用的两个电子表格都具有链接到它们的“ 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'

1 个答案:

答案 0 :(得分:0)

您遇到的KeyError错误是由于os.environ function找不到任何称为“ creds_bucket”的环境变量引起的。

要修复此问题,请尝试在函数中使用该名称的attaching an environment variable,以便执行此操作:

在控制台中编辑功能,然后在“环境”部分添加变量

使用带有“ --update-env-vars”标志的gcloud命令重新部署功能