feat: 新增轻量会话校验能力,优化登录态失效处理流程
1. 新增TODO_COUNT_URL轻量接口用于快速校验会话有效性 2. 定义OALoginExpiredError统一标识登录态失效异常 3. 重构会话校验逻辑,使用轻量接口替代拉取待办页校验 4. 为重试装饰器添加不重试异常配置,登录失效直接上抛 5. 全流程增加登录态失效自动重登机制,最多重试2次 6. 新增通用钉钉机器人推送工具类
This commit is contained in:
@@ -80,6 +80,8 @@ HOME_URL = f"{BASE_URL}/sys/portal/page.jsp?portalId=1754a0f1c8b63479fb544514619
|
||||
LIST_URL = f"{BASE_URL}/km/review/km_review_main_list.jsp"
|
||||
SEARCH_URL = f"{BASE_URL}/sys/search/search.do"
|
||||
MENU_API_PATH = "/sys/portal/sys_portal_nav/sysPortalNav.do"
|
||||
# 轻量会话校验接口:method=sumTodoCount 返回待办数统计 JSON,会话失效会被重定向到登录页
|
||||
TODO_COUNT_URL = f"{BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
|
||||
DEFAULT_FIXED_PARAMS = {
|
||||
"fdModelName": "com.landray.kmss.km.review.model.KmReviewMain",
|
||||
@@ -253,10 +255,15 @@ def create_browser_with_saved_cookies(path):
|
||||
|
||||
|
||||
def is_oa_session_valid(session):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效(无需启动浏览器)。"""
|
||||
try:
|
||||
session.get(HOME_URL)
|
||||
session.get(TODO_COUNT_URL, params={"method": "sumTodoCount"}, timeout=10)
|
||||
resp = session.response
|
||||
return resp is not None and resp.status_code == 200
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
# 会话有效时返回待办数统计 JSON(如 {"type_2":"39","type_1":"8"});失效会被重定向到登录页返回 HTML
|
||||
text = resp.text
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
logger.info("OA 会话已失效: %s", e)
|
||||
return False
|
||||
@@ -642,6 +649,9 @@ def get_fd_id_by_listening(session, browser=None):
|
||||
logger.info("正在访问 OA 首页:%s", HOME_URL)
|
||||
browser.get(HOME_URL)
|
||||
time.sleep(5)
|
||||
# 兜底:若浏览器 cookies 失效会停在登录页,快速失败避免空等,且异常含『登录』可触发主流程自动重登
|
||||
if "login.jsp" in browser.url or browser.ele('tag:input@name=j_username', timeout=2):
|
||||
raise RuntimeError("登录态已失效,页面停留在登录页,请重新登录")
|
||||
deadline = time.time() + 10
|
||||
target = None
|
||||
while time.time() < deadline:
|
||||
@@ -920,42 +930,56 @@ def _write_annotated(headers, rows, emp_col, mode, base_name, output_dir="."):
|
||||
def export_employee_change_list(menu_name, filter_idx, columns, output_dir, query_date=None):
|
||||
logger.info("社保增减名单核对流程开始,菜单:%s", menu_name)
|
||||
base_params = {**DEFAULT_FIXED_PARAMS, **_build_filter_params(filter_idx, query_date)}
|
||||
browser, session = get_oa_session()
|
||||
|
||||
try:
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total == 0:
|
||||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||||
return ""
|
||||
|
||||
logger.info("开始导出 %d 条记录...", total)
|
||||
content = export_all_data(session, base_params, total, columns, search_id, timestamp)
|
||||
output_path = os.path.abspath(os.path.join(
|
||||
output_dir, f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"))
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir)
|
||||
# 登录态失效时自动删除 cookie、重新登录并重跑一遍(最多 2 轮)
|
||||
for login_attempt in range(2):
|
||||
browser, session = get_oa_session()
|
||||
try:
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
return final_path
|
||||
finally:
|
||||
if browser is not None:
|
||||
fd_id = get_fd_id_by_listening(session, browser)
|
||||
search_id = get_search_id_from_menu(session, fd_id, menu_name)
|
||||
timestamp = str(int(time.time() * 1000))
|
||||
total = get_total_count(session, base_params, search_id, timestamp)
|
||||
if total == 0:
|
||||
logger.warning("查询结果为 0 条,请检查筛选条件或无数据")
|
||||
return ""
|
||||
|
||||
logger.info("开始导出 %d 条记录...", total)
|
||||
content = export_all_data(session, base_params, total, columns, search_id, timestamp)
|
||||
output_path = os.path.abspath(os.path.join(
|
||||
output_dir, f"{time.strftime('%Y%m')}_{menu_name}表_{time.strftime('%H%M%S')}.xls"))
|
||||
with open(output_path, "wb") as f:
|
||||
f.write(content)
|
||||
logger.info("导出完成,文件保存为:%s", output_path)
|
||||
|
||||
headers, rows, emp_col = _read_and_clean(output_path)
|
||||
mode = "suspension" if menu_name == MENU_NAME_SUSPEND else "participation"
|
||||
final_path = _write_annotated(
|
||||
headers, rows, emp_col, mode,
|
||||
os.path.splitext(os.path.basename(output_path))[0], output_dir)
|
||||
try:
|
||||
browser.quit()
|
||||
os.remove(output_path)
|
||||
logger.info("已清理中间原始导出文件:%s", output_path)
|
||||
except Exception:
|
||||
pass
|
||||
return final_path
|
||||
except Exception as e:
|
||||
logger.error("导出过程出错: %s", e)
|
||||
is_login_fail = "登录" in str(e) or "cookie" in str(e).lower()
|
||||
if is_login_fail and login_attempt == 0:
|
||||
try:
|
||||
if os.path.exists(COOKIE_FILE_OA):
|
||||
os.remove(COOKIE_FILE_OA)
|
||||
logger.info("检测到 OA 登录态失效,已删除 cookie,自动重新登录后重跑")
|
||||
except Exception:
|
||||
pass
|
||||
continue
|
||||
raise
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def export_participation(output_dir=".", query_date=None):
|
||||
|
||||
Reference in New Issue
Block a user