2014-12-24 62 views
12

我有一个很大的问题: 我的python软件运行的服务器的路由器似乎存在一些硬件问题。与数据库的连接大约每三次都是成功的。因此,在得到超时异常之前,psycopg2.connect()最多可能需要5分钟。Python psycopg2超时

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) 

我尝试了一些超时添加的查询,但没有帮助,因为连接没有得到建立。

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

回答

18

当使用connect函数的关键字参数语法时,可以使用任何libpd支持的连接参数。在这些有以秒connect_timeout

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

http://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS

http://initd.org/psycopg/docs/module.html

的连接超时引发OperationalError例外。

+0

要先评论一下,虽然这可能值得一提的新问题:在我的情况下,我得到超时以及此提示:“服务器是否在主机上运行”xxxxxx.xxxxxx.us-west-1.rds。 amazonaws.com“(xx.x.xxx.xxx)并接受端口5432上的TCP/IP连接?'。那些答案确实是对的。事实上,我可以在同一个工具的节点变体中建立连接,但仍然无法通过我编写的'psycopg2'版本进行连接。 – kuanb