2012-09-01 55 views
2

如何控制opener.open的重試次數?urllib打開 - 如何控制重試次數

在下面的代碼中,它會在引發異常或代碼成功之前發送大約6個GET HTTP請求(我在Wireshark嗅探器中看到它)。

password_mgr = urllib.request.HTTPPasswordMgrWithDefaultRealm() 
password_mgr.add_password(None,url, username, password) 
handler = urllib.request.HTTPBasicAuthHandler(password_mgr) 
opener = urllib.request.build_opener(handler) 

try: 
    resp = opener.open(url,None,1) 

except urllib.error.URLError as e: 
    print ("no success") 
else: 
    print ("success!") 

回答

0

urllib使用httplib來處理HTTP連接。如果您查看httplib.py源文件並分析HTTPConnection課程,您將看到connect方法的工作原理。

def connect(self): 
    """Connect to the host and port specified in __init__.""" 
    msg = "getaddrinfo returns an empty list" 
    for res in socket.getaddrinfo(self.host, self.port, 0, socket.SOCK_STREAM): 
     af, socktype, proto, canonname, sa = res 
     try: 
      self.sock = socket.socket(af, socktype, proto) 
      if self.debuglevel > 0: 
       print "connect: (%s, %s)" % (self.host, self.port) 
      self.sock.connect(sa) 
     except socket.error, msg: 
      if self.debuglevel > 0: 
       print 'connect fail:', (self.host, self.port) 
      if self.sock: 
       self.sock.close() 
      self.sock = None 
      continue 
     break 

    if not self.sock: 
     raise socket.error, msg 

其實,嘗試次數依賴於socket.getaddrinfo返回列表的長度。代碼遍歷所有可用套接字選項以設置連接。

我懷疑減少嘗試次數是否有意義。但是你可以像下面這樣增加這個數字:

maxtries = 3 
delay = 3 
n = 0 
while n < maxtries: 
    try: 
     resp = opener.open(url,None,1) 
    except e: 
     print ("no success") 
     n += 1 
     sleep(delay) 
    else: 
     print ("success!") 
     break