feat(oa): 搭建OA审批流程框架,实现请假/加班通用审批引擎
本次提交完成了OA人事审批系统的基础架构搭建: 1. 新增项目依赖包DrissionPage、python-dotenv 2. 初始化项目目录结构,创建通用工具包、日志模块、重试工具 3. 搭建HRBP OA系统模块,拆分公共配置、登录、会话管理、SSO解析、API接口 4. 实现请假、加班审批的通用流程引擎,抽离公共逻辑 5. 完善两个业务审批模块的校验入参文档,优化代码结构 6. 新增cookies持久化功能,支持复用登录态避免重复登录 7. 替换原有print日志为统一彩色日志系统
This commit is contained in:
@@ -0,0 +1,6 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: utils
|
||||
@Description: 项目级通用工具包
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -4,55 +4,76 @@
|
||||
@FileName: utils.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 21:30
|
||||
@Description: 项目级通用工具(重试装饰器等)
|
||||
@Version: 1.0.0
|
||||
@Description: 项目级通用工具(重试装饰器)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
import functools
|
||||
import logging
|
||||
import os
|
||||
import random
|
||||
import sys
|
||||
import time
|
||||
from typing import Callable, Tuple, Type
|
||||
from typing import Callable
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
|
||||
from logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def retry(
|
||||
max_attempts: int = 3,
|
||||
delay: float = 1.0,
|
||||
exceptions: Tuple[Type[BaseException], ...] = (Exception,),
|
||||
) -> Callable:
|
||||
class RetryExhaustedError(Exception):
|
||||
"""重试耗尽后抛出的异常,保留原始异常链。"""
|
||||
pass
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3) -> Callable:
|
||||
"""
|
||||
重试装饰器:函数执行抛出异常时自动重试。
|
||||
重试装饰器:内置指数退避 + 随机抖动,只暴露重试次数。
|
||||
|
||||
Args:
|
||||
max_attempts: 最大尝试次数(含首次执行),默认 3
|
||||
delay: 每次重试前的等待秒数
|
||||
exceptions: 触发重试的异常类型元组,默认所有 Exception
|
||||
max_attempts: 最大尝试次数(含首次执行),默认 3,必须 >= 1。
|
||||
|
||||
规则:
|
||||
- 检测到错误自动重试,最多执行 max_attempts 次;
|
||||
- 连续 max_attempts 次都失败,才通过 logging.error 记录错误,并抛出最后一次异常。
|
||||
内部行为(对调用方透明):
|
||||
- 捕获所有 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 exceptions as e:
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt < max_attempts:
|
||||
logger.warning(
|
||||
"%s 第 %d 次执行失败: %s,%.1f 秒后重试",
|
||||
func.__name__, attempt, e, delay,
|
||||
)
|
||||
time.sleep(delay)
|
||||
else:
|
||||
if attempt >= max_attempts:
|
||||
logger.error(
|
||||
"%s 连续执行 %d 次仍失败,放弃并记录: %s",
|
||||
"%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||||
func.__name__, max_attempts, e,
|
||||
)
|
||||
raise last_exc
|
||||
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
|
||||
return decorator
|
||||
@@ -0,0 +1,89 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: utils.logger
|
||||
@FileName: logger.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05
|
||||
@Description: 项目统一日志配置:控制台彩色输出 + 文件持久化
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import logging
|
||||
import logging.handlers
|
||||
import os
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
_console_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(message)s"
|
||||
_file_fmt = "%(asctime)s | %(levelname)-7s | %(name)s | %(filename)s:%(lineno)d | %(message)s"
|
||||
_date_fmt = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
_initialized = False
|
||||
|
||||
|
||||
class _ColoredFormatter(logging.Formatter):
|
||||
"""控制台彩色日志格式,不修改 record 本身,避免污染文件输出"""
|
||||
|
||||
_colors = {
|
||||
logging.DEBUG: "\033[36m",
|
||||
logging.INFO: "\033[32m",
|
||||
logging.WARNING: "\033[33m",
|
||||
logging.ERROR: "\033[31m",
|
||||
logging.CRITICAL: "\033[35m",
|
||||
}
|
||||
_reset = "\033[0m"
|
||||
|
||||
def format(self, record: logging.LogRecord) -> str:
|
||||
color = self._colors.get(record.levelno, "")
|
||||
orig_levelname = record.levelname
|
||||
record.levelname = f"{color}{record.levelname}{self._reset}"
|
||||
result = super().format(record)
|
||||
record.levelname = orig_levelname
|
||||
return result
|
||||
|
||||
|
||||
def setup_logging(
|
||||
level: int = logging.INFO,
|
||||
log_dir: str = None,
|
||||
log_file: bool = True,
|
||||
) -> None:
|
||||
"""
|
||||
初始化项目统一日志配置。只需在入口调用一次。
|
||||
|
||||
Args:
|
||||
level: 日志级别,默认 INFO
|
||||
log_dir: 日志文件目录,默认 app/logs/
|
||||
log_file: 是否同时输出到文件,默认 True
|
||||
"""
|
||||
global _initialized
|
||||
if _initialized:
|
||||
return
|
||||
|
||||
logger = logging.getLogger()
|
||||
logger.setLevel(level)
|
||||
logger.handlers.clear()
|
||||
|
||||
console_handler = logging.StreamHandler(sys.stdout)
|
||||
console_handler.setLevel(level)
|
||||
console_handler.setFormatter(_ColoredFormatter(_console_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(console_handler)
|
||||
|
||||
if log_file:
|
||||
if log_dir is None:
|
||||
log_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "logs")
|
||||
os.makedirs(log_dir, exist_ok=True)
|
||||
log_path = os.path.join(log_dir, f"app_{datetime.now().strftime('%Y%m%d')}.log")
|
||||
file_handler = logging.handlers.RotatingFileHandler(
|
||||
log_path, maxBytes=5 * 1024 * 1024, backupCount=5, encoding="utf-8"
|
||||
)
|
||||
file_handler.setLevel(logging.DEBUG)
|
||||
file_handler.setFormatter(logging.Formatter(_file_fmt, datefmt=_date_fmt))
|
||||
logger.addHandler(file_handler)
|
||||
|
||||
_initialized = True
|
||||
|
||||
|
||||
def get_logger(name: str) -> logging.Logger:
|
||||
"""获取模块级 logger,用法:logger = get_logger(__name__)"""
|
||||
return logging.getLogger(name)
|
||||
Reference in New Issue
Block a user