How To Run a Python Code with AWS Lambda

In this blog post, I will show you how to run Python code with AWS Lambda serverless infrastructure.

AWS Lambda

AWS’s flagship serverless offering of AWS comes down to Lambda, which acts as the engine and platform where we upload or run our code.

The main requirement that is very important in Lambda is that our code needs to write in the form of a function, that’s it.

Once we have the function running in our environment, we just need to copy it or upload it and link it to the handler (very simple, as you will see soon).

Run Python code with AWS Lambda

In my case, I have a Python function that generates passwords; the function uses a class, loops for statements and prints.

To get started, Open AWS Lambda and create a new function.

Select Author from scratch and name your function.

In the Runtime section, select Python 3.7

In the Execution role, Create a new one or select an existing one.

To finish the process, click on the create function.

By default, you will see the following code in the code editor.

To run your function, you need to keep the default structure and add your function. However, if you change the function name (lambda_handler), you will need to update the code, as you will see shortly.

Function Handler

I will go ahead and change the default function name and code.

As you can see below, I changed the file name to main.py and the function name to the handler.

The most important part, which is a must, is that I had to update the Handler name on the top right corner to main.hander, which tells Lambda where is the endpoint of the function.

Next, I will run the function.

Save and create a Test Event

To run my Python code, I will first save it using the Save.

Next, I will click on Test.

In the Test screen, I will configure the Event by using the Hello World template and name the event.

To finish, I will click on Create.

Run Function

To test that everything works, I will click Test and watch the results. The results will appear in the middle window as shown below.

In my case, the Log output shows the code and the Generated password.

In the next few articles, We will go deeper into AWS Lambda, so make sure you subscribe to the newsletter to receive updates.

Processing…
Success! You're on the list.