Python psycopg2 超时问题

44
我有一个大问题: 我的 Python 软件运行的服务器路由器似乎出现了一些硬件问题。与数据库的连接只有大约每三次成功一次。因此,psycopg2.connect() 可能需要长达 5 分钟才能获得超时异常。
2014-12-23 15:03:12,461 - ERROR - could not connect to server: Connection timed out
    Is the server running on host "172.20.19.1" and accepting

这是我正在使用的代码。

# Connection to the DB
try:
    db = psycopg2.connect(host=dhost, database=ddatabase,
                          user=duser, password=dpassword)
    cursor = db.cursor(cursor_factory=psycopg2.extras.DictCursor)

except psycopg2.DatabaseError, err:
    print(str(err))
    logging.error(str(err))
    logging.info('program terminated')
    sys.exit(1)

我尝试了一些针对查询的超时设置,但这并没有帮助,因为连接根本没有建立。

有没有办法,在连接无法建立时立即停止程序?


可能被某种应用防火墙拦截了? - Jasen
1个回答

79

1
首先进行注释,尽管这可能值得新的问题:在我的情况下,我遇到了超时问题,以及这个提示:服务器是否在主机“xxxxxx.xxxxxx.us-west-1.rds.amazonaws.com”(xx.x.xxx.xxx)上运行,并且在端口5432上接受TCP/IP连接? 对于这些问题,答案确实是肯定的。事实上,我可以在同一工具的节点变体中建立连接,但仍然无法通过我编写的 psycopg2 版本连接。 - kuanb
如果你可以执行 psql "some connection string",那么 psycopg2.connect(dsn="some connection string") 也应该能够正常工作。 - Jasen
PGOPTIONS 中的超时选项和 libpq 连接参数中的超时选项有什么区别? - CMCDragonkai

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接