"""
@author: luojunhui
"""
import time
import requests


def retryOnNone():
    """
    基于None类型数据的重试装饰器
    :return:
    """

    def decorator(func):
        """
        :param func:
        :return:
        """
        max_retries = 10
        wait_seconds = 2

        def wrapper(*args, **kwargs):
            """

            :param args:
            :param kwargs:
            :return:
            """
            for attempt in range(max_retries):
                response = func(*args, **kwargs)
                if response['data'] is not None:
                    return response
                time.sleep(wait_seconds)
            return None

        return wrapper

    return decorator


def retryOnTimeout(retries=3, delay=2):
    """
    超时重试code
    :param retries:
    :param delay:
    :return:
    """
    def decorator(func):
        """
        :param func:
        :return:
        """
        def wrapper(*args, **kwargs):
            """
            :param args:
            :param kwargs:
            :return:
            """
            for attempt in range(retries):
                try:
                    return func(*args, **kwargs)
                except requests.exceptions.Timeout:
                    if attempt < retries - 1:
                        time.sleep(delay)
                        print(f"Timeout occurred, retrying... ({attempt + 1}/{retries})")
                    else:
                        print("Maximum retries reached. Function failed.")
                        raise

        return wrapper

    return decorator