Python psycopg2 超时
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/27641740/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Python psycopg2 timeout
提问by gulden
I have a huge problem: There seems to be some hardware problems on the router of the server my python software runs on. The connection to the database only is successfull about every third time. So a psycopg2.connect() can take up to 5 minutes before I get an timeout exception.
我有一个大问题:运行我的 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
That's the code I'm using.
这就是我正在使用的代码。
# 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)
I tried some timeout additions for the query, but that didn't helped, since the connection didn't got established at all.
我为查询尝试了一些超时添加,但这没有帮助,因为根本没有建立连接。
Is there a way, I can stop the program immediately, when the connection couldn't be established?
有没有办法,当无法建立连接时,我可以立即停止程序?
回答by Clodoaldo Neto
When using the keyword arguments syntax to the connect
function it is possible to use any of the libpd
supported connection parameters. Among those there is connect_timeout
in seconds:
对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://www.postgresql.org/docs/current/static/libpq-connect.html#LIBPQ-PARAMKEYWORDS
http://initd.org/psycopg/docs/module.html
http://initd.org/psycopg/docs/module.html
A connection time out raises an OperationalError
exception.
连接超时引发OperationalError
异常。