# -*- coding: utf-8 -*- """ @Module: hrbp.utils @FileName: utils.py @Author: 小布丁 @CreateTime: 2026-08-05 21:30 @Description: 项目级通用工具(重试装饰器等) @Version: 1.0.0 """ import functools import logging import time from typing import Callable, Tuple, Type logger = logging.getLogger(__name__) def retry( max_attempts: int = 3, delay: float = 1.0, exceptions: Tuple[Type[BaseException], ...] = (Exception,), ) -> Callable: """ 重试装饰器:函数执行抛出异常时自动重试。 Args: max_attempts: 最大尝试次数(含首次执行),默认 3 delay: 每次重试前的等待秒数 exceptions: 触发重试的异常类型元组,默认所有 Exception 规则: - 检测到错误自动重试,最多执行 max_attempts 次; - 连续 max_attempts 次都失败,才通过 logging.error 记录错误,并抛出最后一次异常。 """ def decorator(func: Callable) -> Callable: @functools.wraps(func) def wrapper(*args, **kwargs): last_exc = None for attempt in range(1, max_attempts + 1): try: return func(*args, **kwargs) except exceptions as e: last_exc = e if attempt < max_attempts: logger.warning( "%s 第 %d 次执行失败: %s,%.1f 秒后重试", func.__name__, attempt, e, delay, ) time.sleep(delay) else: logger.error( "%s 连续执行 %d 次仍失败,放弃并记录: %s", func.__name__, max_attempts, e, ) raise last_exc return wrapper return decorator