[英]How to retry urllib2.urlopen n times
I am trying to implement a decorator to retry a urllib2.urlopen n times. 我正在尝试实现一个装饰器以重试urllib2.urlopen n次。 I cannot get the decorator to work. 我不能让装饰工工作。 When I run it I get the followin error: Traceback (most recent call last): File "F:\\retry\\dec_class.py", line 60, in x.getURLdata('127.0.0.1') TypeError: 'NoneType' object is not callable 当我运行它时,我收到以下错误:Traceback(最近一次调用):文件“ F:\\ retry \\ dec_class.py”,第60行,位于x.getURLdata('127.0.0.1')TypeError:'NoneType'对象不可通话
Can anyone give me hand please? 有人可以帮我吗?
import serial, urllib2, time
from functools import wraps
import xml.etree.cElementTree as ET
from xml.etree.cElementTree import parse
class Retry(object):
default_exceptions = (Exception)
def __init__(self, tries, exceptions=None, delay=0):
self.tries = tries
if exceptions is None:
exceptions = Retry.default_exceptions
self.exceptions = exceptions
self.delay = delay
def __call__(self, f):
def fn(*args, **kwargs):
tried = 0
exception = None
while tried <= self.tries:
try:
return f(*args, **kwargs)
except self.exceptions, e:
print "Retry, exception: "+str(e)
time.sleep(self.delay)
tried += 1
exception = e
#if no success after tries, raise last exception
raise exception
return fn
class getURL(object):
@Retry(2 )
def getURLdata(self, IPaddress):
try:
f = urllib2.urlopen(''.join(['http://', IPaddress]))
f = ET.parse(f)
return f
except IOError, err:
print("L112 IOError is %s" %err)
except urllib2.URLError, err:
print("L114 urllib2.URLError is %s" %err)
except urllib2.HTTPError, err:
print("L116 urllib2.HTTPError is %s" %err)
except Exception, err :
print("L118 Exception is %s" %err)
x = getURL()
x.getURLdata('127.0.0.1')
Your __call__
method doesn't return fn
. 您的__call__
方法不返回fn
。 Instead, it implicitly returns None
and so None is bound to getURLdata
. 相反,它隐式返回None
,因此None绑定到getURLdata
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.