本次提交完成了OA人事审批系统的基础架构搭建: 1. 新增项目依赖包DrissionPage、python-dotenv 2. 初始化项目目录结构,创建通用工具包、日志模块、重试工具 3. 搭建HRBP OA系统模块,拆分公共配置、登录、会话管理、SSO解析、API接口 4. 实现请假、加班审批的通用流程引擎,抽离公共逻辑 5. 完善两个业务审批模块的校验入参文档,优化代码结构 6. 新增cookies持久化功能,支持复用登录态避免重复登录 7. 替换原有print日志为统一彩色日志系统
79 lines
2.3 KiB
Python
79 lines
2.3 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""
|
||
@Module: hrbp.utils
|
||
@FileName: utils.py
|
||
@Author: 小布丁
|
||
@CreateTime: 2026-08-05 21:30
|
||
@Description: 项目级通用工具(重试装饰器)
|
||
@Version: 1.1.0
|
||
"""
|
||
|
||
import functools
|
||
import os
|
||
import random
|
||
import sys
|
||
import time
|
||
from typing import Callable
|
||
|
||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||
|
||
from logger import get_logger
|
||
|
||
logger = get_logger(__name__)
|
||
|
||
|
||
class RetryExhaustedError(Exception):
|
||
"""重试耗尽后抛出的异常,保留原始异常链。"""
|
||
pass
|
||
|
||
|
||
def retry(max_attempts: int = 3) -> Callable:
|
||
"""
|
||
重试装饰器:内置指数退避 + 随机抖动,只暴露重试次数。
|
||
|
||
Args:
|
||
max_attempts: 最大尝试次数(含首次执行),默认 3,必须 >= 1。
|
||
|
||
内部行为(对调用方透明):
|
||
- 捕获所有 Exception;
|
||
- 延迟策略:第 n 次重试等待 1.0 * 2^(n-1) 秒,并乘以 [0.5, 1.5] 随机因子;
|
||
- 全部失败后抛出 RetryExhaustedError,可通过 __cause__ 获取原始异常。
|
||
"""
|
||
if max_attempts < 1:
|
||
raise ValueError("max_attempts must be >= 1")
|
||
|
||
def decorator(func: Callable) -> Callable:
|
||
@functools.wraps(func)
|
||
def wrapper(*args, **kwargs):
|
||
last_exc = None
|
||
base_delay = 1.0
|
||
backoff = 2.0
|
||
|
||
for attempt in range(1, max_attempts + 1):
|
||
try:
|
||
return func(*args, **kwargs)
|
||
except Exception as e:
|
||
last_exc = e
|
||
if attempt >= max_attempts:
|
||
logger.error(
|
||
"%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||
func.__name__, max_attempts, e,
|
||
)
|
||
break
|
||
|
||
# 计算退避 + 抖动
|
||
delay = base_delay * (backoff ** (attempt - 1))
|
||
delay *= random.uniform(0.5, 1.5)
|
||
|
||
logger.warning(
|
||
"%s 第 %d 次执行失败: %s,%.2f 秒后重试",
|
||
func.__name__, attempt, e, delay,
|
||
)
|
||
time.sleep(delay)
|
||
|
||
raise RetryExhaustedError(
|
||
f"{func.__name__} failed after {max_attempts} attempts"
|
||
) from last_exc
|
||
|
||
return wrapper
|
||
return decorator |