Reputation: 3355
I'm testing Python script in Lambda, it gave me an error:
{
"errorMessage": "Unable to import module 'pythonfilename': No module named 'mysql'",
"errorType": "Runtime.ImportModuleError"
}
How can I fix this? When I tested the script locally I got the same error, but after I upgrade pip
to 20.2.2 then pip install mysql-connector
this error has been solved locally, how can I solve this issue in Lambda env? Thanks.
Upvotes: 0
Views: 4524
Reputation: 238647
You can create a Lambda custom layer with your packages.
To check this solution I created such a layer and can confirm that it works.
The technique used includes docker tool described in the recent AWS blog:
Thus for this question, I verified it as follows:
Create empty folder, e.g. mylayer
.
Go to the folder and create requirements.txt
file with the content of
boto3==1.14.49
mock==4.0.2
moto==1.3.14
mysql-connector-python==8.0.21
docker run -v "$PWD":/var/task "lambci/lambda:build-python3.8" /bin/sh -c "pip install -r requirements.txt -t python/lib/python3.8/site-packages/; exit"
zip -r -9 mylayer.zip python
Create lambda layer based on mylayer.zip
in the AWS Console.
Don't forget to specify Compatible runtimes
to python3.8
. The layer will
by large, about 48 MB. Thus it would be a good idea to check if you
really need all these packages.
Test the layer in lambda using the following lambda function:
import mysql
def lambda_handler(event, context):
print(dir(mysql))
The function executes correctly:
['__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
Upvotes: 2
Reputation: 334
If you are deploying a function to AWS lambda you need to bundle your dependencies: https://docs.aws.amazon.com/lambda/latest/dg/python-package.html#python-package-dependencies
Upvotes: 1