Python函数重试装饰器

def retry(**params):
    """
    重试装饰器
    :param params:
    :return:
    """
    def decorate(func):
        @wraps(func)
        def wrapper(*args, **kwargs):
            res = {
                "status": -1,
                "msg": ""
            }
            flag = False
            retry = params["retry"]
            while not flag and retry > 0:
                try:
                    result = func(*args, **kwargs)
                    flag = True
                except:
                    retry -= 1
                    print("重试")
            if retry > 0 and flag:
                res["status"] = 0
                res["msg"] = result
            return res

        return wrapper
    return decorate

使用示例:

# 导入retry
from sdk.utils.util_decorate import retry
import requests


# 支持自定义重试次数
@retry(retry=10)
def get_data(url):
    response = requests.get(url=url)
    return response


if __name__ == '__main__':
    url = "https://www.icbs.cn/en/web/index/"
    print(get_data(url)["msg"].text)

你可能感兴趣的:(python,开发语言)