名称'conn'未定义:NameError

问题描述 投票:0回答:1

我想将我的aws iot mqtt消息存储到我的postgresql中。为此,我已将本地posrtgresql连接到amazon RDS实例。现在,我需要在amazon lambda calculus之间创建一个连接,然后将数据发送到postgresql数据库。但无论何时,我正在测试我的lambda演算,它给了我“name'conn'未定义:NameError”错误。这是我在aws lambda中的python代码。我还将psycopg2库包含在我的项目中。

import sys
import logging
import rds_config
import psycopg2
#rds settings
rds_host  = "myhost"
name = "username"
password = "username_password"
db_name = "dbname"

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

try:
    conn = psycopg2.connect(host=rds_host, user=name, password=password, 
           dbname=db_name, connect_timeout=5)
except:
     logger.error("ERROR: Unexpected error: Could not connect to postgreSQL 
          instance.")

logger.info("SUCCESS: Connection to RDS postgreSQL instance succeeded")
def handler(event, context):
"""
This function fetches content from postgreSQL RDS instance
"""
item_count = 0
with conn.cursor() as cur: 
    cur.execute('insert into awsiotdata (serialnumber, dateandtime, clicktype, batteryvoltage) values(serialNumber, datetime.datetime.utcnow(), clickType, batteryVoltage)')
    conn.commit()
    cur.execute("select * from awsiotdata")
    for row in cur:
        item_count += 1
        logger.info(row)
        #print(row)


return "Added %d items from RDS PostgreSQL table" %(item_count)
python-3.x postgresql amazon-web-services aws-lambda
1个回答
1
投票

您正在隐藏真实的错误消息。 Python的异常处理模式看起来像qazxsw poi:

this

这样您将看到真正的错误消息:

无效的dsn:无效的连接选项“passwd”

编辑#1:

“超时”表示由于RDS实例的“安全组规则”,lambda无法连接。请记住,即使公共RDS实例默认也有IP入站限制(即,它可以从PC连接,但从AWS Lambda连接是不可能的)。

try: conn = psycopg2.connect(host=rds_host, user=name, password=password, database=db_name) except Exception as e: print(e) RDS wizard

© www.soinside.com 2019 - 2024. All rights reserved.