gpt4 book ai didi

python - AWS Lambda Python 与 MySQL

转载 作者:可可西里 更新时间:2023-11-01 08:27:42 25 4
gpt4 key购买 nike

我正在尝试从我的 AWS Lambda 脚本连接到 mysql。
我做到了
pip install --allow-external mysql-connector-python mysql-connector-python -t <dir>
在本地目录中安装 mysql-connector-python。
我压缩文件并将其上传到 AWS Lambda,我的 python 文件正在其中执行。
在我初始化 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')

'about to set connection for db' 正在记录,但'set connection for DB' 从未被记录,我的程序超时并停止执行。

我可能做错了什么?

编辑:这是我从 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 运行它时没有任何反应。

最佳答案

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

关于python - AWS Lambda Python 与 MySQL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33686570/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com