Python DBAPI 连接超时?
我试图测试连接失败,不幸的是,如果主机的 IP 地址被防火墙屏蔽,则连接不会失败。
这是代码:
def get_connection(self, conn_data):
rtu, hst, prt, usr, pwd, db = conn_data
try:
self.conn = pgdb.connect(host=hst+":"+prt, user=usr, password=pwd, database=db)
self.cur = self.conn.cursor()
return True
except pgdb.Error as e:
logger.exception("Error trying to connect to the server.")
return False
if self.get_connection(conn_data):
# Do stuff here:
如果我尝试连接到已知服务器但提供了不正确的用户名,它将触发异常并失败。
但是,如果我尝试连接到没有响应(防火墙)的计算机,它永远不会通过 self.conn = pgdb.connect()
如何等待或测试超时而不是让我的应用程序当用户输错 IP 地址时似乎挂起?
I was attempting to test for connection failure, and unfortunately it's not failing if the IP address of the host is fire walled.
This is the code:
def get_connection(self, conn_data):
rtu, hst, prt, usr, pwd, db = conn_data
try:
self.conn = pgdb.connect(host=hst+":"+prt, user=usr, password=pwd, database=db)
self.cur = self.conn.cursor()
return True
except pgdb.Error as e:
logger.exception("Error trying to connect to the server.")
return False
if self.get_connection(conn_data):
# Do stuff here:
If I try to connect to a known server but give an incorrect user name, it will trigger the exception and fail.
However if I try to connect to a machine that does not respond (firewalled) it never gets passed self.conn = pgdb.connect()
How to I wait or test for time out rather than have my app appear to hang when a user mistypes an IP address?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
你所经历的是防火墙的痛苦,超时是正常的TCP超时。
What you are experiencing is the pain of firewalls, and the timeout is the normal TCP timeout.
您通常可以在 connect 函数中传递超时参数。如果它不存在,您可以尝试使用 socket.timeout 或 默认超时:
这将将此设置应用于您建立的所有连接(基于套接字),并在等待 10 秒后失败。
You can usually pass timeout argument in connect function. If it doesn't exist you could try with socket.timeout or default timeout:
This will apply this setting to all connections(socket based) you make and will fail after 10 seconds of waiting.