简体   繁体   English

未定义名称“ conn”:NameError

[英]name 'conn' is not defined: NameError

I want to store my aws iot mqtt messages into my postgresql. 我想将aws物联网mqtt消息存储到我的postgresql中。 To do so, I have already connected my local posrtgresql to the amazon RDS instance. 为此,我已经将本地posrtgresql连接到了Amazon RDS实例。 Now, I need to create a connection between amazon lambda calculus and then send the data to the postgresql database. 现在,我需要在Amazon Lambda演算之间创建连接,然后将数据发送到postgresql数据库。 But whenever, I am testing my lambda calculus, it was giving me "name 'conn' is not defined: NameError" error. 但是每当我测试我的lambda演算时,它都会给我“未定义名称'conn':NameError”的错误。 Here, is my python code in aws lambda. 这是aws lambda中的python代码。 I have also included the psycopg2 library to my project. 我还将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)

You are hiding a true error message. 您正在隐藏真实的错误消息。 Exception handling patter for Python looks like this : Python的异常处理模式如下所示

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

This way you will see the real error message: 这样,您将看到真正的错误消息:

invalid dsn: invalid connection option "passwd" 无效的dsn:无效的连接选项“ passwd”

Edit #1: 编辑#1:

"Timeout" means that lambda can't connect because of "Security group rules" for RDS instance. “超时”表示lambda无法连接,因为RDS实例的“安全组规则”。 Please keep in mind that even public RDS instance by default have inbound restriction by IP (ie it is posible to connect from PC but it is imposible to connect from AWS Lambda). 请记住,默认情况下,即使是公共RDS实例也具有IP的入站限制(即,可以从PC连接,但不能从AWS Lambda连接)。

RDS向导 RDS实例选项

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM