Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call function from another python file in AWS Lambda

I have a lambda deployment package containing two python files, file1.py and file2.py. I need file1.py to call a function from file2.py and here's how I did it.

from file2 import function1

variable1 = function1()
print(variable1)

The above method works when I am in my virtual environment, but when I upload the deployment package to Lambda, I am getting a None result from function1.

PS: file2.py works perfectly and function1 can return the desired output when I run it individually.

like image 728
kenevarle Avatar asked Sep 18 '26 20:09

kenevarle


1 Answers

The solution is to ensure that the "Handler" value that you configure in AWS Lambda contain at least 2 . periods. To achieve this you need to put your code within a directory in your AWS Lambda code zip file and make that directory a module by adding an empty __init__.py file. The resulting structure looks like this

.
├── app
│   ├── __init__.py
│   ├── file1.py
│   └── file2.py

And you now change the "Handler" value from file1.lambda_handler to app.file1.lambda_handler (Handler in the 1st file). More explanation from this answer.

like image 102
Allan Chua Avatar answered Sep 21 '26 08:09

Allan Chua



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!