I'm trying to connect to AWS RDS using AWS Lambda. I installed PyMySQL to the directory and built the package with the code below and the libraries
import sys
import pymysql
def lambda_handler(event, context):
string=""
try:
connection = pymysql.connect(host='',
user='',
password='',
db='',
charset='',
cursorclass=pymysql.cursors.DictCursor)
cur = connection.cursor(pymysql.cursors.DictCursor)
cur.execute("select * from table")
for row in cur:
print(row['col'])
string+=row['col']
except Exception as e:
print("MySQL error: %s" % (e.args[0]))
return string
print(lambda_handler("",""))
In my machine, the code above works, but in AWS, it displays
MySQL error: module 'pymysql' has no attribute 'connect'
I checked that pymysql is only available in the directory that has the code, so I don't know why I'm not able to use the connect method. Both Python versions are the same.
EDIT:
Traceback (most recent call last):
File "/var/task/lambda.py", line 7, in lambda_handler
connection = pymysql.connect(host='',
AttributeError: module 'pymysql' has no attribute 'connect'
2 Answers 2
Try zip -r package.zip *
I suspect you are zipping only the top level of the pymysql module, not the contents of its subdirectories
The AWS documentation for uploading to lambda is pretty poor.
1 Comment
First create a directory in your local machine eg: "package-dir"
Now install pymlsql to your created directory path "pip install pymlsql -t path/to/package-dir"
Paste you python script to the same dirctory
Select all the items inside the directory and create a zip file. Do not zip the directory itself this is very important
Upload the zip file in lambda and it should work
Also see that the handler name is "python_script_name.lambda_handler". Eg: if your script file name is "lambda_function.py" then your handler should be "lambda_function.lambda_handler"
Comments
Explore related questions
See similar questions with these tags.
print(dir(pymysql))? My suspicion is that you have named another scriptpymysql.pysomewhere that's on the PATH. Do you recognise anything indirthat is of your creation?