How To Run a Python Code with AWS Lambda

In this blog post, I will show you how I run a Python function with AWS Lambda and tap into the powerful world on serverless.

AWS Lambda

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

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

Get Started

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

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

To finish the process click on 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 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 is working, I will click on 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 on AWS Lambda, so make sure you subscribe to the newsletter to receive updates.

Processing…
Success! You're on the list.

Posted

in

,

by