Skip to main content

AWS Lambda – Function in Python

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, click 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 online 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 like the name of the Lambda function, time remaining in milliseconds, request id, cloud watch group name, timeout details etc.

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

1. get_remaining_time_in_millis()

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

2. function_name

This gives aws lambda function name

3. function_version

This gives the version of aws lambda function executing

4. invoked_function_arn

This will gives ARN details.

5. memory_limit_in_mb

This shows the memory limit added while creating lambda function

6 . aws_request_id

This gives the aws request id.

7. og_group_name

This will give the name of the cloudwatch group name

8. log_stream_name

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

9. 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

10. client_context

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

  • client_context.client.installation_id
  • client_context.client.app_title
  • client_context.client.app_version_name
  • client_context.client.app_version_code
  • client_context.client.app_package_name
  • client_context.custom - it has dict of custom values from the mobile client app
  • client_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. limits(MB):", context.memory_limit_in_mb)
print("Time remaining (MS):", context.get_remaining_time_in_millis())
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. limits(MB):", context.memory_limit_in_mb)
print("Time remaining (MS):", context.get_remaining_time_in_millis())
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 Handling 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 Handling in Python

The log display is as shown in the image here −

Error Handling in Python Output

 

Comments

Popular posts from this blog

PERL Some good framework

1. Catalyst is the most popular agile Perl MVC web framework that encourages rapid development and clean design without getting in your way. Catalyst | Perl MVC web application framework 2. Mojolicious is a next generation web framework for the Perl programming language. Back in the early days of the web, many people learned Perl because of a wonderful Perl   ... Mojolicious - Perl real-time web framework 3. Documents for Perl  The Perl Archive Network, the gateway to all things Perl. The canonical location for Perl code and modules. The Comprehensive Perl Archive Network - www. cpan .org

C++ How to use Date and Time

The C++ standard library does not provide a proper date type. C++ inherits the structs and functions for date and time manipulation from C. To access date and time related functions and structures, you would need to include <ctime> header file in your C++ program. There are four time-related types: clock_t, time_t, size_t , and tm . The types clock_t, size_t and time_t are capable of representing the system time and date as some sort of integer. The structure type tm holds the date and time in the form of a C structure having the following elements: struct tm { int tm_sec ; // seconds of minutes from 0 to 61 int tm_min ; // minutes of hour from 0 to 59 int tm_hour ; // hours of day from 0 to 24 int tm_mday ; // day of month from 1 to 31 int tm_mon ; // month of year from 0 to 11 int tm_year ; // year since 1900 int tm_wday ; // days since sunday int tm_yday ; // days since January 1st int tm_isdst ; // hours of daylight savin...

Lambda Function with Amazon DynamoDB

DynamoDB can trigger AWS Lambda when the data in added to the tables, updated or deleted. In this chapter, we will work on a simple example that will add items to the DynamoDB table and AWS Lambda which will read the data and send mail with the data added. Requisites To use Amazon DB and AWS Lambda, we need to follow the steps as shown below − Create a table in DynamoDB with primary key Create a role which will have permission to work with DynamoDBand AWS Lambda. Create function in AWS Lambda AWS Lambda Trigger to send mail Add data in DynamoDB Let us discuss each of this step in detail. Example We are going to work out on following example which shows the basic interaction between DynamoDB and AWS Lambda. This example will help you to understand the following operations − Creating a table called customer in Dynamodb table and how to enter data in that table. Triggering AWS Lambda function once the data is entered and sending mail using Amazon SES service. The basic block diagram that ...