feat(sdk): desktopauto 0.5.3 银行卡/证件 OCR 增强、dingtalk 1.1.0、aitable 0.1.3
- desktopauto:cardocr 引擎/流水线/校验与 ocr 调整,sdk.json/pyproject/版本三处一致 - dingtalk:AI 表格读写与错误封装扩充 - aitable:client/cli/自测与打包配置更新
This commit is contained in:
+30
-1
@@ -22,6 +22,7 @@
|
||||
| 群聊推送(文本/文件、标题、@所有人、@成员) | `dws.Dws`、`dws.push` | 同上 |
|
||||
| 防封控限流 + 推送记录 CSV | `Dws(rate_limit=...)`、`Dws(record_dir=...)` | 同上 |
|
||||
| AI 表格读写(sheet/字段/分页读/批量增改、值归一与类型转换) | `aitable.AiTable` | `libs/aitable/aitable/client.py` |
|
||||
| AI 表格附件下载(图片/文件字段、预签名过期检测、重试/命名/魔数校验) | `aitable.AiTable.download_attachments`、`aitable.attachment_items` | 新增(`libs/aitable` 1.1.0 同步实现) |
|
||||
| 月报/周报数据采集(Git + 需求表) | `report.collect`、`python -m dingtalk_sdk.report` | `libs/aitable/aitable/report.py` |
|
||||
|
||||
不在范围内:`workflows/share/dingtalk_sender.py`(已废弃的 OCR + 模拟点击单聊推送,
|
||||
@@ -96,6 +97,32 @@ with AiTable() as table: # 操作人取配置 AITABLE_OPERATOR_UN
|
||||
`base` 参数支持别名(`workplan` / `hr`)、baseId、alidocs 链接三种写法,方法内部自动转换
|
||||
(旧 `libs/aitable` 需要先调 `resolve_base`,SDK 里可省略)。
|
||||
|
||||
附件(图片/文件)字段的下载:
|
||||
|
||||
```python
|
||||
from dingtalk_sdk import AiTable, attachment_items
|
||||
|
||||
with AiTable() as table:
|
||||
rows = table.records("hr", "uavChPe") # 银行卡-变更收集表
|
||||
for record in rows:
|
||||
fields = record.get("fields") or {}
|
||||
photos = attachment_items(fields.get("银行卡卡号面照片")) # 元数据(含预签名 url)
|
||||
for res in table.download_attachments(fields.get("银行卡卡号面照片"),
|
||||
rf"D:\资料\银行卡照片\{fields.get('持卡人姓名', '')}",
|
||||
prefix="银行卡-"):
|
||||
print(res["ok"], res["path"], res["kind"], res["size_match"])
|
||||
```
|
||||
|
||||
要点:
|
||||
|
||||
- `attachment` 字段的 `url` 是阿里云 OSS **预签名地址**(免 token 直连,约 **2 小时过期**):
|
||||
拉完记录要立刻下载,过期只能重拉记录换新地址(抛 `AttachmentExpiredError`,重试同一地址无用);
|
||||
- `download_attachment()` 单文件失败抛异常;`download_attachments()` 批量时单文件失败**不中断**,
|
||||
结果里 `ok=False` + `error` + `expired`;
|
||||
- 落盘文件名为 `prefix + 原文件名`,同名自动加 `-2`,非法字符换 `_`,限长 120;
|
||||
- `kind` 按文件头魔数判断真实类型、`size_match` 与表格声明大小比对,防止把错误页/半截文件当图片;
|
||||
- `resourceUrl` 是相对路径,不能直连(`attachment_items` 会丢掉它)。
|
||||
|
||||
### 5. 月报 / 周报
|
||||
|
||||
```python
|
||||
@@ -135,6 +162,7 @@ dws 可执行文件解析顺序:`Dws(bin=...)` > `DINGTALK_DWS_BIN` > `~/.loca
|
||||
| 项 | 旧实现 | SDK |
|
||||
|---|---|---|
|
||||
| 错误 | `SystemExit` / 返回 dict 混用 | 统一异常(`ConfigError`/`ApiError`/`NetworkError`/`DwsError`);兼容入口 `robot.push` / `dws.push` 仍返回 dict |
|
||||
| 附件下载 | 无(只有 `attachment` 元数据) | `download_attachment(s)`;预签名过期抛 `AttachmentExpiredError`,批量失败项不中断 |
|
||||
| 输出 | 直接 `print` | 通过 `log=` 回调(默认静默),不污染插件日志 |
|
||||
| 环境定位 | 按 `__file__` 推仓库根 | 按 cwd 向上 + 环境变量 |
|
||||
| 影刀全局变量 | 写 `glv['push_record_path']` | 仍 best-effort 写;同时 `push()` 返回 `record_path` |
|
||||
@@ -173,7 +201,7 @@ cd libs\dingtalk; ..\..\.venv\Scripts\python.exe -m dingtalk_sdk._selftest; cd .
|
||||
# 直发正式(SDK 无独立入口、无法单测,不走测试通道;要小范围看就发消费插件的测试版)
|
||||
.venv\Scripts\python.exe tools\agent_cli.py --admin puddy --password 123456 `
|
||||
--base http://172.30.30.243:8800 `
|
||||
sdk-publish dist-sdk\dingtalk_sdk_v0.1.2.zip --baseline-sdk <上一版 zip> --prod
|
||||
sdk-publish dist-sdk\dingtalk_sdk_v0.1.3.zip --baseline-sdk <上一版 zip> --prod
|
||||
```
|
||||
|
||||
完整发版 SOP 见技能 `.skills/37du-SDK-Deploy/SKILL.md`;`^0.x` 是标准 caret 语义,
|
||||
@@ -190,3 +218,4 @@ cd libs\dingtalk; ..\..\.venv\Scripts\python.exe -m dingtalk_sdk._selftest; cd .
|
||||
5. **AI 表格必须带 `operatorId`**:操作人须是目标表协作者,个人空间文档默认不对应用开放。
|
||||
6. **日期是毫秒时间戳 + 北京时间**:`norm` / `to_ms` 已处理,自己拼时间戳容易整体差一天。
|
||||
7. **dws 限流**:默认 50 条/分钟,批量推送会阻塞等待(不丢消息),长批次请预留时间。
|
||||
8. **表格附件 url 约 2 小时过期**:`attachment` 字段里的 `url` 是预签名地址,必须“拉记录 → 立刻下载”,不能存 url 隔夜用;翻页拉 5000 条再回头下载前面的是常见翻车点。
|
||||
|
||||
+43
-4
@@ -1,13 +1,14 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"sdk_id": "dingtalk_sdk",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"modules": {
|
||||
"dingtalk_sdk": {
|
||||
"exports": [
|
||||
"AccessToken",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
@@ -20,6 +21,7 @@
|
||||
"RobotAccount",
|
||||
"Settings",
|
||||
"aitable",
|
||||
"attachment_items",
|
||||
"auth",
|
||||
"build_sign",
|
||||
"build_url",
|
||||
@@ -38,12 +40,15 @@
|
||||
"media",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"parse_period",
|
||||
"push_dws",
|
||||
"push_robot",
|
||||
"report",
|
||||
"resolve_base",
|
||||
"robot",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"split_by_chars",
|
||||
"to_base_id",
|
||||
"to_ms",
|
||||
@@ -55,6 +60,7 @@
|
||||
"AccessToken",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
@@ -67,6 +73,7 @@
|
||||
"RobotAccount",
|
||||
"Settings",
|
||||
"aitable",
|
||||
"attachment_items",
|
||||
"auth",
|
||||
"build_sign",
|
||||
"build_url",
|
||||
@@ -85,12 +92,15 @@
|
||||
"media",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"parse_period",
|
||||
"push_dws",
|
||||
"push_robot",
|
||||
"report",
|
||||
"resolve_base",
|
||||
"robot",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"split_by_chars",
|
||||
"to_base_id",
|
||||
"to_ms",
|
||||
@@ -108,6 +118,7 @@
|
||||
"Robot": "(webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '', env: 'str' = 'prod', timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[Callable[[str], None]]' = None) -> 'None'",
|
||||
"RobotAccount": "(webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '37du 任务调度平台') -> None",
|
||||
"Settings": "(app_key: 'str' = '', app_secret: 'str' = '', operator: 'str' = '', dws_bin: 'str' = '', timeout: 'float' = 30.0, retries: 'int' = 3, rate_limit: 'int' = 50, rate_window: 'float' = 60.0, default_env: 'str' = 'prod', robots: 'Dict[str, RobotAccount]' = <factory>, base_aliases: 'Dict[str, str]' = <factory>) -> None",
|
||||
"attachment_items": "(value: 'Any') -> 'List[Dict[str, Any]]'",
|
||||
"build_sign": "(secret: 'str', timestamp_ms: 'Union[int, str]') -> 'str'",
|
||||
"build_url": "(webhook: 'str', secret: 'str' = '') -> 'str'",
|
||||
"coerce_for_fields": "(meta: 'dict', data: 'dict') -> 'dict'",
|
||||
@@ -120,10 +131,13 @@
|
||||
"markdown_image": "(media_id: 'str', alt: 'str' = '图片') -> 'str'",
|
||||
"ms_to_str": "(ms: 'Any', with_time: 'bool' = False) -> 'str'",
|
||||
"norm": "(value: 'Any') -> 'Any'",
|
||||
"parse_expires": "(url: 'str') -> 'int'",
|
||||
"parse_period": "(month: 'str' = '', week: 'Optional[str]' = None) -> 'dict'",
|
||||
"push_dws": "(messages: 'Iterable', record_dir: 'str' = '', chat_type: 'str' = '') -> 'dict'",
|
||||
"push_robot": "(text, title: 'str' = '消息通知', status: 'str' = 'info', webhook: 'str' = '', secret: 'str' = '', server_name: 'str' = '', env: 'str' = 'prod', batch: 'bool' = False, max_chars: 'int' = 15000, log: 'Optional[Callable[[str], None]]' = None) -> 'dict'",
|
||||
"resolve_base": "(raw: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'Tuple[str, str]'",
|
||||
"safe_filename": "(name: 'Any', fallback: 'str' = 'file') -> 'str'",
|
||||
"sniff_kind": "(path: 'Any') -> 'str'",
|
||||
"split_by_chars": "(content: 'str', max_chars: 'int' = 15000) -> 'List[str]'",
|
||||
"to_base_id": "(base: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'str'",
|
||||
"to_ms": "(value: 'Any') -> 'Optional[int]'",
|
||||
@@ -148,6 +162,7 @@
|
||||
"report",
|
||||
"robot",
|
||||
"test_aitable",
|
||||
"test_aitable_attachment",
|
||||
"test_config",
|
||||
"test_dws",
|
||||
"test_http",
|
||||
@@ -160,6 +175,7 @@
|
||||
"signatures": {
|
||||
"main": "() -> 'int'",
|
||||
"test_aitable": "() -> 'None'",
|
||||
"test_aitable_attachment": "() -> 'None'",
|
||||
"test_config": "() -> 'None'",
|
||||
"test_dws": "() -> 'None'",
|
||||
"test_http": "() -> 'None'",
|
||||
@@ -170,45 +186,66 @@
|
||||
},
|
||||
"dingtalk_sdk.aitable": {
|
||||
"exports": [
|
||||
"ATTACH_MIN_REMAIN",
|
||||
"ATTACH_TIMEOUT",
|
||||
"MAX_PAGES",
|
||||
"PAGE_SIZE",
|
||||
"TZ_CN",
|
||||
"WRITE_BATCH",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"attachment_items",
|
||||
"coerce_for_fields",
|
||||
"flatten",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"resolve_base",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"to_base_id",
|
||||
"to_ms"
|
||||
"to_ms",
|
||||
"unique_path"
|
||||
],
|
||||
"all": [
|
||||
"ATTACH_MIN_REMAIN",
|
||||
"ATTACH_TIMEOUT",
|
||||
"MAX_PAGES",
|
||||
"PAGE_SIZE",
|
||||
"TZ_CN",
|
||||
"WRITE_BATCH",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"attachment_items",
|
||||
"coerce_for_fields",
|
||||
"flatten",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"resolve_base",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"to_base_id",
|
||||
"to_ms"
|
||||
"to_ms",
|
||||
"unique_path"
|
||||
],
|
||||
"signatures": {
|
||||
"AiTable": "(operator: 'str' = '', app_key: 'str' = '', app_secret: 'str' = '', timeout: 'Optional[float]' = None, retries: 'Optional[int]' = None, log: 'Optional[Callable[[str], None]]' = None) -> 'None'",
|
||||
"ApiError": "(message: 'str', code: 'str' = '', errmsg: 'str' = '', payload=None)",
|
||||
"attachment_items": "(value: 'Any') -> 'List[Dict[str, Any]]'",
|
||||
"coerce_for_fields": "(meta: 'dict', data: 'dict') -> 'dict'",
|
||||
"flatten": "(record: 'dict') -> 'dict'",
|
||||
"ms_to_str": "(ms: 'Any', with_time: 'bool' = False) -> 'str'",
|
||||
"norm": "(value: 'Any') -> 'Any'",
|
||||
"parse_expires": "(url: 'str') -> 'int'",
|
||||
"resolve_base": "(raw: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'Tuple[str, str]'",
|
||||
"safe_filename": "(name: 'Any', fallback: 'str' = 'file') -> 'str'",
|
||||
"sniff_kind": "(path: 'Any') -> 'str'",
|
||||
"to_base_id": "(base: 'str', aliases: 'Optional[Dict[str, str]]' = None) -> 'str'",
|
||||
"to_ms": "(value: 'Any') -> 'Optional[int]'"
|
||||
"to_ms": "(value: 'Any') -> 'Optional[int]'",
|
||||
"unique_path": "(dest: 'Path') -> 'Path'"
|
||||
}
|
||||
},
|
||||
"dingtalk_sdk.auth": {
|
||||
@@ -336,6 +373,7 @@
|
||||
"dingtalk_sdk.errors": {
|
||||
"exports": [
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
@@ -345,6 +383,7 @@
|
||||
],
|
||||
"all": [
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
|
||||
@@ -33,16 +33,17 @@ AI 表格(notable)读写 :class:`aitable.AiTable` 与值归一工具
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
__version__ = "0.1.2"
|
||||
__version__ = "0.1.3"
|
||||
|
||||
from . import aitable, auth, config, dws, errors, http, media, robot
|
||||
from .aitable import (AiTable, coerce_for_fields, flatten, ms_to_str, norm, resolve_base,
|
||||
from .aitable import (AiTable, attachment_items, coerce_for_fields, flatten, ms_to_str,
|
||||
norm, parse_expires, resolve_base, safe_filename, sniff_kind,
|
||||
to_base_id, to_ms)
|
||||
from .auth import AccessToken, invalidate as invalidate_token, token
|
||||
from .config import RobotAccount, Settings, get_settings, load_env_files
|
||||
from .dws import Dws, push as push_dws
|
||||
from .errors import (ApiError, AuthError, CancelledError, ConfigError, DingTalkError,
|
||||
DwsError, NetworkError)
|
||||
from .errors import (ApiError, AttachmentExpiredError, AuthError, CancelledError,
|
||||
ConfigError, DingTalkError, DwsError, NetworkError)
|
||||
from .media import markdown_image, upload_media
|
||||
from .robot import (DingTalkRobot, Robot, build_sign, build_url, compose_batch_messages,
|
||||
push as push_robot, split_by_chars)
|
||||
@@ -64,6 +65,7 @@ __all__ = [
|
||||
"AccessToken",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
@@ -76,6 +78,7 @@ __all__ = [
|
||||
"RobotAccount",
|
||||
"Settings",
|
||||
"aitable",
|
||||
"attachment_items",
|
||||
"auth",
|
||||
"build_sign",
|
||||
"build_url",
|
||||
@@ -94,12 +97,15 @@ __all__ = [
|
||||
"media",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"parse_period",
|
||||
"push_dws",
|
||||
"push_robot",
|
||||
"report",
|
||||
"resolve_base",
|
||||
"robot",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"split_by_chars",
|
||||
"to_base_id",
|
||||
"to_ms",
|
||||
|
||||
@@ -225,6 +225,97 @@ def test_aitable() -> None:
|
||||
"baseId 幂等")
|
||||
|
||||
|
||||
# ==================== AI 表格:附件下载 ====================
|
||||
|
||||
def test_aitable_attachment() -> None:
|
||||
import socketserver
|
||||
import http.server as httpserver
|
||||
import tempfile
|
||||
import threading
|
||||
|
||||
value = [{"resourceId": "r1", "filename": "卡号面.jpg", "size": 12, "type": "image",
|
||||
"url": "https://x.oss-cn/y.jpg?Expires=1794886717&Signature=abc"},
|
||||
{"resourceId": "r2", "filename": "身份证.png", "size": 8, "type": "image",
|
||||
"resourceUrl": "/core/api/resources/img/zz"}]
|
||||
items = aitable.attachment_items(value)
|
||||
_eq(len(items), 2, "attachment 字段值拆出 2 个附件")
|
||||
_eq(items[0]["size"], 12, "声明大小保留")
|
||||
_eq(items[1]["url"], "", "相对 resourceUrl 不当作可直连地址")
|
||||
_eq(aitable.attachment_items(None), [], "空附件返回空列表")
|
||||
_eq(aitable.attachment_items({"filename": "x"})[0]["url"], "", "单个 dict 兼容")
|
||||
_eq(aitable.parse_expires(items[0]["url"]), 1794886717, "解析预签名 Expires")
|
||||
_eq(aitable.parse_expires("https://x/y.jpg"), 0, "无 Expires 返回 0")
|
||||
|
||||
_eq(aitable.safe_filename('a/b:c*?"<>|.jpg'), "a_b_c_.jpg", "非法字符换下划线")
|
||||
_eq(aitable.safe_filename("", ""), "file", "空名兜底")
|
||||
_eq(len(aitable.safe_filename("x" * 200)), 120, "文件名限长 120")
|
||||
|
||||
# 本地 HTTP 服务模拟 OSS;不联网、不读生产凭证
|
||||
png = b"\x89PNG\r\n\x1a\n" + b"\0" * 24
|
||||
|
||||
class _Handler(httpserver.BaseHTTPRequestHandler):
|
||||
def do_GET(self):
|
||||
if self.path.startswith("/ok"):
|
||||
self.send_response(200)
|
||||
self.send_header("content-type", "image/png")
|
||||
self.send_header("content-length", str(len(png)))
|
||||
self.end_headers()
|
||||
self.wfile.write(png)
|
||||
else:
|
||||
self.send_response(403)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *args):
|
||||
pass
|
||||
|
||||
table = object.__new__(aitable.AiTable) # 只测下载,不初始化鉴权
|
||||
table._http = http.HttpClient(retries=2, timeout=5, log=lambda m: None)
|
||||
|
||||
with socketserver.TCPServer(("127.0.0.1", 0), _Handler) as srv:
|
||||
threading.Thread(target=srv.serve_forever, daemon=True).start()
|
||||
base = f"http://127.0.0.1:{srv.server_address[1]}"
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
res = table.download_attachment({"url": f"{base}/ok.png", "size": len(png)},
|
||||
os.path.join(tmp, "a.png"))
|
||||
_ok(res["ok"] and res["kind"] == "png" and res["size_match"] is True,
|
||||
"下载成功 + 魔数/声明大小校验")
|
||||
|
||||
dup = table.download_attachment({"url": f"{base}/ok.png"},
|
||||
os.path.join(tmp, "a.png"))
|
||||
_eq(os.path.basename(dup["path"]), "a-2.png", "同名附件不覆盖")
|
||||
|
||||
_raises(aitable.AttachmentExpiredError,
|
||||
lambda: table.download_attachment({"url": f"{base}/deny.png"},
|
||||
os.path.join(tmp, "b.png")),
|
||||
"403 抛 AttachmentExpiredError")
|
||||
_raises(aitable.AttachmentExpiredError,
|
||||
lambda: table.download_attachment(
|
||||
{"url": f"{base}/ok.png?Expires=1000"},
|
||||
os.path.join(tmp, "c.png")),
|
||||
"Expires 已过期 → 不发请求直接报过期")
|
||||
_raises(config.ConfigError,
|
||||
lambda: table.download_attachment({"resourceUrl": "/x"},
|
||||
os.path.join(tmp, "d.png")),
|
||||
"无可直连 url 抛 ConfigError")
|
||||
|
||||
# 批量:单文件失败不中断,过期项打 expired,prefix 命名生效
|
||||
batch = table.download_attachments(
|
||||
[{"url": f"{base}/ok.png", "filename": "卡号面.jpg", "size": len(png)},
|
||||
{"url": f"{base}/deny.png", "filename": "身份证.png"}],
|
||||
os.path.join(tmp, "sub"), prefix="银行卡-", col="银行卡卡号面照片")
|
||||
_eq(len(batch), 2, "批量下载 2 个附件")
|
||||
_ok(batch[0]["ok"] and os.path.basename(batch[0]["path"]) == "银行卡-卡号面.jpg",
|
||||
"批量成功项落盘且带 prefix")
|
||||
_ok(batch[1]["ok"] is False and batch[1]["expired"] is True
|
||||
and "403" in batch[1]["error"], "批量失败项标 expired 并带原因")
|
||||
_eq(batch[1]["col"], "银行卡卡号面照片", "结果带字段名")
|
||||
_eq(batch[0]["index"], 1, "结果带序号")
|
||||
finally:
|
||||
srv.shutdown()
|
||||
srv.server_close()
|
||||
|
||||
|
||||
# ==================== 媒体 ====================
|
||||
|
||||
def test_media() -> None:
|
||||
@@ -264,6 +355,7 @@ def main() -> int:
|
||||
("http", test_http),
|
||||
("dws", test_dws),
|
||||
("aitable", test_aitable),
|
||||
("aitable_attachment", test_aitable_attachment),
|
||||
("media", test_media),
|
||||
("report", test_report),
|
||||
]
|
||||
|
||||
@@ -1,15 +1,19 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""钉钉 AI 表格(notable)读写。
|
||||
|
||||
能力(与原 ``libs/aitable`` 一致):
|
||||
能力(在原 ``libs/aitable`` 一致基础上补齐附件下载):
|
||||
- 列 sheet / 字段定义;按 ``hasMore`` + ``nextToken`` 分页读全量记录;
|
||||
- 批量新增 / 更新记录(自动按 20 条一批);
|
||||
- 值归一(``norm``)、日期毫秒互转(``ms_to_str`` / ``to_ms``)、
|
||||
按字段类型转换写入值(``coerce_for_fields``)、记录拍平(``flatten``);
|
||||
- 附件(图片/文件)字段解析与下载:``attachment_items`` + ``AiTable.download_attachments``
|
||||
(``attachment`` 字段里带阿里云 OSS 预签名 url,免 token 直连、约 2 小时过期);
|
||||
- base 支持别名 / baseId / alidocs 链接三种写法(``resolve_base``)。
|
||||
|
||||
与旧实现的差异(SDK 契约要求):
|
||||
- 失败抛 ``ConfigError`` / ``ApiError`` / ``NetworkError``,**不再 SystemExit**;
|
||||
- 预签名附件地址过期抛 ``AttachmentExpiredError``(``ConfigError`` 子类),
|
||||
批量下载时单文件失败不中断,结果里 ``ok=False`` 并带原因;
|
||||
- 凭证与操作人可显式传入,缺省读配置(见 :mod:`dingtalk_sdk.config`)。
|
||||
"""
|
||||
|
||||
@@ -17,12 +21,17 @@ from __future__ import annotations
|
||||
|
||||
import json
|
||||
import re
|
||||
import time
|
||||
import urllib.parse as urllib_parse
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from pathlib import Path
|
||||
from typing import Any, Callable, Dict, List, Optional, Tuple
|
||||
|
||||
import requests
|
||||
|
||||
from .auth import KIND_V1, AccessToken
|
||||
from .config import BASE_ALIASES, get_settings
|
||||
from .errors import ApiError, ConfigError
|
||||
from .errors import ApiError, AttachmentExpiredError, ConfigError, NetworkError
|
||||
from .http import API_BASE, HttpClient, install_dns_fallback
|
||||
|
||||
TZ_CN = timezone(timedelta(hours=8)) # 表格日期按北京时间落库(毫秒时间戳)
|
||||
@@ -32,6 +41,12 @@ WRITE_BATCH = 20 # 批量写单次上限
|
||||
MAX_PAGES = 500 # 500 × 100 = 5 万条上限
|
||||
_TS_FLOOR = 1_000_000_000_000 # 毫秒时间戳判定下限
|
||||
|
||||
ATTACH_MIN_REMAIN = 60 # 预签名 url 剩余有效期低于该秒数即视为不可用
|
||||
ATTACH_TIMEOUT = 30.0 # 附件下载单次超时(秒)
|
||||
_BAD_NAME = re.compile(r'[\\/:*?"<>|\r\n\t]+')
|
||||
_MAGIC = ((b"\xff\xd8\xff", "jpg"), (b"\x89PNG\r\n\x1a\n", "png"),
|
||||
(b"GIF87a", "gif"), (b"GIF89a", "gif"), (b"BM", "bmp"), (b"%PDF", "pdf"))
|
||||
|
||||
|
||||
# ==================== 值归一 / 类型转换 ====================
|
||||
|
||||
@@ -106,6 +121,77 @@ def flatten(record: dict) -> dict:
|
||||
return row
|
||||
|
||||
|
||||
# ==================== 附件(图片 / 文件)====================
|
||||
|
||||
def attachment_items(value: Any) -> List[Dict[str, Any]]:
|
||||
"""``attachment`` 字段值 → ``[{resourceId, filename, size, type, url}]``。
|
||||
|
||||
notable 返回的附件元数据里 ``url`` 是阿里云 OSS **预签名地址**(免 token 直连、
|
||||
约 2 小时过期);``resourceUrl`` 是相对路径不能直连,故只保留绝对 url。
|
||||
"""
|
||||
if not value:
|
||||
return []
|
||||
if isinstance(value, dict):
|
||||
value = [value]
|
||||
out: List[Dict[str, Any]] = []
|
||||
for item in value:
|
||||
if not isinstance(item, dict):
|
||||
continue
|
||||
url = str(item.get("url") or "")
|
||||
if not url.startswith(("http://", "https://")):
|
||||
url = ""
|
||||
out.append({"resourceId": item.get("resourceId") or "",
|
||||
"filename": item.get("filename") or "",
|
||||
"size": int(item.get("size") or 0),
|
||||
"type": item.get("type") or "",
|
||||
"url": url})
|
||||
return out
|
||||
|
||||
|
||||
def parse_expires(url: str) -> int:
|
||||
"""预签名 url 的 ``Expires`` 秒级时间戳;取不到返回 0(不限时的地址)。"""
|
||||
try:
|
||||
query = urllib_parse.parse_qs(urllib_parse.urlparse(url).query)
|
||||
return int((query.get("Expires") or ["0"])[0] or 0)
|
||||
except (TypeError, ValueError):
|
||||
return 0
|
||||
|
||||
|
||||
def safe_filename(name: Any, fallback: str = "file") -> str:
|
||||
"""文件名净化:Windows 非法字符换 ``_``、去首尾点空格、限长 120。"""
|
||||
text = _BAD_NAME.sub("_", str(name or "")).strip(" .")
|
||||
if not text:
|
||||
text = _BAD_NAME.sub("_", str(fallback or "file")).strip(" .") or "file"
|
||||
return text[:120]
|
||||
|
||||
|
||||
def sniff_kind(path: Any) -> str:
|
||||
"""按文件头魔数判断真实类型(避免把错误页/半截文件当图片存下来)。"""
|
||||
try:
|
||||
head = Path(path).read_bytes()[:16]
|
||||
except OSError:
|
||||
return "missing"
|
||||
if head[:4] == b"RIFF" and b"WEBP" in head[:16]:
|
||||
return "webp"
|
||||
for sig, kind in _MAGIC:
|
||||
if head.startswith(sig):
|
||||
return kind
|
||||
return "unknown"
|
||||
|
||||
|
||||
def unique_path(dest: Path) -> Path:
|
||||
"""目标已存在时追加 ``-2``、``-3``…,避免同名附件互相覆盖。"""
|
||||
dest = Path(dest)
|
||||
if not dest.exists():
|
||||
return dest
|
||||
index = 2
|
||||
while True:
|
||||
candidate = dest.with_name(f"{dest.stem}-{index}{dest.suffix}")
|
||||
if not candidate.exists():
|
||||
return candidate
|
||||
index += 1
|
||||
|
||||
|
||||
def resolve_base(raw: str, aliases: Optional[Dict[str, str]] = None) -> Tuple[str, str]:
|
||||
"""别名 / baseId / alidocs 链接 → ``(baseId, 链接里带的 sheetId 或空)``。"""
|
||||
mapping = dict(BASE_ALIASES)
|
||||
@@ -263,19 +349,124 @@ class AiTable:
|
||||
return self.update(base, sheet,
|
||||
[{"id": record_id, "fields": coerce_for_fields(meta, fields)}])
|
||||
|
||||
# ---- 附件(图片 / 文件)下载 ----
|
||||
def download_attachment(self, item: Dict[str, Any], dest: Any,
|
||||
overwrite: bool = False,
|
||||
timeout: Optional[float] = None) -> Dict[str, Any]:
|
||||
"""下载单个附件到 ``dest``,返回结果 dict(``ok`` 恒为 True)。
|
||||
|
||||
返回字段:``path`` / ``bytes`` / ``kind`` / ``content_type`` / ``size_match``
|
||||
(与表格声明大小比对)/ ``expires_in``(预签名剩余秒数)。
|
||||
|
||||
Raises:
|
||||
AttachmentExpiredError: 预签名地址已过期/即将过期,或下载被拒(403)——
|
||||
重新 ``records()`` 拉记录换新地址,重试同一地址无用
|
||||
ConfigError: 附件没有可直连 url(只有相对 ``resourceUrl``)
|
||||
ApiError: OSS 返回其它非 2xx
|
||||
NetworkError: 重试耗尽仍未下载成功
|
||||
"""
|
||||
target = Path(dest)
|
||||
item = item or {}
|
||||
url = str(item.get("url") or "")
|
||||
if not url:
|
||||
raise ConfigError("附件没有可直连的 url(只有相对 resourceUrl)")
|
||||
expires_in: Optional[int] = None
|
||||
expires = parse_expires(url)
|
||||
if expires:
|
||||
expires_in = int(expires - time.time())
|
||||
if expires_in <= ATTACH_MIN_REMAIN:
|
||||
raise AttachmentExpiredError(
|
||||
f"预签名 url 已过期/即将过期(剩 {expires_in}s),请重新拉记录换新地址")
|
||||
target = target if overwrite else unique_path(target)
|
||||
tmo = float(timeout if timeout is not None else ATTACH_TIMEOUT)
|
||||
last: Optional[BaseException] = None
|
||||
for attempt in range(1, self._http.retries + 1):
|
||||
try:
|
||||
resp = self._http.session.get(url, timeout=tmo)
|
||||
except requests.RequestException as exc: # 网络抖动
|
||||
last = NetworkError(f"附件下载失败({attempt}/{self._http.retries}):{exc}")
|
||||
else:
|
||||
if resp.status_code == 403:
|
||||
raise AttachmentExpiredError(
|
||||
"附件下载被拒(403,预签名 url 已过期或无权限),请重新拉记录")
|
||||
if resp.status_code >= 400:
|
||||
last = ApiError(f"附件下载失败:HTTP {resp.status_code}",
|
||||
code=str(resp.status_code))
|
||||
else:
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
target.write_bytes(resp.content)
|
||||
declared = int(item.get("size") or 0)
|
||||
return {"ok": True, "path": str(target), "bytes": len(resp.content),
|
||||
"kind": sniff_kind(target),
|
||||
"content_type": resp.headers.get("content-type", ""),
|
||||
"size_match": (None if not declared
|
||||
else len(resp.content) == declared),
|
||||
"expires_in": expires_in}
|
||||
if attempt < self._http.retries:
|
||||
time.sleep(1.0 * attempt)
|
||||
assert last is not None
|
||||
if isinstance(last, (ApiError, NetworkError)):
|
||||
raise last
|
||||
raise NetworkError(f"附件下载失败:{last}")
|
||||
|
||||
def download_attachments(self, value: Any, save_dir: Any, prefix: str = "",
|
||||
col: str = "", overwrite: bool = False) -> List[Dict[str, Any]]:
|
||||
"""下载一个 ``attachment`` 字段的全部附件到 ``save_dir/``(``prefix + 原文件名``)。
|
||||
|
||||
单个附件失败不中断,结果里 ``ok=False`` 并带 ``error``/``expired``;成功项带
|
||||
``path``/``bytes``/``kind``/``size_match``。结果额外含 ``col``/``index``/
|
||||
``filename``/``resourceId``/``declared_size``,便于按字段归类落盘。
|
||||
|
||||
Example::
|
||||
|
||||
rows = table.records("hr", "uavChPe") # 银行卡-变更收集表
|
||||
for record in rows:
|
||||
fields = record.get("fields") or {}
|
||||
table.download_attachments(fields.get("银行卡卡号面照片"),
|
||||
rf"D:\\资料\\银行卡照片\\{fields.get('持卡人姓名','')}",
|
||||
prefix="银行卡-")
|
||||
"""
|
||||
results: List[Dict[str, Any]] = []
|
||||
for index, item in enumerate(attachment_items(value), 1):
|
||||
name = safe_filename(item["filename"],
|
||||
item["resourceId"] or f"{col or 'file'}{index}")
|
||||
target = Path(save_dir) / safe_filename(f"{prefix}{name}" if prefix else name)
|
||||
row: Dict[str, Any] = {
|
||||
"col": col or "", "index": index, "filename": item["filename"],
|
||||
"resourceId": item["resourceId"], "declared_size": item["size"],
|
||||
"ok": False, "path": "", "bytes": 0, "kind": "", "content_type": "",
|
||||
"size_match": None, "expires_in": None, "expired": False, "error": "",
|
||||
}
|
||||
try:
|
||||
row.update(self.download_attachment(item, target, overwrite=overwrite))
|
||||
except AttachmentExpiredError as exc:
|
||||
row.update(expired=True, error=str(exc))
|
||||
except (ConfigError, ApiError, NetworkError) as exc:
|
||||
row["error"] = str(exc)
|
||||
results.append(row)
|
||||
return results
|
||||
|
||||
|
||||
__all__ = [
|
||||
"ATTACH_MIN_REMAIN",
|
||||
"ATTACH_TIMEOUT",
|
||||
"MAX_PAGES",
|
||||
"PAGE_SIZE",
|
||||
"TZ_CN",
|
||||
"WRITE_BATCH",
|
||||
"AiTable",
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"attachment_items",
|
||||
"coerce_for_fields",
|
||||
"flatten",
|
||||
"ms_to_str",
|
||||
"norm",
|
||||
"parse_expires",
|
||||
"resolve_base",
|
||||
"safe_filename",
|
||||
"sniff_kind",
|
||||
"to_base_id",
|
||||
"to_ms",
|
||||
"unique_path",
|
||||
]
|
||||
|
||||
@@ -18,6 +18,10 @@ class ConfigError(DingTalkError):
|
||||
"""配置缺失/非法(缺少 app key、webhook 未配置、dws 未安装等)。"""
|
||||
|
||||
|
||||
class AttachmentExpiredError(ConfigError):
|
||||
"""预签名附件地址已过期或被拒(403):需重新拉记录换新地址,重试同一地址无用。"""
|
||||
|
||||
|
||||
class NetworkError(DingTalkError):
|
||||
"""网络层失败(超时、连接中断、5xx),重试后仍失败才抛出。"""
|
||||
|
||||
@@ -56,6 +60,7 @@ class CancelledError(DingTalkError):
|
||||
|
||||
__all__ = [
|
||||
"ApiError",
|
||||
"AttachmentExpiredError",
|
||||
"AuthError",
|
||||
"CancelledError",
|
||||
"ConfigError",
|
||||
|
||||
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "dingtalk_sdk"
|
||||
version = "0.1.2"
|
||||
version = "0.1.3"
|
||||
description = "钉钉能力 SDK:群机器人推送 / 应用鉴权 / 媒体上传 / 单聊群聊推送(dws)/ AI 表格读写与月报周报采集"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.9"
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "dingtalk_sdk",
|
||||
"name": "钉钉 SDK",
|
||||
"version": "0.1.2",
|
||||
"version": "0.1.3",
|
||||
"description": "钉钉能力集合:群机器人推送(加签/Markdown/状态色/分批/块格式/多环境)、企业内部应用鉴权(v1 + oapi)、媒体库上传、dws 单聊/群聊推送(文本/文件/@/限流/推送记录)、AI 表格读写与月报周报采集",
|
||||
"provides": [
|
||||
"dingtalk_sdk"
|
||||
|
||||
Reference in New Issue
Block a user