feat: 新增登录态过期不重试逻辑,优化社保核对流程

1. 重构重试装饰器,新增no_retry_on参数支持指定异常不重试
2. 为社保核对模块添加登录态过期检测与自动刷新逻辑
3. 统一两处社保业务代码的异常处理与会话重建流程
4. 更新版本号与默认输出目录配置
This commit is contained in:
2026-08-08 19:25:42 +08:00
parent 83d8204847
commit eef5df9ce2
4 changed files with 135 additions and 32 deletions
@@ -5,7 +5,7 @@
@Author: 小布丁
@CreateTime: 2026-08-07 14:55
@Description: 社保增减名单模块:复用 OA 登录态,监听首页请求动态获取参数并导出员工异动名单(精简版)
@Version: 2.3.0
@Version: 2.4.0
"""
import os
@@ -502,13 +502,32 @@ def _build_hr_session():
return session
@retry(max_attempts=3)
class HRSessionExpiredError(Exception):
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
def _si_is_expired(text) -> bool:
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
return bool(text) and not text.lstrip().startswith(("{", "["))
def _si_refresh_hr_session():
"""HR 登录态过期后重新执行 HR 登录刷新 cookies,并重建会话。"""
from app.service.hrbp.ehr.common.login import login as hr_login
if not hr_login():
raise RuntimeError("HR 登录态过期后重新登录失败")
return _build_hr_session()
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
def _si_query_batch(session, codes_batch):
"""查询一批工号(≤15个),返回响应 JSON。"""
params = SI_BASE_PARAMS.copy()
params["base_codes"] = ",".join(codes_batch)
resp = session.post(SI_QUERY_URL, data=params, timeout=15)
resp.raise_for_status()
if _si_is_expired(resp.text):
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
return resp.json()
@@ -522,11 +541,23 @@ def _si_check_batch(session, codes_batch) -> set:
"""返回这一批中『能查到参保记录』的工号集合;请求失败返回空集合并告警。"""
try:
return _si_found_codes(_si_query_batch(session, codes_batch))
except HRSessionExpiredError:
raise
except Exception as e:
logger.warning("参保记录批量查询失败 %s:%s", codes_batch, e)
return set()
def _si_preflight(session):
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
try:
_si_query_batch(session, ["0"])
except HRSessionExpiredError:
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
return _si_refresh_hr_session()
return session
def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".") -> str:
"""逐批查 HR 参保记录,追加『社保记录查询结果』列,写出最终 .xlsx。"""
if _XlsxWorkbook is None:
@@ -540,10 +571,17 @@ def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir=".") ->
seen.add(code)
unique_codes.append(code)
session = _build_hr_session()
session = _si_preflight(_build_hr_session())
found = set()
for i in range(0, len(unique_codes), SI_BATCH_SIZE):
found |= _si_check_batch(session, unique_codes[i:i + SI_BATCH_SIZE])
batch = unique_codes[i:i + SI_BATCH_SIZE]
try:
found |= _si_check_batch(session, batch)
except HRSessionExpiredError:
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
session = _si_refresh_hr_session()
found |= _si_check_batch(session, batch)
logger.info("参保记录核对 %d/%d 个工号", min(i + SI_BATCH_SIZE, len(unique_codes)), len(unique_codes))
time.sleep(0.3)
@@ -6,7 +6,7 @@
@CreateTime: 2026-08-07 15:20
@Description: 社保参保状态核对:读取清洗后的社保增减名单(参保/停保),按工号逐批调用 HR 参保记录接口,
判断每个工号是否有参保记录,追加一列标注结果并导出 .xlsx。
@Version: 2.0.0
@Version: 2.1.0
业务判定(对应 aa.md):
- 参保申请表:某工号在 HR 参保记录中「有返回数据」→ 已参保,属异常;
@@ -87,6 +87,23 @@ RESULT_COL = "社保记录查询结果"
BATCH_SIZE = 15
class HRSessionExpiredError(Exception):
"""HR 登录态过期:接口返回登录页等非 JSON 内容。"""
def _is_expired(text) -> bool:
"""接口正常情况下返回 JSON;返回登录页/错误页等非 JSON 即视为登录态过期。"""
return bool(text) and not text.lstrip().startswith(("{", "["))
def _refresh_hr_session() -> "requests.Session":
"""HR 登录态过期后重新执行 HR 登录刷新 cookies,并重建会话。"""
from app.service.hrbp.ehr.common.login import login as hr_login
if not hr_login():
raise RuntimeError("HR 登录态过期后重新登录失败")
return build_hr_session()
# ----------------------------------------------
# 1. HR 会话(复用登录缓存 cookies)
# ----------------------------------------------
@@ -115,13 +132,15 @@ def build_hr_session() -> "requests.Session":
# ----------------------------------------------
# 2. 查询参保记录接口
# ----------------------------------------------
@retry(max_attempts=3)
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
def query_batch(session, codes_batch: List[str]):
"""查询一批工号(≤15个),返回响应 JSON。"""
params = SI_BASE_PARAMS.copy()
params["base_codes"] = ",".join(codes_batch)
resp = session.post(SI_QUERY_URL, data=params, timeout=15)
resp.raise_for_status()
if _is_expired(resp.text):
raise HRSessionExpiredError("HR 登录态已过期,接口返回非 JSON 内容")
return resp.json()
@@ -135,11 +154,23 @@ def check_codes(session, codes_batch: List[str]) -> set:
"""返回这一批中『能查到参保记录』的工号集合;请求失败时返回空集合并告警。"""
try:
return extract_found_codes(query_batch(session, codes_batch))
except HRSessionExpiredError:
raise
except Exception as e:
logger.warning("批量查询失败 %s:%s", codes_batch, e)
return set()
def preflight(session) -> "requests.Session":
"""正式核对前先探测一次接口,确认 HR 登录态有效;过期则重新登录并重建会话。"""
try:
query_batch(session, ["0"])
except HRSessionExpiredError:
logger.warning("预检发现 HR 登录态已过期,正在重新登录")
return _refresh_hr_session()
return session
# ----------------------------------------------
# 3. 读取表格(支持 .xlsx / .xls)
# ----------------------------------------------
@@ -189,10 +220,17 @@ def check_and_annotate(table_path: str, mode: str, output_dir: str = ".") -> str
seen.add(code)
unique_codes.append(code)
session = build_hr_session()
session = preflight(build_hr_session())
found = set()
for i in range(0, len(unique_codes), BATCH_SIZE):
found |= check_codes(session, unique_codes[i:i + BATCH_SIZE])
batch = unique_codes[i:i + BATCH_SIZE]
try:
found |= check_codes(session, batch)
except HRSessionExpiredError:
logger.warning("HR 登录态过期,正在重新登录并续跑(第 %d/%d 批)",
min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
session = _refresh_hr_session()
found |= check_codes(session, batch)
logger.info("已查询 %d/%d 个工号", min(i + BATCH_SIZE, len(unique_codes)), len(unique_codes))
time.sleep(0.3) # 轻微限速,避免触发风控
+4 -1
View File
@@ -23,12 +23,13 @@ class RetryExhaustedError(Exception):
pass
def retry(max_attempts: int = 3) -> Callable:
def retry(max_attempts: int = 3, no_retry_on: tuple = ()) -> Callable:
"""
重试装饰器:内置指数退避 + 随机抖动,只暴露重试次数。
Args:
max_attempts: 最大尝试次数(含首次执行),默认 3,必须 >= 1。
no_retry_on: 遇到这些异常类型时直接抛出、不做重试(用于无需重试的确定性失败)。
内部行为(对调用方透明):
- 捕获所有 Exception;
@@ -48,6 +49,8 @@ def retry(max_attempts: int = 3) -> Callable:
for attempt in range(1, max_attempts + 1):
try:
return func(*args, **kwargs)
except no_retry_on:
raise
except Exception as e:
last_exc = e
if attempt >= max_attempts: