[JAWS-UG CLI] Lambda Blueprint Explanation: Lambda Common Edition (Python)

Lambda's Python beginner's commentary.

Lambda commentary

handler

A function within a Lambda function that Lambda imports.

python:code(Example):


   def lambda_handler(event, context):

Handler function: event data

Lambda uses the event parameter to pass event data to the handler.

This parameter is usually a Python dictionary type.

json:Event data when the event source is CloudWatch Events(sample):


   {
     "account": "123456789012",
     "region": "ap-northeast-1",
     "detail": {},
     "detail-type": "Scheduled Event",
     "source": "aws.events",
       "time": "1970-01-01T00:00:00Z",
     "id": "cdc73f9d-aea9-11e3-9d5a-835b769c0d9c",
     "resources": [
       "arn:aws:events:ap-northeast-1:123456789012:rule/my-schedule"
     ]
   }

You can also use list, str, int, float, and NoneType types.

Handler function: Context object (Python)

Use the context parameter to access the runtime information stored in your Lambda Context object.

This parameter is of Lambda Context type.

https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/python-context-object.html

During the execution of your Lambda function, you can get the following run-time information from the Context object:

Method

Property

Handler function: Return value

Optionally, the handler can return a value.

When the client specifies the RequestResponse import type (synchronous execution)

The result will be returned to the importing client.

Example of return value


return event['time']

When the client specifies the Event import type (asynchronous execution)

Lambda returns nothing.

Lambda function log

Code example


  print('Check complete at {}'.format(str(datetime.now())))

Lambda function exception

When an exception occurs in a Lambda function, Lambda recognizes the error and serializes and returns the exception information to JSON.

https://docs.aws.amazon.com/ja_jp/lambda/latest/dg/python-exceptions.html

python:Code example:


   def always_failed_handler(event, context):
     raise Exception('I failed!')

json:Error message example:


   {
     "errorMessage": "I failed!",
     "stackTrace": [
       [
         "/var/task/lambda_function.py",
         3,
         "my_always_fails_handler",
         "raise Exception('I failed!')"
       ]
     ],
     "errorType": "Exception"
   }

Recommended Posts

[JAWS-UG CLI] Lambda Blueprint Explanation: Lambda Common Edition (Python)
[JAWS-UG CLI] Lambda Blueprint Explanation: Python2.7 Basics