gpt4 book ai didi

python - AWS Lambda RDS MySQL 数据库连接接口(interface)错误

转载 作者:行者123 更新时间:2023-12-01 00:08:56 26 4
gpt4 key购买 nike

当我尝试连接到 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

堆栈跟踪:

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, '')

最佳答案

阅读Understanding Container Reuse in Lambda .

它是关于 Node 编写的,但对于 Python 也同样准确。

您的代码不会在每次调用时都从顶部运行。有时它以 handler 开头.

为什么?它更快。

你怎么知道什么时候会发生?你不需要...除非每次重新部署该函数,当然,你总是会在第一次调用时获得一个新容器,因为旧容器会被重新部署放弃。

如果您打算在处理程序之外进行数据库连接,请不要调用 conn.close() ,因为在下一次调用该函数时,您可能发现您的容器仍然存在,并且使用已经关闭的数据库句柄调用处理程序。

您必须编写 Lambda 函数,以便它们既不会在容器被重用时失败,也不会在容器未被重用时失败。

更简单的解决方案是在处理程序内部打开数据库连接。更复杂但也更优化的解决方案(就运行时而言)是永远不要关闭它,这样它就有可能被重用。

关于python - AWS Lambda RDS MySQL 数据库连接接口(interface)错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43355278/

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