One - One Code All

Blog Content

python程序超时重试机制

Python   2013-11-28 22:23:47

python程序的重试机制,在爬虫,http请求获取数据的时候比较常用。

import requests
 
def url_retry(url,num_retries=3):
    print("access!")
    try:
        request = requests.get(url,timeout=60)
        #raise_for_status(),如果不是200会抛出HTTPError错误
        request.raise_for_status()
        html = request.content
    except requests.HTTPError as e:
        html=None
        if num_retries>0:
            #如果不是200就重试,每次递减重试次数
            return url_retry(url,num_retries-1)
    #如果url不存在会抛出ConnectionError错误,这个情况不做重试
    except requests.exceptions.ConnectionError as e:
        return
    return html


装饰器实现:

import requests
 
#定义一个重试修饰器,默认重试一次
def retry(num_retries=1):
    #用来接收函数
    def wrapper(func):
        #用来接收函数的参数
        def wrapper(*args,**kwargs):
            #为了方便看抛出什么错误定义一个错误变量
            last_exception =None
            #循环执行包装的函数
            for _ in range(num_retries):
                try:
                    #如果没有错误就返回包装的函数,这样跳出循环
                    return func(*args, **kwargs)
                except Exception as e:
                    #捕捉到错误不要return,不然就不会循环了
                    last_exception = e
            #如果要看抛出错误就可以抛出
            # raise last_exception
        return wrapper
    return wrapper
 
if __name__=="__main__":
    @retry(5)
    def url_retry(url):
        request = requests.get(url, timeout=60)
        print("access!")
        request.raise_for_status()
        html = request.content
        print(html)
        return html
    url_retry(url)



上一篇:padas中DataFrame之模糊查询
下一篇:socket.error: [Errno 98] Address already in use解决方案

The minute you think of giving up, think of the reason why you held on so long.