py-wisharetec-sdk 0.1.0__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,14 @@
1
+ # ==============================================================================
2
+ # __init__.py
3
+ # ------------------------------------------------------------------------------
4
+ # 【描述】py_wisharetec_sdk 包入口。外部调用统一通过 provider 模块。
5
+ # 【文件结构】
6
+ # 重导出 __version__ / provider
7
+ # ==============================================================================
8
+
9
+ from __future__ import annotations
10
+
11
+ from . import provider
12
+ from ._version import __version__
13
+
14
+ __all__ = ["__version__", "provider"]
@@ -0,0 +1,16 @@
1
+ # ==============================================================================
2
+ # _version.py
3
+ # ------------------------------------------------------------------------------
4
+ # 【描述】py_wisharetec_sdk 版本号独立文件。
5
+ # 【文件结构】
6
+ # __version__ str 唯一的版本号变量
7
+ # 【说明】
8
+ # - 被 pyproject.toml 通过 hatchling 动态读取([tool.hatch.version] 配置)
9
+ # - 遵循语义化版本 (SemVer):主版本号 . 次版本号 . 修订号
10
+ # ==============================================================================
11
+
12
+ # SDK 版本号(语义化版本 SemVer)
13
+ # 主版本号:不兼容的 API 变更
14
+ # 次版本号:向下兼容的功能性新增
15
+ # 修订号:向下兼容的问题修正
16
+ __version__ = "0.1.0"
@@ -0,0 +1,7 @@
1
+ # ==============================================================================
2
+ # __init__.py
3
+ # ------------------------------------------------------------------------------
4
+ # 【描述】py_wisharetec_sdk 核心实现目录。
5
+ # ==============================================================================
6
+
7
+ from __future__ import annotations
@@ -0,0 +1,7 @@
1
+ # ==============================================================================
2
+ # __init__.py
3
+ # ------------------------------------------------------------------------------
4
+ # 【描述】善数(shangshu)业务模块包。
5
+ # ==============================================================================
6
+
7
+ from __future__ import annotations
@@ -0,0 +1,7 @@
1
+ # ==============================================================================
2
+ # __init__.py
3
+ # ------------------------------------------------------------------------------
4
+ # 【描述】善数・基础模块包(登录鉴权 / HTTP / 缓存 / 配置 / 模型 / 异常)。
5
+ # ==============================================================================
6
+
7
+ from __future__ import annotations
@@ -0,0 +1,177 @@
1
+ # ==============================================================================
2
+ # api.py
3
+ # ------------------------------------------------------------------------------
4
+ # 【描述】善数・基础 API — 登录 / 鉴权 / HTTP 客户端。
5
+ # 【文件结构】
6
+ # 类 ShanshuBaseAPI 登录鉴权 + HTTP 客户端 + authorization 缓存
7
+ # 类 ShanshuAPI 空别名,供 Facade 继承
8
+ # ==============================================================================
9
+
10
+ from __future__ import annotations
11
+
12
+ from typing import Any
13
+
14
+ import httpx
15
+
16
+ from .config import ShanshuAPIConfig
17
+ from .models import ShanshuCommonResponse
18
+
19
+
20
+ class ShanshuBaseAPI:
21
+ """善数平台基础客户端。
22
+
23
+ 负责账号登录、authorization 缓存、HTTP 请求发送。
24
+ 业务 API 类(如 :class:`ShanshuBaseArchiveAPI`)构造时注入本实例,
25
+ 复用其 HTTP 客户端与 authorization,无需重复登录。
26
+
27
+ Attributes:
28
+ config: 平台配置。
29
+ authorization: 最新的 authorization token(登录成功后由响应头读取)。
30
+ client: 底层 httpx.Client 实例。
31
+ """
32
+
33
+ # ------------------------------------------------------------------
34
+ # 基础接口路径常量(登录 / 鉴权验证)
35
+ # ------------------------------------------------------------------
36
+
37
+ LOGIN_PATH = "/api/user/loginInteractive"
38
+ AUTH_VERIFY_PATH = "/api/space/space/manageTree"
39
+
40
+ def __init__(
41
+ self,
42
+ config: ShanshuAPIConfig,
43
+ *,
44
+ client: httpx.Client | None = None,
45
+ client_kwargs: dict[str, Any] | None = None,
46
+ ) -> None:
47
+ """构造基础客户端。
48
+
49
+ 参数:
50
+ config: 善数平台配置。
51
+ client: 外部注入的 httpx.Client(可选,用于测试 / 连接池复用)。
52
+ client_kwargs: httpx.Client 额外参数(可选,自动补 base_url / timeout)。
53
+ """
54
+ self.config = config
55
+ self.authorization: str = ""
56
+ self._client_injected = client is not None
57
+ if client is not None:
58
+ self.client = client
59
+ else:
60
+ client_kwargs = client_kwargs or {}
61
+ client_kwargs.setdefault("base_url", config.base_url)
62
+ client_kwargs.setdefault("timeout", config.timeout)
63
+ self.client = httpx.Client(**client_kwargs)
64
+
65
+ # ==================================================================
66
+ # 请求辅助
67
+ # ==================================================================
68
+
69
+ def headers_with_authorization(self) -> dict[str, str]:
70
+ """返回带 authorization 的请求头(合并默认头 + token)。"""
71
+ return {**self.config.http_default_headers, "authorization": self.authorization or ""}
72
+
73
+ def _parse_response(self, raw: Any) -> ShanshuCommonResponse:
74
+ """将任意 JSON 响应(dict / list / str / int / float / bool / null)统一解析为 ShanshuCommonResponse。
75
+
76
+ 善数接口大部分返回 dict,但少数接口可能直接返回 list / str / int / float / bool / null。
77
+ dict 直接校验;非 dict 统一包装到 ``{"_raw": <原始值>}`` 中,
78
+ 调用方通过 ``resp.raw`` 取原始值,``resp.data`` 拿业务字段 dict。
79
+ """
80
+ if isinstance(raw, dict):
81
+ return ShanshuCommonResponse.model_validate(raw)
82
+ return ShanshuCommonResponse.model_validate({"_raw": raw})
83
+
84
+ def _get(self, url: str, payload: Any, **kwargs: Any) -> ShanshuCommonResponse:
85
+ """发送 GET 请求并解析为 ShanshuCommonResponse。"""
86
+ response = self.client.get(url=url, params=payload, **kwargs)
87
+ response.raise_for_status()
88
+ return self._parse_response(response.json())
89
+
90
+ def _post_raw(self, url: str, payload: Any, **kwargs: Any) -> ShanshuCommonResponse:
91
+ """发送 form-urlencoded POST 请求(data=payload)。"""
92
+ response = self.client.post(url=url, data=payload, **kwargs)
93
+ response.raise_for_status()
94
+ return self._parse_response(response.json())
95
+
96
+ def _post_json(self, url: str, payload: Any, **kwargs: Any) -> ShanshuCommonResponse:
97
+ """发送 JSON POST 请求(json=payload)。"""
98
+ response = self.client.post(url=url, json=payload, **kwargs)
99
+ response.raise_for_status()
100
+ return self._parse_response(response.json())
101
+
102
+ # ==================================================================
103
+ # 登录 / 鉴权
104
+ # ==================================================================
105
+
106
+ def login(self) -> ShanshuCommonResponse:
107
+ """账号密码登录,从响应头读取 authorization 并存入实例。
108
+
109
+ 返回:
110
+ 登录响应(ShanshuCommonResponse),可通过 .ok() 判断是否成功。
111
+ """
112
+ response = self.client.post(
113
+ url=self.LOGIN_PATH,
114
+ json={"account": self.config.account, "password": self.config.password_md5},
115
+ headers=self.headers_with_authorization(),
116
+ )
117
+ response.raise_for_status()
118
+ shangshu_response = ShanshuCommonResponse.model_validate(response.json())
119
+ if shangshu_response.ok():
120
+ self.authorization = response.headers.get("authorization", "")
121
+ return shangshu_response
122
+
123
+ def verfy_authorization_valid(self) -> bool:
124
+ """通过访问轻量接口验证 authorization 是否有效。
125
+
126
+ 返回:
127
+ True 表示 token 有效,False 表示无效或请求异常。
128
+ """
129
+ try:
130
+ response = self._get(
131
+ url=self.AUTH_VERIFY_PATH,
132
+ headers=self.headers_with_authorization(),
133
+ )
134
+ return response.ok()
135
+ except Exception:
136
+ return False
137
+
138
+ def refresh_authorization(self, force: bool = False) -> ShanshuBaseAPI:
139
+ """确保 authorization 有效(缓存 → 验证 → 登录)。
140
+
141
+ 优先从 config.authorization_cache 读取缓存 token;
142
+ 缓存缺失或 force=True 时触发登录,并将新 token 写入缓存(TTL 120 天)。
143
+
144
+ 参数:
145
+ force: 是否强制重新登录(忽略缓存)。
146
+
147
+ 返回:
148
+ self(支持链式调用)。
149
+ """
150
+ self.authorization = self.config.authorization_cache.get(self.config.authorization_cache_key)
151
+ if force or not self.verfy_authorization_valid():
152
+ self.login()
153
+ self.config.authorization_cache.set(
154
+ self.config.authorization_cache_key,
155
+ self.authorization,
156
+ 86400 * 120,
157
+ )
158
+ return self
159
+
160
+ # ==================================================================
161
+ # 生命周期
162
+ # ==================================================================
163
+
164
+ def close(self) -> None:
165
+ """关闭底层 HTTP 客户端(仅当 client 由本实例创建时才关闭)。"""
166
+ if not self._client_injected:
167
+ self.client.close()
168
+
169
+ def __enter__(self) -> ShanshuBaseAPI:
170
+ return self
171
+
172
+ def __exit__(self, *args: object) -> None:
173
+ self.close()
174
+
175
+
176
+ class ShanshuAPI(ShanshuBaseAPI):
177
+ """别名类,供 Facade 继承使用。"""
@@ -0,0 +1,128 @@
1
+ # ==============================================================================
2
+ # cache.py
3
+ # ------------------------------------------------------------------------------
4
+ # 【描述】善数・authorization 缓存后端。
5
+ # 【文件结构】
6
+ # 类 ShanshuAuthorizationBaseCache 缓存后端抽象基类(ABC)
7
+ # 类 ShanshuAuthorizationDiskcache diskcache 本地文件缓存(默认)
8
+ # 类 ShanshuAuthorizationRedis Redis 分布式缓存
9
+ # ==============================================================================
10
+
11
+ from __future__ import annotations
12
+
13
+ from abc import ABC, abstractmethod
14
+ from typing import Any
15
+
16
+ import diskcache
17
+
18
+
19
+ class ShanshuAuthorizationBaseCache(ABC):
20
+ """缓存后端抽象基类。
21
+
22
+ 所有缓存后端(diskcache / redis)都必须实现 set / get / delete / clear。
23
+ """
24
+
25
+ @abstractmethod
26
+ def set(self, key: str, value: str, expire: float) -> Any:
27
+ """设置缓存值。
28
+
29
+ 参数:
30
+ key: 缓存键。
31
+ value: 缓存值(str)。
32
+ expire: 过期秒数。
33
+
34
+ 返回:
35
+ 底层缓存客户端的 set 返回值。
36
+ """
37
+
38
+ @abstractmethod
39
+ def get(self, key: str) -> str:
40
+ """获取缓存值。
41
+
42
+ 参数:
43
+ key: 缓存键。
44
+
45
+ 返回:
46
+ 缓存值(str),不存在时返回空字符串。
47
+ """
48
+
49
+ @abstractmethod
50
+ def delete(self, key: str) -> Any:
51
+ """删除缓存值。
52
+
53
+ 参数:
54
+ key: 缓存键。
55
+ """
56
+
57
+ @abstractmethod
58
+ def clear(self) -> Any:
59
+ """清空整个缓存。"""
60
+
61
+
62
+ class ShanshuAuthorizationDiskcache(ShanshuAuthorizationBaseCache):
63
+ """diskcache 本地文件缓存(默认后端)。
64
+
65
+ 将 authorization 写入本地 ``.cache/py_wisharetec_sdk/shanshu`` 目录,
66
+ 进程重启后仍然有效,适合单进程或小规模集群。
67
+ """
68
+
69
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
70
+ """构造 diskcache 缓存。
71
+
72
+ 参数:
73
+ *args: 透传给 ``diskcache.Cache()``。
74
+ **kwargs: 透传给 ``diskcache.Cache()``,常用 ``directory=...``。
75
+ """
76
+ self.client = diskcache.Cache(*args, **kwargs)
77
+
78
+ def set(self, key: str, value: str, expire: float = 86400 * 180) -> Any:
79
+ """设置缓存。"""
80
+ return self.client.set(key=key, value=value, expire=expire)
81
+
82
+ def get(self, key: str) -> str:
83
+ """获取缓存,不存在时返回空字符串。"""
84
+ return self.client.get(key=key, default="")
85
+
86
+ def delete(self, key: str) -> Any:
87
+ """删除缓存。"""
88
+ return self.client.delete(key=key)
89
+
90
+ def clear(self) -> Any:
91
+ """清空缓存目录。"""
92
+ return self.client.clear()
93
+
94
+
95
+ class ShanshuAuthorizationRedis(ShanshuAuthorizationBaseCache):
96
+ """Redis 分布式缓存。
97
+
98
+ 通过 ``redis.Redis.from_url(url, ...)`` 构造,支持单例连接池。
99
+ 适合多进程 / 多服务部署场景。
100
+ """
101
+
102
+ def __init__(self, *args: Any, **kwargs: Any) -> None:
103
+ """构造 Redis 缓存。
104
+
105
+ 参数:
106
+ *args: 透传给 ``redis.Redis.from_url()``。
107
+ **kwargs: 透传给 ``redis.Redis.from_url()``。
108
+ """
109
+ import redis
110
+
111
+ self.client = redis.Redis.from_url(*args, **kwargs)
112
+
113
+ def set(self, key: str, value: str, expire: float = 86400 * 180) -> Any:
114
+ """设置缓存(使用 setex 同时设置过期时间)。"""
115
+ return self.client.setex(name=key, value=value, time=expire)
116
+
117
+ def get(self, key: str) -> str:
118
+ """获取缓存,返回 bytes 需要 decode。"""
119
+ val = self.client.get(name=key)
120
+ return val.decode("utf-8") if val else ""
121
+
122
+ def delete(self, key: str) -> Any:
123
+ """删除缓存。"""
124
+ return self.client.delete(key)
125
+
126
+ def clear(self) -> Any:
127
+ """清空当前选中的 Redis 数据库。"""
128
+ return self.client.flushdb()
@@ -0,0 +1,86 @@
1
+ # ==============================================================================
2
+ # config.py
3
+ # ------------------------------------------------------------------------------
4
+ # 【描述】善数(Wisharetec)SDK 配置模型定义。
5
+ # 【文件结构】
6
+ # 类 ShanshuAPIConfig SDK 全局配置(Pydantic BaseModel)
7
+ # ==============================================================================
8
+
9
+ from __future__ import annotations
10
+
11
+ import hashlib
12
+ from typing import Any
13
+
14
+ from pydantic import BaseModel, ConfigDict, Field
15
+
16
+ from .cache import ShanshuAuthorizationBaseCache, ShanshuAuthorizationDiskcache
17
+
18
+
19
+ class ShanshuAPIConfig(BaseModel):
20
+ """善数 SDK 全局配置(Pydantic BaseModel)。
21
+
22
+ 所有字段都会被自动校验类型;``arbitrary_types_allowed=True``
23
+ 是为了允许注入 ShanshuAuthorizationBaseCache 实例(非 Pydantic 类型)。
24
+ """
25
+
26
+ model_config = ConfigDict(arbitrary_types_allowed=True)
27
+
28
+ # ---------------- 必填 ----------------
29
+
30
+ account: str = Field(
31
+ ...,
32
+ description="善数平台登录账号(手机号)",
33
+ )
34
+
35
+ password: str = Field(
36
+ ...,
37
+ description="善数平台登录密码(明文,SDK 内部自动做 MD5 处理后发送)",
38
+ )
39
+
40
+ # ---------------- 可选 ----------------
41
+
42
+ base_url: str = Field(
43
+ default="https://saas.wisharetec.com",
44
+ description="善数平台 API 基础 URL",
45
+ )
46
+
47
+ timeout: float = Field(
48
+ default=60.0,
49
+ description="HTTP 请求超时时间(秒)",
50
+ )
51
+
52
+ authorization_cache_key_prefix: str = Field(
53
+ default="py_wisharetec_sdk:shanshu:account:",
54
+ description="登录缓存 key 前缀",
55
+ )
56
+
57
+ authorization_cache: ShanshuAuthorizationBaseCache = Field(
58
+ default_factory=lambda: ShanshuAuthorizationDiskcache(
59
+ directory=".cache/py_wisharetec_sdk/shanshu",
60
+ ),
61
+ description="登录缓存实例,默认使用 diskcache 本地文件缓存",
62
+ )
63
+
64
+ http_default_headers: dict[str, Any] = Field(
65
+ default_factory=lambda: {"client": "co-pc"},
66
+ description="所有请求都会携带的默认 HTTP 头",
67
+ )
68
+
69
+ # ==================================================================
70
+ # 计算属性
71
+ # ==================================================================
72
+
73
+ @property
74
+ def password_md5(self) -> str:
75
+ """将明文密码做 MD5,发送登录接口时使用。"""
76
+ return hashlib.md5(self.password.encode("utf-8")).hexdigest()
77
+
78
+ @property
79
+ def authorization_cache_key(self) -> str:
80
+ """拼接完整的 authorization 缓存 key:prefix + account。"""
81
+ return f"{self.authorization_cache_key_prefix}{self.account}"
82
+
83
+ def model_post_init(self, context: Any, /) -> None:
84
+ """Pydantic 初始化后钩子 — 去掉 base_url 末尾的斜杠。"""
85
+ self.base_url = self.base_url.rstrip("/")
86
+ return super().model_post_init(context)
@@ -0,0 +1,111 @@
1
+ # ==============================================================================
2
+ # models.py
3
+ # ------------------------------------------------------------------------------
4
+ # 【描述】善数・基础数据模型(Pydantic)。
5
+ # 【文件结构】
6
+ # 类 ShanshuBaseResponse 善数接口通用响应包装体
7
+ # 类 ShanshuCommonResponse 通用响应别名(与 BaseResponse 等价)
8
+ # 类 ShanshuQueryPaginatorPayload 分页查询通用入参
9
+ # ==============================================================================
10
+
11
+ from __future__ import annotations
12
+
13
+ from typing import Any
14
+
15
+ from pydantic import BaseModel, ConfigDict, Field
16
+
17
+
18
+ class ShanshuBaseResponse(BaseModel):
19
+ """善数接口通用响应模型。
20
+
21
+ 善数接口大部分返回 dict(分页数据、详情对象等),
22
+ 少数接口可能直接返回 list / str / int / float / bool / null。
23
+ 通过 ``extra="allow"`` 把业务字段挂到模型上,非 dict 响应统一包装到
24
+ ``{"_raw": <原始值>}`` 中,通过 :attr:`raw` 便捷访问。
25
+
26
+ Attributes:
27
+ code: 业务错误码(成功时通常为 None)。
28
+ msg: 业务错误信息。
29
+ data: 所有业务字段组成的 dict(含分页 records / total 等),不含 _raw。
30
+ raw: 当接口直接返回 list / str / int / float / bool / null 时,
31
+ 这里返回原始值;正常 dict 响应时返回 None。
32
+ """
33
+
34
+ model_config = ConfigDict(extra="allow", populate_by_name=True)
35
+
36
+ code: int | str | None = Field(default=None, description="业务错误码")
37
+ msg: str | None = Field(default=None, description="业务错误信息")
38
+
39
+ # ------------------------------------------------------------------
40
+ # 便捷访问
41
+ # ------------------------------------------------------------------
42
+
43
+ @property
44
+ def data(self) -> dict[str, Any]:
45
+ """所有业务字段组成的 dict(不含 code / msg / _raw)。"""
46
+ extra = dict(self.model_extra or {})
47
+ extra.pop("_raw", None)
48
+ return extra
49
+
50
+ @property
51
+ def raw(self) -> Any:
52
+ """非 dict 响应的原始值(list / str / int / float / bool / null)。
53
+
54
+ 只有当接口返回非 dict JSON 时才有值;正常 dict 响应返回 None,
55
+ 此时应使用 :attr:`data` 访问业务字段。
56
+ """
57
+ return (self.model_extra or {}).get("_raw")
58
+
59
+ def ok(self) -> bool:
60
+ """是否为成功响应。
61
+
62
+ 判断规则:只有同时存在 code + msg 且没有任何业务字段(含 _raw)时才视为失败。
63
+ """
64
+ return not (
65
+ self.code is not None
66
+ and self.msg is not None
67
+ and not self.model_extra
68
+ )
69
+
70
+
71
+ class ShanshuCommonResponse(ShanshuBaseResponse):
72
+ """通用响应别名(与 ShanshuBaseResponse 等价)。"""
73
+
74
+
75
+ class ShanshuQueryPaginatorPayload(BaseModel):
76
+ """善数分页查询通用入参。
77
+
78
+ 字段与前端实际请求体保持一致(camelCase 别名序列化)。
79
+ 支持以 dict 形式传入任意分页请求体(如前端抓包原样透传)。
80
+ """
81
+
82
+ model_config = ConfigDict(populate_by_name=True, serialize_by_alias=True, extra="allow")
83
+
84
+ conditions: dict = Field(
85
+ default_factory=lambda: {"fields": []},
86
+ description="查询条件,常用结构为 {'fields': [...]}",
87
+ )
88
+ count: bool = Field(default=True, description="是否统计总数")
89
+ last: bool = Field(default=True, description="是否为最后一次查询")
90
+ order_by: list = Field(default_factory=list, alias="orderBy", description="排序条件")
91
+ page_num: int = Field(default=1, alias="pageNum", description="页码,从 1 开始")
92
+ page_size: int = Field(default=20, alias="pageSize", description="每页条数")
93
+
94
+ @classmethod
95
+ def normalize(
96
+ cls,
97
+ payload: ShanshuQueryPaginatorPayload | dict | None,
98
+ ) -> dict[str, Any]:
99
+ """将 ``ShanshuQueryPaginatorPayload`` / ``dict`` / ``None`` 统一转换为可发送的 dict。
100
+
101
+ Args:
102
+ payload: 分页查询入参,三种类型均可。
103
+
104
+ Returns:
105
+ 序列化后的 dict(camelCase 别名)。
106
+ """
107
+ if payload is None:
108
+ return cls().model_dump(by_alias=True)
109
+ if isinstance(payload, cls):
110
+ return payload.model_dump(by_alias=True)
111
+ return payload
@@ -0,0 +1,7 @@
1
+ # ==============================================================================
2
+ # __init__.py
3
+ # ------------------------------------------------------------------------------
4
+ # 【描述】善数・基础档案(base_archive)API 包。
5
+ # ==============================================================================
6
+
7
+ from __future__ import annotations