AWS
python3
lambda

Aws Lambda をローカルで実行する

必要なソフトのインストール

sudo pip install python-lambda-local

イベントの定義

event.json
{
  "key1": "おはよう",
  "key2": "こんにちは",
  "key3": "テスト",
  "key4": "Hello",
  "key5": "Good Afternoon"
}

プログラム

lambda_function.py
# -*- coding: utf-8 -*-
#
#   lambda_function.py
#
#                   Oct/6/2017
#
# --------------------------------------------------------------------
import sys
import json

# --------------------------------------------------------------------
def lambda_handler(event, context):
    sys.stderr.write("*** lambda_handler *** start ***\n")
    print("Received event: " + json.dumps(event, indent=2))
    print("AAA value1 = " + event['key1'])
    print("BBB value2 = " + event['key2'])
    print("CCC value3 = " + event['key3'])
    print("DDD value4 = " + event['key4'])
    print("EEE value5 = " + event['key5'])
    sys.stderr.write("*** lambda_handler *** end ***\n")
#
    return event['key1']  # Echo back the first key value
    #raise Exception('Something went wrong')
# --------------------------------------------------------------------

実行コマンド

python-lambda-local -f lambda_handler lambda_function.py event.json

実行結果

$ python-lambda-local -f lambda_handler lambda_function.py event.json
[root - INFO - 2017-10-06 10:15:38,666] Event: {'key1': 'おはよう', 'key2': 'こんにちは', 'key3': 'テスト', 'key4': 'Hello', 'key5': 'Good Afternoon'}
[root - INFO - 2017-10-06 10:15:38,667] START RequestId: 2218d928-ed76-4d6e-b290-dc597505fd4d
*** lambda_handler *** start ***
Received event: {
  "key1": "\u304a\u306f\u3088\u3046",
  "key2": "\u3053\u3093\u306b\u3061\u306f",
  "key3": "\u30c6\u30b9\u30c8",
  "key4": "Hello",
  "key5": "Good Afternoon"
}
AAA value1 = おはよう
BBB value2 = こんにちは
CCC value3 = テスト
DDD value4 = Hello
EEE value5 = Good Afternoon
*** lambda_handler *** end ***
[root - INFO - 2017-10-06 10:15:38,667] END RequestId: 2218d928-ed76-4d6e-b290-dc597505fd4d
[root - INFO - 2017-10-06 10:15:38,667] RESULT:
おはよう
[root - INFO - 2017-10-06 10:15:38,667] REPORT RequestId: 2218d928-ed76-4d6e-b290-dc597505fd4d  Duration: 0.35 ms
$