Python psycopg2超时

Python psycopg2超时,python,postgresql,connection,timeout,psycopg2,Python,Postgresql,Connection,Timeout,Psycopg2,我有一个大问题: 运行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 这就是我正在使用

我有一个大问题: 运行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)
我尝试为查询添加一些超时,但没有帮助,因为根本没有建立连接


有没有办法,当无法建立连接时,我可以立即停止程序?

connect
函数中使用关键字参数语法时,可以使用
libpd
支持的任何连接参数。其中有
connect\u timeout
秒:

db = psycopg2.connect (
    host=dhost, database=ddatabase,
    user=duser, password=dpassword,
    connect_timeout=3
)


连接超时会引发异常。

首先进行评论,尽管这可能需要新的问题:在我的情况下,我会得到超时,并得到提示:
服务器是否在主机“xxxxxx.xxxxxx.us-west-1.rds.amazonaws.com”(xx.x.xxx.xxx)上运行,并在端口5432上接受TCP/IP连接?
。答案确实是肯定的。事实上,我可以在同一工具的节点变体中建立连接,但仍然无法通过我编写的
psycopg2
版本进行连接。如果可以执行
psql“some connection string”
psycopg2.connect(dsn=“some connection string”)
也应该可以工作。
PGOPTIONS
中的超时选项与作为libpq connect参数一部分的超时选项有什么区别?可能被某种应用程序防火墙阻止了?
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