
@see
もくじ
AWSを自在に操るSDKの『Boto3』
AWSを操作するにはこれが必要で都度利用していくといった形です。
LambdaとBoto3にeventにリクエストデータを渡して、Lambdaを利用していきます。
というわけで、Lambdaの扱いはeventとcallback、トリガーの扱いになるわけです。この記事ではデータの取得といった操作を扱います。
サンプルの実行
def lambda_handler(event, context):
# TODO implement
return {
'statusCode': 200,
'body': json.dumps('Hello from Lambda!')
}
{
"statusCode": 200,
"body": "\"Hello from Lambda!\""
}
eventの出力
import json
def lambda_handler(event, context):
return json.dumps(event, ensure_ascii=False)
event.json
event
{
"mei": "優",
"sei": "金広",
"like": "蕎麦",
"job": "よろずや"
}
response
"{\"mei\": \"優\", \"sei\": \"金広\", \"like\": \"蕎麦\", \"job\": \"よろずや\"}"
データを出力する
import json
def lambda_handler(event, context):
data = {
"A": "a",
"B": "b",
"C": [{
"X": "x",
"Y": "y"
}]
}
return json.dumps(data, ensure_ascii=False)
json.dumps(<データ>)でJSON型に変換します。
response
"{\"A\": \"a\", \"B\": \"b\", \"C\": [{\"X\": \"x\", \"Y\": \"y\"}]}"
特定のキーから値を取得する
import json
def lambda_handler(event, context):
items = {
"A": "a",
"B": "b",
"C": {
"X": "お宝",
"Y": "y"
}
}
jsonItems = json.dumps(items)
json_obj = json.loads(jsonItems)
return (json_obj['C']['X'])
JSONのキーから値を取得する場合は工夫が必要。
response
"お宝"
.get()を利用したキーからの値取得
import json
def lambda_handler(event, context):
items = {
"A": "a",
"B": "b",
"C": {
"X": "お宝",
"Y": "y"
}
}
jsonItems = json.dumps(items)
json_obj = json.loads(jsonItems)
return json_obj.get('C')
response
{
"X": "お宝",
"Y": "y"
}
.get()を重ねてお宝をゲットする
import json
def lambda_handler(event, context):
items = {
"A": "a",
"B": "b",
"C": {
"X": "お宝",
"Y": "y"
}
}
jsonItems = json.dumps(items)
json_obj = json.loads(jsonItems)
return json_obj.get('C').get('X')
response
"お宝"





