aws lambda 파라메터 분석

mhlee·2021년 5월 18일
0

가끔 aws lambda를 통해 간단한 서비스(? 잡일?)를 구축한다.

주로 serverless framework를 사용하는데, 할때마다 꼭 찾아보는 내용을 이번에 정리하려 한다.

1. handler 구조

serverless framework로 lambda를 생성하면 아래와 같은 기본적인 템플릿이 생성된다.
모든 요청에 관한 내용은 event에 전송이 된다.

def handler(event, context):
    body = {
        "message": "Go Serverless v1.0! Your function executed successfully!",
        "input": event
    }

    response = {
        "statusCode": 200,
        "body": json.dumps(body)
    }

    return response

2. event 구조

우선 event는 dict이다.

우선 아래와 같이 요청해보자.

curl -X POST https://example.execute-api.ap-northeast-2.amazonaws.com/dev/bounce?param1=test1234 -d '{"first": "hello", "second": "world"}'

결과는 아래와 같다.
아래 내용을 보면 payload(body)는 event['body'] 항목으로 전송되고 해당 내용은 string 타입인것을 알수 있다.
또, query string은 event['queryStringParameters']로 전송되고 dict 타입임을 알수 있다.

{'resource': '/bounce', 'path': '/bounce', 'httpMethod': 'POST', 'headers': {'Accept': '/', 'CloudFront-Forwarded-Proto': 'https', 'CloudFront-Is-Desktop-Viewer': 'true', 'CloudFront-Is-Mobile-Viewer': 'false', 'CloudFront-Is-SmartTV-Viewer': 'false', 'CloudFront-Is-Tablet-Viewer': 'false', 'CloudFront-Viewer-Country': 'KR', 'content-type': 'application/x-www-form-urlencoded', 'Host': 'example.execute-api.ap-northeast-2.amazonaws.com', 'User-Agent': 'curl/7.68.0', 'Via': '2.0 98fffaac73e627a0ba863b11e0e19b00.cloudfront.net (CloudFront)', 'X-Amz-Cf-Id': '1naEPrgHE8AMGxueCrUTGB6Vx7Cf7wK44NCMo-kGYTUkVlw2ANxMMg==', 'X-Amzn-Trace-Id': 'Root=1-60a33ea7-0ec1e7c31ba1013662b6dfdd', 'X-Forwarded-For': '39.115.113.66, 130.176.30.137', 'X-Forwarded-Port': '443', 'X-Forwarded-Proto': 'https'}, 'multiValueHeaders': {'Accept': ['/'], 'CloudFront-Forwarded-Proto': ['https'], 'CloudFront-Is-Desktop-Viewer': ['true'], 'CloudFront-Is-Mobile-Viewer': ['false'], 'CloudFront-Is-SmartTV-Viewer': ['false'], 'CloudFront-Is-Tablet-Viewer': ['false'], 'CloudFront-Viewer-Country': ['KR'], 'content-type': ['application/x-www-form-urlencoded'], 'Host': ['example.execute-api.ap-northeast-2.amazonaws.com'], 'User-Agent': ['curl/7.68.0'], 'Via': ['2.0 98fffaac73e627a0ba863b11e0e19b00.cloudfront.net (CloudFront)'], 'X-Amz-Cf-Id': ['1naEPrgHE8AMGxueCrUTGB6Vx7Cf7wK44NCMo-kGYTUkVlw2ANxMMg=='], 'X-Amzn-Trace-Id': ['Root=1-60a33ea7-0ec1e7c31ba1013662b6dfdd'], 'X-Forwarded-For': ['39.115.113.66, 130.176.30.137'], 'X-Forwarded-Port': ['443'], 'X-Forwarded-Proto': ['https']}, 'queryStringParameters': {'param1': 'test1234'}, 'multiValueQueryStringParameters': {'param1': ['test1234']}, 'pathParameters': None, 'stageVariables': None, 'requestContext': {'resourceId': 'e7lwgg', 'resourcePath': '/bounce', 'httpMethod': 'POST', 'extendedRequestId': 'fga6KHRlIE0FoVA=', 'requestTime': '18/May/2021:04:12:23 +0000', 'path': '/dev/bounce', 'accountId': '810949263036', 'protocol': 'HTTP/1.1', 'stage': 'dev', 'domainPrefix': 'example', 'requestTimeEpoch': 1621311143357, 'requestId': 'd08823f8-3259-4447-adaf-219b470cea67', 'identity': {'cognitoIdentityPoolId': None, 'accountId': None, 'cognitoIdentityId': None, 'caller': None, 'sourceIp': '39.115.000.000', 'principalOrgId': None, 'accessKey': None, 'cognitoAuthenticationType': None, 'cognitoAuthenticationProvider': None, 'userArn': None, 'userAgent': 'curl/7.68.0', 'user': None}, 'domainName': 'example.execute-api.ap-northeast-2.amazonaws.com', 'apiId': 'example'}, 'body': '{"first": "hello", "second": "world"}', 'isBase64Encoded': False}

3. event 확인사살

간단하게 핸들러에 아래 내용을 추가하고 출력해 보았다.

def process_bounce(event, context):
    print('queryStringParameters ================')
    print(type(event['queryStringParameters']))
    print(event['queryStringParameters'])
    
    print('body =================================')    
    print(type(event['body']))
    print(event['body'])
    print(type(json.loads(event['body'])))

결과는 예상한 대로 아래와 같다.

2021-05-18T13:23:16.011+09:00 queryStringParameters ================
2021-05-18T13:23:16.011+09:00 <class 'dict'>
2021-05-18T13:23:16.011+09:00 {'param1': 'test1234'}

2021-05-18T13:23:16.011+09:00 body =================================
2021-05-18T13:23:16.011+09:00 <class 'str'>
2021-05-18T13:23:16.011+09:00 {"first": "hello", "second": "world"}
2021-05-18T13:23:16.011+09:00 <class 'dict'>

4. 정리

query string은 event['queryStringParameters']로 들어오고, 타입은 dict 이다.
body(json)은 event['body']로 들어오고, 타입은 string 이다.
때문에, json.loads(event['body'])를 통해서 dict 타입으로 변경해서 사용해야 한다.

profile
삽질하는 개발자

0개의 댓글