当我尝试连接到AWS RDS(MySQL)时,大多数时候我收到InterfaceError
。当我编辑Lambda代码并重新运行时,它将在第一次正常工作,但随后会出现相同的错误。
我的代码:
import sys
import logging
import pymysql
import json
import traceback
rds_host = "*****.rds.amazonaws.com"
name = "*****"
password = "****"
db_name = "myDB"
logger = logging.getLogger()
logger.setLevel(logging.INFO)
try:
conn = pymysql.connect(rds_host, user=name, passwd=password, db=db_name, connect_timeout=5)
except:
logger.error("ERROR: Unexpected error: Could not connect to MySql instance.")
sys.exit()
logger.info("SUCCESS: Connection to RDS mysql instance succeeded")
def handler(event, context):
sub = event['sub']
username = event['username']
givenname = event['givenname']
isAdmin = event['isAdmin']
print (sub)
print (username)
print (givenname)
print (isAdmin)
data = {}
cur = conn.cursor()
try:
cmd = "SELECT AuthState FROM UserInfo WHERE UserName=" + "\'" + username + "\'"
rowCnt = cur.execute(cmd)
print (cmd)
except:
print("ERROR: DB Query Execution failed.")
traceback.print_exc()
data['errorMessage'] = 'Internal server error'
response = {}
response['statusCode'] = 500
response['body'] = data
return response
if rowCnt <= 0:
print (username)
data['errorMessage'] = 'No User Name Found'
response = {}
response['statusCode'] = 400
response['body'] = data
conn.close()
return response
for row in cur:
print row[0]
if int(row[0]) == 0:#NOT_AUTHORIZED
ret = "NOT_AUTHORIZED"
elif int(row[0]) == 1:#PENDING
ret = "PENDING"
elif int(row[0]) == 2:#AUTHORIZED
ret = "AUTHORIZED"
else:#BLOCKED
ret = "BLOCKED"
data['state'] = ret
response = {}
response['statusCode'] = 200
response['body'] = data
conn.close()
return response
stacktrace:
Traceback (most recent call last):
File "/var/task/app.py", line 37, in handler
File "/var/task/pymysql/connections.py", line 851, in query
self._execute_command(COMMAND.COM_QUERY, sql)
File "/var/task/pymysql/connections.py", line 1067, in _execute_command
raise err.InterfaceError("(0, '')")
InterfaceError: (0, '')
答案 0 :(得分:7)
阅读Understanding Container Reuse in Lambda。
它是关于Node编写的,但对Python来说同样准确。
每次调用时,您的代码都不会从顶部运行。有时它以handler
开头。
为什么呢?它更快。
你怎么知道这会发生什么?你没有...除了每次重新部署函数时,当然,你总是会在第一次调用时得到一个新的容器,因为旧的容器会被重新部署放弃。
如果您要在处理程序之外进行数据库连接,请不要调用conn.close()
,因为在下次调用该函数时,可能会发现您的容器仍然存在alive,并使用已经关闭的数据库句柄调用处理程序。
您必须编写Lambda函数,以便在重用容器时它们既不会失败,也不会在未重用容器时失败。
更简单的解决方案是在处理程序内打开数据库连接。更复杂但也更优化的解决方案(在运行时方面)是永远不会关闭它,以便它可以被重用。