如何重试urllib2.urlopen n次

时间:2014-05-08 18:07:38

标签: python python-2.5

我正在尝试实现一个装饰器来重试一次urllib2.urlopen n次。 我无法让装饰工作。当我运行它时,我得到以下错误:         Traceback(最近一次调用最后一次):         文件" F:\ retry \ dec_class.py",第60行,in         x.getURLdata(' 127.0.0.1')         TypeError:' NoneType'对象不可调用

有人能帮我一把吗?

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')

1 个答案:

答案 0 :(得分:1)

您的__call__方法未返回fn。相反,它隐式返回None,因此None绑定到getURLdata