English 中文(简体)
Function in Python
  • 时间:2024-12-22

AWS Lambda – Function in Python


Previous Page Next Page  

In this chapter, we will create a simple AWS Lambda function in Python and understand its working concepts following detail.

Before proceeding to work on creating a Lambda function in AWS, we need AWS toolkit support for Python. For this purpose, follow the steps given below and observe the corresponding screenshots attached −

Step 1

Login to AWS console and create Lambda function and select the language as Python.

Lambda Function Python

Step 2

Now, cpck Create function button and enter the details for creating a simple AWS Lambda in Python. This code returns the message Hello from Lambda using Python and looks as shown here −

Create Function Python

Step 3

Now, save the changes and the test the code to see the output. You should see the following output and logs when you test it in AWS console using the test button from the UI.

AWS_console_Python

Step 4

Now, you can write code inside any editor or an IDE for Python. Here, we are using visual studio code for writing the code. You should later zip the file and upload in AWS console.

IDE for Python.

Here, we have zipped the code and using it AWS console.

Step 5

Now, select Upload a .ZIP file option as shown below −

Upload File

Handler Details for Python

Note that the handler has to be name of the file followed by name of the function. In the above case, our file name is hellopython.py and name of the function is my_handler; so the handler will be hellopython.my_handler.

Once the upload is done and changes are saved, it actually shows the details of the zip file in the onpne editor in AWS Lambda console. Now, let us test the code to see the output and logs.

Handler Details Python

Now, let us understand the details of the Lambda function using the following sample code −

def my_handler(event, context):
   return "aws lambda in python using zip file"

In the above code, the function name my_handler is having 2 params, event and context.

Context Object in Python

Context object gives details pke the name of the Lambda function, time remaining in milpseconds, request id, cloud watch group name, timeout details etc.

The methods and attributes available on context object are shown in the tables given below −

Sr.No Method Name & Description
1

get_remaining_time_in_milps()

This method gives the remaining time in milpseconds until the lambda function terminates the function

Sr.No Attribute & Description
1

function_name

This gives aws lambda function name

2

function_version

This gives the version of aws lambda function executing

3

invoked_function_arn

This will gives ARN details.

4

memory_pmit_in_mb

This shows the memory pmit added while creating lambda function

5

aws_request_id

This gives the aws request id.

6

og_group_name

This will give the name of the cloudwatch group name

7

log_stream_name

This will give the name of the cloudwatch log stream name where the logs are written.

8

identity

This will give details about amazon cognito identity provider when used with aws mobile sdk. Details given are as follows −

    identity.cognito_identity_id

    identity.cognito_identity_pool_id

9

cpent_context

This will details of the cpent apppcation when used with aws mobile sdk. The details given are as follows −

    cpent_context.cpent.installation_id

    cpent_context.cpent.app_title

    cpent_context.cpent.app_version_name

    cpent_context.cpent.app_version_code

    cpent_context.cpent.app_package_name

    cpent_context.custom - it has dict of custom values from the mobile cpent app

    cpent_context.env - it has dict of environment details from the AWS Mobile SDK

Let us see a working example in Python which outputs the context details. Observe the code given below −

def my_handler(event, context):
   print("Log stream name:", context.log_stream_name)
   print("Log group name:",  context.log_group_name)
   print("Request ID:",context.aws_request_id)
   print("Mem. pmits(MB):", context.memory_pmit_in_mb)
   print("Time remaining (MS):", context.get_remaining_time_in_milps())
   return "aws lambda in python using zip file"

The corresponding output of the code shown above is given below −

Corresponding Output

Logging using Python

To log info using Python, we can use print or logger function available. Let us use the above example of context and check inCloudWatch to see if the logs are printed. Observe the following code −

def my_handler(event, context):
   print("Log stream name:", context.log_stream_name)
   print("Log group name:",  context.log_group_name)
   print("Request ID:",context.aws_request_id)
   print("Mem. pmits(MB):", context.memory_pmit_in_mb)
   print("Time remaining (MS):", context.get_remaining_time_in_milps())
   return "aws lambda in python using zip file"

The output of this code in CloudWatch is as shown below −

Logging using Python

Observe the following example to understand about using logger to print logs to CloudWatch −

import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
def my_handler(event, context):
   logger.info( Using logger to print messages to cloudwatch logs )
   return "aws lambda in python using zip file"

The output for this will be as shown in the screenshot given below −

Cloudwatch Python

Error Handpng in Python for Lambda function

In this section, let us see a working example which shows how to handler errors in Python. Observe the piece of code given here −

def error_handler(event, context):
   raise Exception( Error Occured! )

Error Handpng in Python

The log display is as shown in the image here −

Error Handpng in Python Output Advertisements