Python psycopg2超时

gul*_*den 22 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
Run Code Online (Sandbox Code Playgroud)

那是我正在使用的代码.

# 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)
Run Code Online (Sandbox Code Playgroud)

我为查询尝试了一些超时添加,但这没有帮助,因为连接根本没有建立.

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

Clo*_*eto 35

connect函数使用关键字arguments语法时,可以使用任何libpd支持的连接参数.其中有connect_timeout几秒钟:

db = psycopg2.connect (
    host=dhost, database=ddatabase,
    user=duser, password=dpassword,
    connect_timeout=3
)
Run Code Online (Sandbox Code Playgroud)

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

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

连接超时会引发OperationalError异常.