python retrying 重试装饰器

python retrying chache

def login_required(view_func):
    """检验用户的登录状态"""

    @wraps(view_func)  # 不改变原有函数的签名文档
    def wrapper(*args, **kwargs):
        user_id = session.get("user_id")
        if user_id is not None:
            # 表示用户已经登录
            # 使用g对象保存user_id,在视图函数中可以直接使用
            g.user_id = user_id
            return view_func(*args, **kwargs)
        else:
            # 用户未登录
            resp = {
                "errno": RET.SESSIONERR,
                "errmsg": "用户未登录"
            }
            return jsonify(resp)

    return wrapper
    
    
# 构建装饰器
def wraps(func):
    @functools.wraps(func)
    def decorator( *args, **kwargs):
        print("开始验证")
        print("%s called" % func.__name__)
        result = func(*args, **kwargs)
        print("验证完毕")
        print("%s end" % func.__name__)
        return result
    return decorator


@wraps
def connnet_db():
    print("searching")
    
    
    
def singleton(fun):
    instances = {}
    def decorator(*args,**kwargs):
        if fun not in instances:
            print(111,fun)
            instances[fun] = fun(*args,**kwargs)
            return instances[fun]
        else:
            print("已存在")
        
    return decorator
    
def singleton(fun):
    cache = {}
    def decorator(*args,**kwargs):
        if fun not in cache:
            print(111,fun)
            cache[fun] = fun(*args,**kwargs)
            return cache[fun]
        else:
            print("已存在")
        
    return decorator

@singleton
def fib(i):
    if i < 2:
        return 1
    return fib(i-1) + fib(i-2)


if __name__ == '__main__':
    for i in range(10):
        test()


import requests
from tenacity import *




## 爬虫专用
def scraping(url):
    
    r = requests.get(url,timeout=3)

## 尝试5次,每次间隔1-2秒
@retry(stop=stop_after_attempt(5),wait=wait_random(min=1, max=2))
def feaching():
    raise scraping()

## 尝试5次,每次间隔5秒
@retry(stop=stop_after_attempt(5),wait=wait.wait_fixed(5))
def feaching1():
    raise scraping()

if __name__ == '__main__':
   feaching()