[英]Python psycopg2 timeout
我有一个很大的问题:我的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
函数中使用关键字arguments语法时,可以使用任何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
异常。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.