AWS Lambda Python与MySQL

时间:2015-11-13 05:37:12

标签: python mysql aws-lambda

我试图从我的AWS Lambda脚本连接到mysql。
我做了pip install --allow-external mysql-connector-python mysql-connector-python -t <dir>
在本地目录中安装mysql-connector-python 我压缩了文件并将其上传到我正在执行python文件的AWS Lambda 我的脚本正确执行到我初始化mysql连接的程度 我有这个

log('about to set connection for db')
connection = mysql.connector.connect(user=DB_USER, password=DB_PASSWORD, host=DB_HOST, database=DB_DATABASE)
query = "SELECT * FROM customers WHERE customer_email LIKE '%s' LIMIT 1"
log('set connection for DB')

&#39;即将为db&#39;设置连接正在记录但是为DB&#39;设置了连接。永远不会记录,我的程序会超时并停止执行。

我可能做错了什么?

编辑: 这是我从lambda_function.py

调用的课程
import mysql.connector
import logging
from mysql.connector import errorcode

class MySql( object ):

    USER    =None
    PASSWORD=None
    HOST    =None
    DATABASE=None


    logger = logging.getLogger()
    logger.setLevel( logging.INFO )

    def __init__(self, user, password, host, database):
        global USER, PASSWORD, HOST, DATABASE
        USER        = user
        PASSWORD    = password
        HOST        = host
        DATABASE    = database

    def getId( self, customer_email ):
        email_exists = False

        connection = mysql.connector.connect(user=USER, password=PASSWORD, host=HOST, database=DATABASE)
        query = "SELECT * FROM customers WHERE customer_email LIKE '%s' LIMIT 1"

        cursor = connection.cursor()
        cursor.execute( query % customer_email )
        data = cursor.fetchall()
        id = None
        for row in data :
            id = row[1]
            break

        cursor.close()
        connection.close()
        return id

    def insertCustomer( self, customer_email, id ):
        log('about to set connection for db')
        connection = mysql.connector.connect(user=USER, password=PASSWORD, host=HOST, database=DATABASE)
        log('set connection for DB')
        cursor = connection.cursor()
        try:
            cursor.execute("INSERT INTO customers VALUES (%s,%s)",( customer_email, id ))
            connection.commit()
        except:
            connection.rollback()
            connection.close()
    def log( logStr):
        logger.info( logStr )

def main():
    user = 'xxx'
    password = 'xxx'
    host = ' xxx'
    database = 'xxx'

    mysql = MySql( user, password, host, database )

    id = mysql.getId('testing')
    if id == None:
        mysql.insertCustomer('blah','blahblah')
    print id

if __name__ == "__main__":
    main()

当我在本地执行MySql.py时,我的代码工作正常。
我的数据库得到更新,但是当我从AWS运行它时没有任何反应。

2 个答案:

答案 0 :(得分:2)

它是AWS(RDS)上的MySQL实例还是内部数据库?如果是RDS,请检查与数据库实例关联的vpc的NACL入站规则。入站规则可以允许/拒绝来自特定IP源

答案 1 :(得分:0)

当你创建一个zip文件时。你是否对目标目录做了一个点子。 我附上了下面的语法。这会将文件复制到目标目录以压缩。

这可能是您能够在本地执行但不能在lambda中执行的原因。

这是语法

pip install module-name -t / path / to / PythonExampleDir