Files
37duAutomation/app/service/hrbp/oa/common/oa_api/base.py
T
puddy 4d999bd17e feat: 新增轻量会话校验能力,优化登录态失效处理流程
1. 新增TODO_COUNT_URL轻量接口用于快速校验会话有效性
2. 定义OALoginExpiredError统一标识登录态失效异常
3. 重构会话校验逻辑,使用轻量接口替代拉取待办页校验
4. 为重试装饰器添加不重试异常配置,登录失效直接上抛
5. 全流程增加登录态失效自动重登机制,最多重试2次
6. 新增通用钉钉机器人推送工具类
2026-08-15 12:45:41 +08:00

70 lines
2.3 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""
@Module: hrbp.oa.common.oa_api
@FileName: base.py
@Description: OA API 通用请求封装(发送 + 校验):只封装「发送 + 状态码 + JSON 解析」,
业务级成功判定(state / success / code)保留在各接口自身。
对应 docs/通用接口请求封装规划.md。
@Version: 1.0.0
"""
from app.utils.logger import get_logger
try:
from DrissionPage import SessionPage
except ImportError:
SessionPage = None
logger = get_logger(__name__)
class OALoginExpiredError(Exception):
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
def _handle_response(resp, label):
"""统一校验响应:存在性 / 状态码 / JSON 可解析性,返回解析后的 JSON。"""
if not resp:
raise RuntimeError(f"{label}请求失败,未获取到响应")
if resp.status_code != 200:
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
text = resp.text or ""
try:
return resp.json()
except Exception:
# OA 会话失效时接口会被重定向到登录页返回 HTML,据此判定登录失效
if "login.jsp" in text or "j_username" in text:
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {text[:200]}")
def oa_request_json(
session: SessionPage,
method: str,
url: str,
params: dict,
label: str,
timeout: int = 20,
):
"""通用「发送请求 + 校验响应」:发出请求 → 校验状态码/JSON → 返回解析后的 JSON。
Args:
session: 已登录的 DrissionPage SessionPage 对象(已带登录 Cookie)
method: "GET" / "POST"(GET 用 params 传参,POST 用 data 传参)
url: 接口地址
params: 请求参数
label: 接口中文名(用于报错信息)
timeout: 请求超时秒数,默认 20
Returns:
解析后的 JSON 字典
Raises:
RuntimeError: 请求失败或响应异常
"""
if method.upper() == "GET":
session.get(url, params=params, timeout=timeout)
else:
session.post(url, data=params, timeout=timeout)
return _handle_response(session.response, label)