Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/362.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python DBAPI连接超时?_Python_Python Db Api - Fatal编程技术网

Python DBAPI连接超时?

Python DBAPI连接超时?,python,python-db-api,Python,Python Db Api,我试图测试连接是否失败,不幸的是,如果主机的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.co

我试图测试连接是否失败,不幸的是,如果主机的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地址时,如何等待或测试超时,而不是让我的应用程序挂起?

您正在经历的是防火墙的痛苦,超时是正常的TCP超时。

您通常可以在connect函数中传递超时参数。如果它不存在,您可以尝试使用socket.timeout或:


这会将此设置应用于您建立的所有基于套接字的连接,并在等待10秒后失败。

s/防火墙/愚蠢、偏执的防火墙/这实际上是删除规则的结果。正确的方法是使用tcp重置ICMP数据包IIRC进行回复。拼写/语法-纳粹时间:Pythobn->Python,fire-walled->firewalled。哦,最后一行似乎没有被四个空格缩进。
import socket
socket.setdefaulttimeout(10) # sets timeout to 10 seconds