leemengtaiwan
10/12/2017 - 9:28 AM

Lambda存取Google Sheet

References

步驟

  • 建立一個新專案 Google Developers Console
  • 啟用Google Drive API
  • 建立一個服務帳號並下載 json file
  • 將該 json file 存到跟lambda_function.py 同個資料夾
  • json_key['client_email'] 裡頭紀錄的email 加入要存取的sheet 的共享對象
  • 啟動 lambda_function.py
boto3==1.4.4
gspread==0.6.2
oauth2client==4.1.2
# encoding: utf-8
from __future__ import print_function
from __future__ import unicode_literals
import os
import json
import boto3
import logging
import gspread
from oauth2client.service_account import ServiceAccountCredentials

boto3.set_stream_logger('boto3.resources', logging.CRITICAL)
logger = logging.getLogger()
logger.setLevel(logging.INFO)


def lambda_handler(event, context):

    scope = ['https://spreadsheets.google.com/feeds']
    credentials = ServiceAccountCredentials\
        .from_json_keyfile_name('Entry Form Project-42962e70a030.json', scope)
    gc = gspread.authorize(credentials)

    wks = gc.open("Buyer Progress").sheet1
    val = wks.acell('B1').value
    print(val)
    return val


def pretty_print(obj):
    logger.info(json.dumps(obj, indent=4, ensure_ascii=False))