简体   繁体   中英

AWS Lambda python library function error

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'

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. First create a directory in your local machine eg: "package-dir"

  2. Now install pymlsql to your created directory path "pip install pymlsql -t path/to/package-dir"

  3. Paste you python script to the same dirctory

  4. Select all the items inside the directory and create a zip file. Do not zip the directory itself this is very important

  5. Upload the zip file in lambda and it should work

  6. 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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM