zc-center-sdk-python 1.0.0__tar.gz
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.
- zc_center_sdk_python-1.0.0/LICENSE +201 -0
- zc_center_sdk_python-1.0.0/PKG-INFO +147 -0
- zc_center_sdk_python-1.0.0/README.md +110 -0
- zc_center_sdk_python-1.0.0/pyproject.toml +74 -0
- zc_center_sdk_python-1.0.0/setup.cfg +4 -0
- zc_center_sdk_python-1.0.0/src/zc_center/__init__.py +24 -0
- zc_center_sdk_python-1.0.0/src/zc_center/api/__init__.py +5 -0
- zc_center_sdk_python-1.0.0/src/zc_center/api/abstract.py +16 -0
- zc_center_sdk_python-1.0.0/src/zc_center/api/exam_notice.py +17 -0
- zc_center_sdk_python-1.0.0/src/zc_center/api/ping.py +11 -0
- zc_center_sdk_python-1.0.0/src/zc_center/client.py +231 -0
- zc_center_sdk_python-1.0.0/src/zc_center/crypto.py +152 -0
- zc_center_sdk_python-1.0.0/src/zc_center/exceptions.py +36 -0
- zc_center_sdk_python-1.0.0/src/zc_center/py.typed +1 -0
- zc_center_sdk_python-1.0.0/src/zc_center/response.py +35 -0
- zc_center_sdk_python-1.0.0/src/zc_center_sdk_python.egg-info/PKG-INFO +147 -0
- zc_center_sdk_python-1.0.0/src/zc_center_sdk_python.egg-info/SOURCES.txt +19 -0
- zc_center_sdk_python-1.0.0/src/zc_center_sdk_python.egg-info/dependency_links.txt +1 -0
- zc_center_sdk_python-1.0.0/src/zc_center_sdk_python.egg-info/requires.txt +7 -0
- zc_center_sdk_python-1.0.0/src/zc_center_sdk_python.egg-info/top_level.txt +1 -0
- zc_center_sdk_python-1.0.0/tests/test_crypto.py +50 -0
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2026 liujunlin
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: zc-center-sdk-python
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: ZC Center SAPI Python SDK (HMAC-SHA256, AES-256-GCM, exam notice push)
|
|
5
|
+
Author-email: liujunlin <ljl763606865@gmail.com>
|
|
6
|
+
Maintainer-email: liujunlin <ljl763606865@gmail.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: Homepage, https://github.com/763606865/zc-center-sdk-python
|
|
9
|
+
Project-URL: Documentation, https://github.com/763606865/zc-center-sdk-python#readme
|
|
10
|
+
Project-URL: Repository, https://github.com/763606865/zc-center-sdk-python
|
|
11
|
+
Project-URL: Issues, https://github.com/763606865/zc-center-sdk-python/issues
|
|
12
|
+
Project-URL: Changelog, https://github.com/763606865/zc-center-sdk-python/releases
|
|
13
|
+
Keywords: zc-center,sapi,sdk,hmac,aes-gcm,exam-notice,flask
|
|
14
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
25
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Requires-Python: >=3.10
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Requires-Dist: requests>=2.31.0
|
|
31
|
+
Requires-Dist: cryptography>=42.0.0
|
|
32
|
+
Provides-Extra: dev
|
|
33
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
34
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
35
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
|
|
38
|
+
# ZC Center Python SDK
|
|
39
|
+
|
|
40
|
+
适用于 Python 3.10+ 的中台 SAPI 服务端 SDK,提供 HMAC-SHA256 请求签名、AES-256-GCM 加解密、响应验签,以及招考公告推送封装。
|
|
41
|
+
|
|
42
|
+
协议与中台 [`docs/sapi/`](../../docs/sapi/README.md)、ThinkPHP / Spring Boot SDK 保持一致。许可证:Apache-2.0。
|
|
43
|
+
|
|
44
|
+
`app_secret` 只能保存在爬虫/服务端,禁止写入前端或客户端。
|
|
45
|
+
|
|
46
|
+
## 安装
|
|
47
|
+
|
|
48
|
+
PyPI(发布后):
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install zc-center-sdk
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
源码开发(推荐虚拟环境,避免 macOS `externally-managed-environment`):
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
cd sdk/python
|
|
58
|
+
python3 -m venv .venv
|
|
59
|
+
source .venv/bin/activate
|
|
60
|
+
python -m pip install -U pip
|
|
61
|
+
python -m pip install -e ".[dev]"
|
|
62
|
+
pytest -q
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
发布到 PyPI 的完整步骤见 [PUBLISH.md](./PUBLISH.md)。
|
|
66
|
+
|
|
67
|
+
## 配置
|
|
68
|
+
|
|
69
|
+
| 环境变量 | 说明 |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `ZC_CENTER_BASE_URL` | 中台根地址,如 `https://zc-center.example.com` |
|
|
72
|
+
| `ZC_CENTER_APP_KEY` | 中台应用 `app_key` |
|
|
73
|
+
| `ZC_CENTER_APP_SECRET` | 中台应用 `app_secret` |
|
|
74
|
+
| `ZC_CENTER_ENCRYPTION` | `1`/`0`,须与中台 `SAPI_ENCRYPTION_ENABLED` 一致 |
|
|
75
|
+
|
|
76
|
+
联调可关闭加密;生产必须开启。
|
|
77
|
+
|
|
78
|
+
## 爬虫推荐流程
|
|
79
|
+
|
|
80
|
+
1. 在中台「业务管理 → 应用管理」为爬虫创建生态应用,拿到 `app_key` / `app_secret`,配置 IP 白名单。
|
|
81
|
+
2. 爬虫抓取并组合数据后,**不要依赖中台扫盘读 JSON**;直接调用 `exam_notice.report_batch`。
|
|
82
|
+
3. 每条至少传 `title`、`collect_source`;强烈建议再传稳定幂等键之一:
|
|
83
|
+
- `uuid`(来源系统 UUID v4)
|
|
84
|
+
- 或 `collect_ref`(来源站点内唯一 ID)
|
|
85
|
+
- 或稳定的 `official_url` / `collect_url`
|
|
86
|
+
4. 单次最多 100 条;示例脚本会自动分批。
|
|
87
|
+
|
|
88
|
+
### 代码示例
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from zc_center import Client
|
|
92
|
+
|
|
93
|
+
client = Client(
|
|
94
|
+
base_url="https://zc-center.example.com",
|
|
95
|
+
app_key="...",
|
|
96
|
+
app_secret="...",
|
|
97
|
+
encryption=True,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
client.ping().send("crawler-ready")
|
|
101
|
+
|
|
102
|
+
result = client.exam_notice().report_batch([
|
|
103
|
+
{
|
|
104
|
+
"title": "某市事业单位招聘公告",
|
|
105
|
+
"collect_source": "某市人社局",
|
|
106
|
+
"collect_ref": "src-2026-001",
|
|
107
|
+
"official_url": "https://example.com/notices/1",
|
|
108
|
+
"publish_time": 1788888888,
|
|
109
|
+
"content": "<p>公告正文</p>",
|
|
110
|
+
}
|
|
111
|
+
]).data()
|
|
112
|
+
|
|
113
|
+
print(result["created"], result["exists"], result["failed"])
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Flask 等框架无特殊依赖,在服务端任务里直接 `from zc_center import Client` 即可。
|
|
117
|
+
|
|
118
|
+
### 一键推送 JSON 文件
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
export ZC_CENTER_BASE_URL=https://zc-center.example.com
|
|
122
|
+
export ZC_CENTER_APP_KEY=...
|
|
123
|
+
export ZC_CENTER_APP_SECRET=...
|
|
124
|
+
|
|
125
|
+
python examples/push_exam_notices.py /data/crawler/notices-2026-09-09.json
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
JSON 支持数组,或 `{"items":[...]}` / `{"list":[...]}`。
|
|
129
|
+
|
|
130
|
+
## 字段约定(招考公告)
|
|
131
|
+
|
|
132
|
+
| 字段 | 必填 | 说明 |
|
|
133
|
+
| --- | --- | --- |
|
|
134
|
+
| `title` | 是 | 公告标题 |
|
|
135
|
+
| `collect_source` | 是 | 采集来源站点/单位名 |
|
|
136
|
+
| `uuid` | 推荐 | UUID v4,来源稳定 ID |
|
|
137
|
+
| `collect_ref` | 推荐 | 来源侧业务主键 |
|
|
138
|
+
| `official_url` / `collect_url` | 推荐 | 用于排重 |
|
|
139
|
+
| `code` / `exam_type` / `area_code` | 否 | 业务编码、招考类型、地区码 |
|
|
140
|
+
| `publisher_name` / `summary` / `content` | 否 | 发布单位、摘要、正文 |
|
|
141
|
+
| `publish_time` 等时间字段 | 否 | Unix 秒;也可传可解析时间字符串 |
|
|
142
|
+
|
|
143
|
+
排重优先级见 [`docs/sapi/招考公告.md`](../../docs/sapi/招考公告.md)。
|
|
144
|
+
|
|
145
|
+
## 与「扫盘导入」的关系
|
|
146
|
+
|
|
147
|
+
本 SDK 走推模式:爬虫写完即上报。中台无需再为「几点读哪个目录」建配置表;若仍保留本地 JSON,仅作备份或对账即可。
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
# ZC Center Python SDK
|
|
2
|
+
|
|
3
|
+
适用于 Python 3.10+ 的中台 SAPI 服务端 SDK,提供 HMAC-SHA256 请求签名、AES-256-GCM 加解密、响应验签,以及招考公告推送封装。
|
|
4
|
+
|
|
5
|
+
协议与中台 [`docs/sapi/`](../../docs/sapi/README.md)、ThinkPHP / Spring Boot SDK 保持一致。许可证:Apache-2.0。
|
|
6
|
+
|
|
7
|
+
`app_secret` 只能保存在爬虫/服务端,禁止写入前端或客户端。
|
|
8
|
+
|
|
9
|
+
## 安装
|
|
10
|
+
|
|
11
|
+
PyPI(发布后):
|
|
12
|
+
|
|
13
|
+
```bash
|
|
14
|
+
pip install zc-center-sdk
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
源码开发(推荐虚拟环境,避免 macOS `externally-managed-environment`):
|
|
18
|
+
|
|
19
|
+
```bash
|
|
20
|
+
cd sdk/python
|
|
21
|
+
python3 -m venv .venv
|
|
22
|
+
source .venv/bin/activate
|
|
23
|
+
python -m pip install -U pip
|
|
24
|
+
python -m pip install -e ".[dev]"
|
|
25
|
+
pytest -q
|
|
26
|
+
```
|
|
27
|
+
|
|
28
|
+
发布到 PyPI 的完整步骤见 [PUBLISH.md](./PUBLISH.md)。
|
|
29
|
+
|
|
30
|
+
## 配置
|
|
31
|
+
|
|
32
|
+
| 环境变量 | 说明 |
|
|
33
|
+
| --- | --- |
|
|
34
|
+
| `ZC_CENTER_BASE_URL` | 中台根地址,如 `https://zc-center.example.com` |
|
|
35
|
+
| `ZC_CENTER_APP_KEY` | 中台应用 `app_key` |
|
|
36
|
+
| `ZC_CENTER_APP_SECRET` | 中台应用 `app_secret` |
|
|
37
|
+
| `ZC_CENTER_ENCRYPTION` | `1`/`0`,须与中台 `SAPI_ENCRYPTION_ENABLED` 一致 |
|
|
38
|
+
|
|
39
|
+
联调可关闭加密;生产必须开启。
|
|
40
|
+
|
|
41
|
+
## 爬虫推荐流程
|
|
42
|
+
|
|
43
|
+
1. 在中台「业务管理 → 应用管理」为爬虫创建生态应用,拿到 `app_key` / `app_secret`,配置 IP 白名单。
|
|
44
|
+
2. 爬虫抓取并组合数据后,**不要依赖中台扫盘读 JSON**;直接调用 `exam_notice.report_batch`。
|
|
45
|
+
3. 每条至少传 `title`、`collect_source`;强烈建议再传稳定幂等键之一:
|
|
46
|
+
- `uuid`(来源系统 UUID v4)
|
|
47
|
+
- 或 `collect_ref`(来源站点内唯一 ID)
|
|
48
|
+
- 或稳定的 `official_url` / `collect_url`
|
|
49
|
+
4. 单次最多 100 条;示例脚本会自动分批。
|
|
50
|
+
|
|
51
|
+
### 代码示例
|
|
52
|
+
|
|
53
|
+
```python
|
|
54
|
+
from zc_center import Client
|
|
55
|
+
|
|
56
|
+
client = Client(
|
|
57
|
+
base_url="https://zc-center.example.com",
|
|
58
|
+
app_key="...",
|
|
59
|
+
app_secret="...",
|
|
60
|
+
encryption=True,
|
|
61
|
+
)
|
|
62
|
+
|
|
63
|
+
client.ping().send("crawler-ready")
|
|
64
|
+
|
|
65
|
+
result = client.exam_notice().report_batch([
|
|
66
|
+
{
|
|
67
|
+
"title": "某市事业单位招聘公告",
|
|
68
|
+
"collect_source": "某市人社局",
|
|
69
|
+
"collect_ref": "src-2026-001",
|
|
70
|
+
"official_url": "https://example.com/notices/1",
|
|
71
|
+
"publish_time": 1788888888,
|
|
72
|
+
"content": "<p>公告正文</p>",
|
|
73
|
+
}
|
|
74
|
+
]).data()
|
|
75
|
+
|
|
76
|
+
print(result["created"], result["exists"], result["failed"])
|
|
77
|
+
```
|
|
78
|
+
|
|
79
|
+
Flask 等框架无特殊依赖,在服务端任务里直接 `from zc_center import Client` 即可。
|
|
80
|
+
|
|
81
|
+
### 一键推送 JSON 文件
|
|
82
|
+
|
|
83
|
+
```bash
|
|
84
|
+
export ZC_CENTER_BASE_URL=https://zc-center.example.com
|
|
85
|
+
export ZC_CENTER_APP_KEY=...
|
|
86
|
+
export ZC_CENTER_APP_SECRET=...
|
|
87
|
+
|
|
88
|
+
python examples/push_exam_notices.py /data/crawler/notices-2026-09-09.json
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
JSON 支持数组,或 `{"items":[...]}` / `{"list":[...]}`。
|
|
92
|
+
|
|
93
|
+
## 字段约定(招考公告)
|
|
94
|
+
|
|
95
|
+
| 字段 | 必填 | 说明 |
|
|
96
|
+
| --- | --- | --- |
|
|
97
|
+
| `title` | 是 | 公告标题 |
|
|
98
|
+
| `collect_source` | 是 | 采集来源站点/单位名 |
|
|
99
|
+
| `uuid` | 推荐 | UUID v4,来源稳定 ID |
|
|
100
|
+
| `collect_ref` | 推荐 | 来源侧业务主键 |
|
|
101
|
+
| `official_url` / `collect_url` | 推荐 | 用于排重 |
|
|
102
|
+
| `code` / `exam_type` / `area_code` | 否 | 业务编码、招考类型、地区码 |
|
|
103
|
+
| `publisher_name` / `summary` / `content` | 否 | 发布单位、摘要、正文 |
|
|
104
|
+
| `publish_time` 等时间字段 | 否 | Unix 秒;也可传可解析时间字符串 |
|
|
105
|
+
|
|
106
|
+
排重优先级见 [`docs/sapi/招考公告.md`](../../docs/sapi/招考公告.md)。
|
|
107
|
+
|
|
108
|
+
## 与「扫盘导入」的关系
|
|
109
|
+
|
|
110
|
+
本 SDK 走推模式:爬虫写完即上报。中台无需再为「几点读哪个目录」建配置表;若仍保留本地 JSON,仅作备份或对账即可。
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
[build-system]
|
|
2
|
+
requires = ["setuptools>=68", "wheel"]
|
|
3
|
+
build-backend = "setuptools.build_meta"
|
|
4
|
+
|
|
5
|
+
[project]
|
|
6
|
+
name = "zc-center-sdk-python"
|
|
7
|
+
version = "1.0.0"
|
|
8
|
+
description = "ZC Center SAPI Python SDK (HMAC-SHA256, AES-256-GCM, exam notice push)"
|
|
9
|
+
readme = "README.md"
|
|
10
|
+
requires-python = ">=3.10"
|
|
11
|
+
license = "Apache-2.0"
|
|
12
|
+
license-files = ["LICENSE"]
|
|
13
|
+
authors = [
|
|
14
|
+
{ name = "liujunlin", email = "ljl763606865@gmail.com" },
|
|
15
|
+
]
|
|
16
|
+
maintainers = [
|
|
17
|
+
{ name = "liujunlin", email = "ljl763606865@gmail.com" },
|
|
18
|
+
]
|
|
19
|
+
keywords = [
|
|
20
|
+
"zc-center",
|
|
21
|
+
"sapi",
|
|
22
|
+
"sdk",
|
|
23
|
+
"hmac",
|
|
24
|
+
"aes-gcm",
|
|
25
|
+
"exam-notice",
|
|
26
|
+
"flask",
|
|
27
|
+
]
|
|
28
|
+
classifiers = [
|
|
29
|
+
"Development Status :: 5 - Production/Stable",
|
|
30
|
+
"Intended Audience :: Developers",
|
|
31
|
+
"Operating System :: OS Independent",
|
|
32
|
+
"Programming Language :: Python",
|
|
33
|
+
"Programming Language :: Python :: 3",
|
|
34
|
+
"Programming Language :: Python :: 3 :: Only",
|
|
35
|
+
"Programming Language :: Python :: 3.10",
|
|
36
|
+
"Programming Language :: Python :: 3.11",
|
|
37
|
+
"Programming Language :: Python :: 3.12",
|
|
38
|
+
"Programming Language :: Python :: 3.13",
|
|
39
|
+
"Topic :: Internet :: WWW/HTTP",
|
|
40
|
+
"Topic :: Software Development :: Libraries :: Python Modules",
|
|
41
|
+
"Typing :: Typed",
|
|
42
|
+
]
|
|
43
|
+
dependencies = [
|
|
44
|
+
"requests>=2.31.0",
|
|
45
|
+
"cryptography>=42.0.0",
|
|
46
|
+
]
|
|
47
|
+
|
|
48
|
+
[project.optional-dependencies]
|
|
49
|
+
dev = [
|
|
50
|
+
"pytest>=7.0",
|
|
51
|
+
"build>=1.2",
|
|
52
|
+
"twine>=5.0",
|
|
53
|
+
]
|
|
54
|
+
|
|
55
|
+
[project.urls]
|
|
56
|
+
Homepage = "https://github.com/763606865/zc-center-sdk-python"
|
|
57
|
+
Documentation = "https://github.com/763606865/zc-center-sdk-python#readme"
|
|
58
|
+
Repository = "https://github.com/763606865/zc-center-sdk-python"
|
|
59
|
+
Issues = "https://github.com/763606865/zc-center-sdk-python/issues"
|
|
60
|
+
Changelog = "https://github.com/763606865/zc-center-sdk-python/releases"
|
|
61
|
+
|
|
62
|
+
[tool.setuptools]
|
|
63
|
+
include-package-data = true
|
|
64
|
+
|
|
65
|
+
[tool.setuptools.packages.find]
|
|
66
|
+
where = ["src"]
|
|
67
|
+
include = ["zc_center*"]
|
|
68
|
+
|
|
69
|
+
[tool.setuptools.package-data]
|
|
70
|
+
zc_center = ["py.typed"]
|
|
71
|
+
|
|
72
|
+
[tool.pytest.ini_options]
|
|
73
|
+
testpaths = ["tests"]
|
|
74
|
+
pythonpath = ["src"]
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from .client import Client
|
|
4
|
+
from .exceptions import (
|
|
5
|
+
ApiException,
|
|
6
|
+
CryptoException,
|
|
7
|
+
SapiException,
|
|
8
|
+
SignatureException,
|
|
9
|
+
TransportException,
|
|
10
|
+
)
|
|
11
|
+
from .response import Response
|
|
12
|
+
|
|
13
|
+
__version__ = "1.0.0"
|
|
14
|
+
|
|
15
|
+
__all__ = [
|
|
16
|
+
"Client",
|
|
17
|
+
"Response",
|
|
18
|
+
"SapiException",
|
|
19
|
+
"ApiException",
|
|
20
|
+
"CryptoException",
|
|
21
|
+
"SignatureException",
|
|
22
|
+
"TransportException",
|
|
23
|
+
"__version__",
|
|
24
|
+
]
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import TYPE_CHECKING, Any, Mapping
|
|
4
|
+
|
|
5
|
+
from ..response import Response
|
|
6
|
+
|
|
7
|
+
if TYPE_CHECKING:
|
|
8
|
+
from ..client import Client
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
class AbstractApi:
|
|
12
|
+
def __init__(self, client: Client) -> None:
|
|
13
|
+
self._client = client
|
|
14
|
+
|
|
15
|
+
def post(self, path: str, payload: Mapping[str, Any] | None = None) -> Response:
|
|
16
|
+
return self._client.post(path, payload or {})
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Mapping, Sequence
|
|
4
|
+
|
|
5
|
+
from ..response import Response
|
|
6
|
+
from .abstract import AbstractApi
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class ExamNoticeApi(AbstractApi):
|
|
10
|
+
def list(self, params: Mapping[str, Any] | None = None) -> Response:
|
|
11
|
+
return self.post("/sapi/exam-notice/list", dict(params or {}))
|
|
12
|
+
|
|
13
|
+
def report(self, notice: Mapping[str, Any]) -> Response:
|
|
14
|
+
return self.post("/sapi/exam-notice/report", dict(notice))
|
|
15
|
+
|
|
16
|
+
def report_batch(self, items: Sequence[Mapping[str, Any]]) -> Response:
|
|
17
|
+
return self.post("/sapi/exam-notice/report-batch", {"items": list(items)})
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Mapping
|
|
4
|
+
|
|
5
|
+
from ..response import Response
|
|
6
|
+
from .abstract import AbstractApi
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
class PingApi(AbstractApi):
|
|
10
|
+
def send(self, echo: str = "ping") -> Response:
|
|
11
|
+
return self.post("/sapi/ping", {"echo": echo})
|
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import json
|
|
4
|
+
import logging
|
|
5
|
+
import time
|
|
6
|
+
from typing import Any, Callable, Mapping
|
|
7
|
+
from urllib.parse import urlparse
|
|
8
|
+
|
|
9
|
+
import requests
|
|
10
|
+
|
|
11
|
+
from .api.exam_notice import ExamNoticeApi
|
|
12
|
+
from .api.ping import PingApi
|
|
13
|
+
from .crypto import Crypto
|
|
14
|
+
from .exceptions import (
|
|
15
|
+
ApiException,
|
|
16
|
+
CryptoException,
|
|
17
|
+
SapiException,
|
|
18
|
+
SignatureException,
|
|
19
|
+
TransportException,
|
|
20
|
+
)
|
|
21
|
+
from .response import Response
|
|
22
|
+
|
|
23
|
+
Logger = Callable[[str, Mapping[str, Any]], None]
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
class Client:
|
|
27
|
+
"""ZC Center SAPI 客户端:签名、加解密、验签与业务入口。"""
|
|
28
|
+
|
|
29
|
+
def __init__(
|
|
30
|
+
self,
|
|
31
|
+
*,
|
|
32
|
+
base_url: str,
|
|
33
|
+
app_key: str,
|
|
34
|
+
app_secret: str,
|
|
35
|
+
encryption: bool = True,
|
|
36
|
+
timeout: float = 10.0,
|
|
37
|
+
connect_timeout: float = 3.0,
|
|
38
|
+
verify_ssl: bool = True,
|
|
39
|
+
debug: bool = False,
|
|
40
|
+
logger: Logger | None = None,
|
|
41
|
+
session: requests.Session | None = None,
|
|
42
|
+
crypto: Crypto | None = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
self.base_url = base_url.rstrip("/")
|
|
45
|
+
self.app_key = app_key.strip()
|
|
46
|
+
self.app_secret = app_secret
|
|
47
|
+
self.encryption = encryption
|
|
48
|
+
self.timeout = (connect_timeout, timeout)
|
|
49
|
+
self.verify_ssl = verify_ssl
|
|
50
|
+
self.debug = debug
|
|
51
|
+
self._logger = logger
|
|
52
|
+
self._session = session or requests.Session()
|
|
53
|
+
self._crypto = crypto or Crypto()
|
|
54
|
+
self._apis: dict[type[Any], Any] = {}
|
|
55
|
+
|
|
56
|
+
parsed = urlparse(self.base_url)
|
|
57
|
+
if parsed.scheme not in {"http", "https"} or not parsed.netloc:
|
|
58
|
+
raise SapiException("ZC Center SDK的base_url配置无效")
|
|
59
|
+
if not self.app_key or not self.app_secret:
|
|
60
|
+
raise SapiException("ZC Center SDK的app_key或app_secret未配置")
|
|
61
|
+
|
|
62
|
+
def ping(self) -> PingApi:
|
|
63
|
+
return self._api(PingApi)
|
|
64
|
+
|
|
65
|
+
def exam_notice(self) -> ExamNoticeApi:
|
|
66
|
+
return self._api(ExamNoticeApi)
|
|
67
|
+
|
|
68
|
+
def get(self, path: str, query: Mapping[str, Any] | None = None) -> Response:
|
|
69
|
+
return self.request("GET", path, {}, query or {})
|
|
70
|
+
|
|
71
|
+
def post(
|
|
72
|
+
self,
|
|
73
|
+
path: str,
|
|
74
|
+
payload: Mapping[str, Any] | None = None,
|
|
75
|
+
query: Mapping[str, Any] | None = None,
|
|
76
|
+
) -> Response:
|
|
77
|
+
return self.request("POST", path, payload or {}, query or {})
|
|
78
|
+
|
|
79
|
+
def request(
|
|
80
|
+
self,
|
|
81
|
+
method: str,
|
|
82
|
+
path: str,
|
|
83
|
+
payload: Mapping[str, Any] | None = None,
|
|
84
|
+
query: Mapping[str, Any] | None = None,
|
|
85
|
+
) -> Response:
|
|
86
|
+
path = "/" + path.lstrip("/")
|
|
87
|
+
if not path.startswith("/sapi/"):
|
|
88
|
+
raise SapiException("SAPI请求路径必须以/sapi/开头")
|
|
89
|
+
|
|
90
|
+
payload = dict(payload or {})
|
|
91
|
+
query = dict(query or {})
|
|
92
|
+
timestamp = str(int(time.time()))
|
|
93
|
+
nonce = self._crypto.nonce()
|
|
94
|
+
aad = self._crypto.aad(self.app_key, timestamp, nonce)
|
|
95
|
+
|
|
96
|
+
try:
|
|
97
|
+
body_obj: Mapping[str, Any] = (
|
|
98
|
+
self._crypto.encrypt(payload, self.app_secret, aad) if self.encryption else payload
|
|
99
|
+
)
|
|
100
|
+
body = self._crypto.json_encode(body_obj)
|
|
101
|
+
except (CryptoException, TypeError, ValueError) as exc:
|
|
102
|
+
raise SapiException("SAPI请求JSON编码或加密失败") from exc
|
|
103
|
+
|
|
104
|
+
canonical = self._crypto.canonical_request(method, path, query, timestamp, nonce, body)
|
|
105
|
+
headers = {
|
|
106
|
+
"Accept": "application/json",
|
|
107
|
+
"Content-Type": "application/json",
|
|
108
|
+
"X-App-Key": self.app_key,
|
|
109
|
+
"X-Timestamp": timestamp,
|
|
110
|
+
"X-Nonce": nonce,
|
|
111
|
+
"X-Signature": self._crypto.sign(canonical, self.app_secret),
|
|
112
|
+
"X-Encrypted": "1" if self.encryption else "0",
|
|
113
|
+
}
|
|
114
|
+
url = self.base_url + path
|
|
115
|
+
|
|
116
|
+
self._log(
|
|
117
|
+
"SAPI request",
|
|
118
|
+
{
|
|
119
|
+
"method": method.upper(),
|
|
120
|
+
"url": url,
|
|
121
|
+
"query": query,
|
|
122
|
+
"request_headers": headers,
|
|
123
|
+
"request_params": payload,
|
|
124
|
+
},
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
try:
|
|
128
|
+
http_response = self._session.request(
|
|
129
|
+
method=method.upper(),
|
|
130
|
+
url=url,
|
|
131
|
+
params=query or None,
|
|
132
|
+
data=body.encode("utf-8"),
|
|
133
|
+
headers=headers,
|
|
134
|
+
timeout=self.timeout,
|
|
135
|
+
verify=self.verify_ssl,
|
|
136
|
+
)
|
|
137
|
+
except requests.RequestException as exc:
|
|
138
|
+
self._log(
|
|
139
|
+
"SAPI request transport error",
|
|
140
|
+
{"method": method.upper(), "url": url, "error": str(exc)},
|
|
141
|
+
)
|
|
142
|
+
raise TransportException(f"SAPI网络请求失败:{exc}") from exc
|
|
143
|
+
|
|
144
|
+
return self._parse_response(http_response, timestamp, nonce, aad)
|
|
145
|
+
|
|
146
|
+
def _parse_response(
|
|
147
|
+
self,
|
|
148
|
+
response: requests.Response,
|
|
149
|
+
timestamp: str,
|
|
150
|
+
nonce: str,
|
|
151
|
+
aad: str,
|
|
152
|
+
) -> Response:
|
|
153
|
+
raw_body = response.text
|
|
154
|
+
status_code = response.status_code
|
|
155
|
+
response_headers = {k: v for k, v in response.headers.items()}
|
|
156
|
+
signature = (response.headers.get("X-Response-Signature") or "").strip()
|
|
157
|
+
encrypted = (response.headers.get("X-Encrypted") or "") == "1"
|
|
158
|
+
|
|
159
|
+
self._log(
|
|
160
|
+
"SAPI response",
|
|
161
|
+
{
|
|
162
|
+
"http_status": status_code,
|
|
163
|
+
"response_headers": response_headers,
|
|
164
|
+
},
|
|
165
|
+
)
|
|
166
|
+
|
|
167
|
+
try:
|
|
168
|
+
decoded = json.loads(raw_body) if raw_body else None
|
|
169
|
+
except json.JSONDecodeError as exc:
|
|
170
|
+
raise TransportException("SAPI响应不是有效JSON") from exc
|
|
171
|
+
if not isinstance(decoded, dict):
|
|
172
|
+
raise TransportException("SAPI响应必须是JSON对象")
|
|
173
|
+
|
|
174
|
+
if signature == "":
|
|
175
|
+
if status_code >= 400:
|
|
176
|
+
raise self._api_exception(decoded, status_code, False)
|
|
177
|
+
raise SignatureException("SAPI响应缺少X-Response-Signature")
|
|
178
|
+
|
|
179
|
+
if encrypted:
|
|
180
|
+
if not self._crypto.verify_encrypted_response(
|
|
181
|
+
decoded, signature, timestamp, nonce, self.app_secret
|
|
182
|
+
):
|
|
183
|
+
raise SignatureException("SAPI加密响应签名验证失败")
|
|
184
|
+
try:
|
|
185
|
+
payload = self._crypto.decrypt(decoded, self.app_secret, aad)
|
|
186
|
+
except CryptoException as exc:
|
|
187
|
+
raise SapiException("SAPI响应解密失败") from exc
|
|
188
|
+
else:
|
|
189
|
+
if not self._crypto.verify_plaintext_response(
|
|
190
|
+
raw_body, signature, timestamp, nonce, self.app_secret
|
|
191
|
+
):
|
|
192
|
+
raise SignatureException("SAPI明文响应签名验证失败")
|
|
193
|
+
payload = decoded
|
|
194
|
+
|
|
195
|
+
self._log(
|
|
196
|
+
"SAPI response payload",
|
|
197
|
+
{"http_status": status_code, "response_payload": payload},
|
|
198
|
+
)
|
|
199
|
+
|
|
200
|
+
if status_code >= 400 or int(payload.get("code") or 0) != 0:
|
|
201
|
+
raise self._api_exception(payload, status_code, True)
|
|
202
|
+
|
|
203
|
+
return Response(status_code, payload, response_headers, raw_body)
|
|
204
|
+
|
|
205
|
+
def _api_exception(
|
|
206
|
+
self,
|
|
207
|
+
payload: Mapping[str, Any],
|
|
208
|
+
http_status: int,
|
|
209
|
+
signature_verified: bool,
|
|
210
|
+
) -> ApiException:
|
|
211
|
+
data = payload.get("data")
|
|
212
|
+
return ApiException(
|
|
213
|
+
str(payload.get("msg") or "SAPI接口调用失败"),
|
|
214
|
+
code=int(payload.get("code") or 0),
|
|
215
|
+
http_status=http_status,
|
|
216
|
+
data=data if isinstance(data, (dict, list)) else None,
|
|
217
|
+
signature_verified=signature_verified,
|
|
218
|
+
)
|
|
219
|
+
|
|
220
|
+
def _api(self, api_cls: type[Any]) -> Any:
|
|
221
|
+
if api_cls not in self._apis:
|
|
222
|
+
self._apis[api_cls] = api_cls(self)
|
|
223
|
+
return self._apis[api_cls]
|
|
224
|
+
|
|
225
|
+
def _log(self, message: str, context: Mapping[str, Any]) -> None:
|
|
226
|
+
if not self.debug:
|
|
227
|
+
return
|
|
228
|
+
if self._logger is not None:
|
|
229
|
+
self._logger(message, context)
|
|
230
|
+
return
|
|
231
|
+
logging.getLogger("zc_center").info("%s %s", message, json.dumps(context, ensure_ascii=False))
|
|
@@ -0,0 +1,152 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
import base64
|
|
4
|
+
import hashlib
|
|
5
|
+
import hmac
|
|
6
|
+
import json
|
|
7
|
+
import secrets
|
|
8
|
+
from typing import Any, Mapping
|
|
9
|
+
from urllib.parse import quote
|
|
10
|
+
|
|
11
|
+
from .exceptions import CryptoException
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
class Crypto:
|
|
15
|
+
"""与 ThinkPHP / Spring Boot SDK 对齐的签名与 AES-GCM 工具。"""
|
|
16
|
+
|
|
17
|
+
def encrypt(self, payload: Mapping[str, Any], app_secret: str, aad: str) -> dict[str, str]:
|
|
18
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
19
|
+
|
|
20
|
+
plaintext = self.json_encode(payload).encode("utf-8")
|
|
21
|
+
iv = secrets.token_bytes(12)
|
|
22
|
+
aesgcm = AESGCM(self._key(app_secret))
|
|
23
|
+
sealed = aesgcm.encrypt(iv, plaintext, aad.encode("utf-8"))
|
|
24
|
+
ciphertext, tag = sealed[:-16], sealed[-16:]
|
|
25
|
+
return {
|
|
26
|
+
"algorithm": "AES-256-GCM",
|
|
27
|
+
"ciphertext": base64.b64encode(ciphertext).decode("ascii"),
|
|
28
|
+
"iv": base64.b64encode(iv).decode("ascii"),
|
|
29
|
+
"tag": base64.b64encode(tag).decode("ascii"),
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
def decrypt(self, envelope: Mapping[str, Any], app_secret: str, aad: str) -> dict[str, Any]:
|
|
33
|
+
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
|
34
|
+
|
|
35
|
+
for field in ("ciphertext", "iv", "tag"):
|
|
36
|
+
value = envelope.get(field)
|
|
37
|
+
if not isinstance(value, str) or value == "":
|
|
38
|
+
raise CryptoException(f"SAPI加密响应缺少字段:{field}")
|
|
39
|
+
|
|
40
|
+
try:
|
|
41
|
+
ciphertext = base64.b64decode(envelope["ciphertext"], validate=True)
|
|
42
|
+
iv = base64.b64decode(envelope["iv"], validate=True)
|
|
43
|
+
tag = base64.b64decode(envelope["tag"], validate=True)
|
|
44
|
+
except Exception as exc: # noqa: BLE001
|
|
45
|
+
raise CryptoException("SAPI加密响应格式错误") from exc
|
|
46
|
+
|
|
47
|
+
if len(iv) != 12 or len(tag) != 16:
|
|
48
|
+
raise CryptoException("SAPI加密响应格式错误")
|
|
49
|
+
|
|
50
|
+
aesgcm = AESGCM(self._key(app_secret))
|
|
51
|
+
try:
|
|
52
|
+
plaintext = aesgcm.decrypt(iv, ciphertext + tag, aad.encode("utf-8"))
|
|
53
|
+
except Exception as exc: # noqa: BLE001
|
|
54
|
+
raise CryptoException("SAPI响应解密或完整性验证失败") from exc
|
|
55
|
+
|
|
56
|
+
try:
|
|
57
|
+
payload = json.loads(plaintext.decode("utf-8"))
|
|
58
|
+
except json.JSONDecodeError as exc:
|
|
59
|
+
raise CryptoException("SAPI解密响应不是JSON对象") from exc
|
|
60
|
+
if not isinstance(payload, dict):
|
|
61
|
+
raise CryptoException("SAPI解密响应不是JSON对象")
|
|
62
|
+
return payload
|
|
63
|
+
|
|
64
|
+
def canonical_request(
|
|
65
|
+
self,
|
|
66
|
+
method: str,
|
|
67
|
+
path: str,
|
|
68
|
+
query: Mapping[str, Any],
|
|
69
|
+
timestamp: str,
|
|
70
|
+
nonce: str,
|
|
71
|
+
raw_body: str,
|
|
72
|
+
) -> str:
|
|
73
|
+
normalized_path = "/" + path.lstrip("/")
|
|
74
|
+
canonical_query = self._canonical_query(query)
|
|
75
|
+
return "\n".join(
|
|
76
|
+
[
|
|
77
|
+
method.upper(),
|
|
78
|
+
normalized_path,
|
|
79
|
+
canonical_query,
|
|
80
|
+
timestamp,
|
|
81
|
+
nonce,
|
|
82
|
+
self.sha256_hex(raw_body),
|
|
83
|
+
]
|
|
84
|
+
)
|
|
85
|
+
|
|
86
|
+
def sign(self, canonical: str, app_secret: str) -> str:
|
|
87
|
+
return hmac.new(app_secret.encode("utf-8"), canonical.encode("utf-8"), hashlib.sha256).hexdigest()
|
|
88
|
+
|
|
89
|
+
def aad(self, app_key: str, timestamp: str, nonce: str) -> str:
|
|
90
|
+
return "\n".join([app_key, timestamp, nonce])
|
|
91
|
+
|
|
92
|
+
def verify_encrypted_response(
|
|
93
|
+
self,
|
|
94
|
+
envelope: Mapping[str, Any],
|
|
95
|
+
signature: str,
|
|
96
|
+
timestamp: str,
|
|
97
|
+
nonce: str,
|
|
98
|
+
app_secret: str,
|
|
99
|
+
) -> bool:
|
|
100
|
+
for field in ("iv", "tag", "ciphertext"):
|
|
101
|
+
if not isinstance(envelope.get(field), str):
|
|
102
|
+
return False
|
|
103
|
+
canonical = "\n".join(
|
|
104
|
+
[
|
|
105
|
+
timestamp,
|
|
106
|
+
nonce,
|
|
107
|
+
str(envelope["iv"]),
|
|
108
|
+
str(envelope["tag"]),
|
|
109
|
+
str(envelope["ciphertext"]),
|
|
110
|
+
]
|
|
111
|
+
)
|
|
112
|
+
expected = self.sign(canonical, app_secret)
|
|
113
|
+
return signature != "" and hmac.compare_digest(expected, signature.lower())
|
|
114
|
+
|
|
115
|
+
def verify_plaintext_response(
|
|
116
|
+
self,
|
|
117
|
+
raw_body: str,
|
|
118
|
+
signature: str,
|
|
119
|
+
timestamp: str,
|
|
120
|
+
nonce: str,
|
|
121
|
+
app_secret: str,
|
|
122
|
+
) -> bool:
|
|
123
|
+
canonical = "\n".join([timestamp, nonce, self.sha256_hex(raw_body)])
|
|
124
|
+
expected = self.sign(canonical, app_secret)
|
|
125
|
+
return signature != "" and hmac.compare_digest(expected, signature.lower())
|
|
126
|
+
|
|
127
|
+
def json_encode(self, payload: Mapping[str, Any] | list[Any]) -> str:
|
|
128
|
+
return json.dumps(payload, ensure_ascii=False, separators=(",", ":"), allow_nan=False)
|
|
129
|
+
|
|
130
|
+
def nonce(self) -> str:
|
|
131
|
+
# 与 PHP rtrim(strtr(base64_encode(random_bytes(18)), '+/', '-_'), '=') 等价
|
|
132
|
+
raw = base64.b64encode(secrets.token_bytes(18)).decode("ascii")
|
|
133
|
+
return raw.translate(str.maketrans("+/", "-_")).rstrip("=")
|
|
134
|
+
|
|
135
|
+
def sha256_hex(self, value: str) -> str:
|
|
136
|
+
return hashlib.sha256(value.encode("utf-8")).hexdigest()
|
|
137
|
+
|
|
138
|
+
def _key(self, app_secret: str) -> bytes:
|
|
139
|
+
return hashlib.sha256(app_secret.encode("utf-8")).digest()
|
|
140
|
+
|
|
141
|
+
def _canonical_query(self, query: Mapping[str, Any]) -> str:
|
|
142
|
+
if not query:
|
|
143
|
+
return ""
|
|
144
|
+
parts: list[str] = []
|
|
145
|
+
for key in sorted(query.keys()):
|
|
146
|
+
value = query[key]
|
|
147
|
+
if value is None:
|
|
148
|
+
continue
|
|
149
|
+
encoded_key = quote(str(key), safe="-_.~")
|
|
150
|
+
encoded_value = quote(str(value), safe="-_.~")
|
|
151
|
+
parts.append(f"{encoded_key}={encoded_value}")
|
|
152
|
+
return "&".join(parts)
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
class SapiException(Exception):
|
|
5
|
+
"""SDK / 协议层异常基类。"""
|
|
6
|
+
|
|
7
|
+
|
|
8
|
+
class CryptoException(SapiException):
|
|
9
|
+
"""加解密失败。"""
|
|
10
|
+
|
|
11
|
+
|
|
12
|
+
class SignatureException(SapiException):
|
|
13
|
+
"""请求或响应签名校验失败。"""
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
class TransportException(SapiException):
|
|
17
|
+
"""网络或响应格式错误。"""
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
class ApiException(SapiException):
|
|
21
|
+
"""业务接口返回非成功。"""
|
|
22
|
+
|
|
23
|
+
def __init__(
|
|
24
|
+
self,
|
|
25
|
+
message: str,
|
|
26
|
+
*,
|
|
27
|
+
code: int = 0,
|
|
28
|
+
http_status: int = 0,
|
|
29
|
+
data: object | None = None,
|
|
30
|
+
signature_verified: bool = False,
|
|
31
|
+
) -> None:
|
|
32
|
+
super().__init__(message)
|
|
33
|
+
self.code = code
|
|
34
|
+
self.http_status = http_status
|
|
35
|
+
self.data = data
|
|
36
|
+
self.signature_verified = signature_verified
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
# marker for PEP 561 typed package
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from typing import Any, Mapping
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
class Response:
|
|
7
|
+
def __init__(
|
|
8
|
+
self,
|
|
9
|
+
status_code: int,
|
|
10
|
+
payload: Mapping[str, Any],
|
|
11
|
+
headers: Mapping[str, str],
|
|
12
|
+
raw_body: str,
|
|
13
|
+
) -> None:
|
|
14
|
+
self._status_code = status_code
|
|
15
|
+
self._payload = dict(payload)
|
|
16
|
+
self._headers = dict(headers)
|
|
17
|
+
self._raw_body = raw_body
|
|
18
|
+
|
|
19
|
+
def status_code(self) -> int:
|
|
20
|
+
return self._status_code
|
|
21
|
+
|
|
22
|
+
def payload(self) -> dict[str, Any]:
|
|
23
|
+
return self._payload
|
|
24
|
+
|
|
25
|
+
def data(self) -> Any:
|
|
26
|
+
return self._payload.get("data")
|
|
27
|
+
|
|
28
|
+
def message(self) -> str:
|
|
29
|
+
return str(self._payload.get("msg") or "")
|
|
30
|
+
|
|
31
|
+
def headers(self) -> dict[str, str]:
|
|
32
|
+
return self._headers
|
|
33
|
+
|
|
34
|
+
def raw_body(self) -> str:
|
|
35
|
+
return self._raw_body
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: zc-center-sdk-python
|
|
3
|
+
Version: 1.0.0
|
|
4
|
+
Summary: ZC Center SAPI Python SDK (HMAC-SHA256, AES-256-GCM, exam notice push)
|
|
5
|
+
Author-email: liujunlin <ljl763606865@gmail.com>
|
|
6
|
+
Maintainer-email: liujunlin <ljl763606865@gmail.com>
|
|
7
|
+
License-Expression: Apache-2.0
|
|
8
|
+
Project-URL: Homepage, https://github.com/763606865/zc-center-sdk-python
|
|
9
|
+
Project-URL: Documentation, https://github.com/763606865/zc-center-sdk-python#readme
|
|
10
|
+
Project-URL: Repository, https://github.com/763606865/zc-center-sdk-python
|
|
11
|
+
Project-URL: Issues, https://github.com/763606865/zc-center-sdk-python/issues
|
|
12
|
+
Project-URL: Changelog, https://github.com/763606865/zc-center-sdk-python/releases
|
|
13
|
+
Keywords: zc-center,sapi,sdk,hmac,aes-gcm,exam-notice,flask
|
|
14
|
+
Classifier: Development Status :: 5 - Production/Stable
|
|
15
|
+
Classifier: Intended Audience :: Developers
|
|
16
|
+
Classifier: Operating System :: OS Independent
|
|
17
|
+
Classifier: Programming Language :: Python
|
|
18
|
+
Classifier: Programming Language :: Python :: 3
|
|
19
|
+
Classifier: Programming Language :: Python :: 3 :: Only
|
|
20
|
+
Classifier: Programming Language :: Python :: 3.10
|
|
21
|
+
Classifier: Programming Language :: Python :: 3.11
|
|
22
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
23
|
+
Classifier: Programming Language :: Python :: 3.13
|
|
24
|
+
Classifier: Topic :: Internet :: WWW/HTTP
|
|
25
|
+
Classifier: Topic :: Software Development :: Libraries :: Python Modules
|
|
26
|
+
Classifier: Typing :: Typed
|
|
27
|
+
Requires-Python: >=3.10
|
|
28
|
+
Description-Content-Type: text/markdown
|
|
29
|
+
License-File: LICENSE
|
|
30
|
+
Requires-Dist: requests>=2.31.0
|
|
31
|
+
Requires-Dist: cryptography>=42.0.0
|
|
32
|
+
Provides-Extra: dev
|
|
33
|
+
Requires-Dist: pytest>=7.0; extra == "dev"
|
|
34
|
+
Requires-Dist: build>=1.2; extra == "dev"
|
|
35
|
+
Requires-Dist: twine>=5.0; extra == "dev"
|
|
36
|
+
Dynamic: license-file
|
|
37
|
+
|
|
38
|
+
# ZC Center Python SDK
|
|
39
|
+
|
|
40
|
+
适用于 Python 3.10+ 的中台 SAPI 服务端 SDK,提供 HMAC-SHA256 请求签名、AES-256-GCM 加解密、响应验签,以及招考公告推送封装。
|
|
41
|
+
|
|
42
|
+
协议与中台 [`docs/sapi/`](../../docs/sapi/README.md)、ThinkPHP / Spring Boot SDK 保持一致。许可证:Apache-2.0。
|
|
43
|
+
|
|
44
|
+
`app_secret` 只能保存在爬虫/服务端,禁止写入前端或客户端。
|
|
45
|
+
|
|
46
|
+
## 安装
|
|
47
|
+
|
|
48
|
+
PyPI(发布后):
|
|
49
|
+
|
|
50
|
+
```bash
|
|
51
|
+
pip install zc-center-sdk
|
|
52
|
+
```
|
|
53
|
+
|
|
54
|
+
源码开发(推荐虚拟环境,避免 macOS `externally-managed-environment`):
|
|
55
|
+
|
|
56
|
+
```bash
|
|
57
|
+
cd sdk/python
|
|
58
|
+
python3 -m venv .venv
|
|
59
|
+
source .venv/bin/activate
|
|
60
|
+
python -m pip install -U pip
|
|
61
|
+
python -m pip install -e ".[dev]"
|
|
62
|
+
pytest -q
|
|
63
|
+
```
|
|
64
|
+
|
|
65
|
+
发布到 PyPI 的完整步骤见 [PUBLISH.md](./PUBLISH.md)。
|
|
66
|
+
|
|
67
|
+
## 配置
|
|
68
|
+
|
|
69
|
+
| 环境变量 | 说明 |
|
|
70
|
+
| --- | --- |
|
|
71
|
+
| `ZC_CENTER_BASE_URL` | 中台根地址,如 `https://zc-center.example.com` |
|
|
72
|
+
| `ZC_CENTER_APP_KEY` | 中台应用 `app_key` |
|
|
73
|
+
| `ZC_CENTER_APP_SECRET` | 中台应用 `app_secret` |
|
|
74
|
+
| `ZC_CENTER_ENCRYPTION` | `1`/`0`,须与中台 `SAPI_ENCRYPTION_ENABLED` 一致 |
|
|
75
|
+
|
|
76
|
+
联调可关闭加密;生产必须开启。
|
|
77
|
+
|
|
78
|
+
## 爬虫推荐流程
|
|
79
|
+
|
|
80
|
+
1. 在中台「业务管理 → 应用管理」为爬虫创建生态应用,拿到 `app_key` / `app_secret`,配置 IP 白名单。
|
|
81
|
+
2. 爬虫抓取并组合数据后,**不要依赖中台扫盘读 JSON**;直接调用 `exam_notice.report_batch`。
|
|
82
|
+
3. 每条至少传 `title`、`collect_source`;强烈建议再传稳定幂等键之一:
|
|
83
|
+
- `uuid`(来源系统 UUID v4)
|
|
84
|
+
- 或 `collect_ref`(来源站点内唯一 ID)
|
|
85
|
+
- 或稳定的 `official_url` / `collect_url`
|
|
86
|
+
4. 单次最多 100 条;示例脚本会自动分批。
|
|
87
|
+
|
|
88
|
+
### 代码示例
|
|
89
|
+
|
|
90
|
+
```python
|
|
91
|
+
from zc_center import Client
|
|
92
|
+
|
|
93
|
+
client = Client(
|
|
94
|
+
base_url="https://zc-center.example.com",
|
|
95
|
+
app_key="...",
|
|
96
|
+
app_secret="...",
|
|
97
|
+
encryption=True,
|
|
98
|
+
)
|
|
99
|
+
|
|
100
|
+
client.ping().send("crawler-ready")
|
|
101
|
+
|
|
102
|
+
result = client.exam_notice().report_batch([
|
|
103
|
+
{
|
|
104
|
+
"title": "某市事业单位招聘公告",
|
|
105
|
+
"collect_source": "某市人社局",
|
|
106
|
+
"collect_ref": "src-2026-001",
|
|
107
|
+
"official_url": "https://example.com/notices/1",
|
|
108
|
+
"publish_time": 1788888888,
|
|
109
|
+
"content": "<p>公告正文</p>",
|
|
110
|
+
}
|
|
111
|
+
]).data()
|
|
112
|
+
|
|
113
|
+
print(result["created"], result["exists"], result["failed"])
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
Flask 等框架无特殊依赖,在服务端任务里直接 `from zc_center import Client` 即可。
|
|
117
|
+
|
|
118
|
+
### 一键推送 JSON 文件
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
export ZC_CENTER_BASE_URL=https://zc-center.example.com
|
|
122
|
+
export ZC_CENTER_APP_KEY=...
|
|
123
|
+
export ZC_CENTER_APP_SECRET=...
|
|
124
|
+
|
|
125
|
+
python examples/push_exam_notices.py /data/crawler/notices-2026-09-09.json
|
|
126
|
+
```
|
|
127
|
+
|
|
128
|
+
JSON 支持数组,或 `{"items":[...]}` / `{"list":[...]}`。
|
|
129
|
+
|
|
130
|
+
## 字段约定(招考公告)
|
|
131
|
+
|
|
132
|
+
| 字段 | 必填 | 说明 |
|
|
133
|
+
| --- | --- | --- |
|
|
134
|
+
| `title` | 是 | 公告标题 |
|
|
135
|
+
| `collect_source` | 是 | 采集来源站点/单位名 |
|
|
136
|
+
| `uuid` | 推荐 | UUID v4,来源稳定 ID |
|
|
137
|
+
| `collect_ref` | 推荐 | 来源侧业务主键 |
|
|
138
|
+
| `official_url` / `collect_url` | 推荐 | 用于排重 |
|
|
139
|
+
| `code` / `exam_type` / `area_code` | 否 | 业务编码、招考类型、地区码 |
|
|
140
|
+
| `publisher_name` / `summary` / `content` | 否 | 发布单位、摘要、正文 |
|
|
141
|
+
| `publish_time` 等时间字段 | 否 | Unix 秒;也可传可解析时间字符串 |
|
|
142
|
+
|
|
143
|
+
排重优先级见 [`docs/sapi/招考公告.md`](../../docs/sapi/招考公告.md)。
|
|
144
|
+
|
|
145
|
+
## 与「扫盘导入」的关系
|
|
146
|
+
|
|
147
|
+
本 SDK 走推模式:爬虫写完即上报。中台无需再为「几点读哪个目录」建配置表;若仍保留本地 JSON,仅作备份或对账即可。
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
LICENSE
|
|
2
|
+
README.md
|
|
3
|
+
pyproject.toml
|
|
4
|
+
src/zc_center/__init__.py
|
|
5
|
+
src/zc_center/client.py
|
|
6
|
+
src/zc_center/crypto.py
|
|
7
|
+
src/zc_center/exceptions.py
|
|
8
|
+
src/zc_center/py.typed
|
|
9
|
+
src/zc_center/response.py
|
|
10
|
+
src/zc_center/api/__init__.py
|
|
11
|
+
src/zc_center/api/abstract.py
|
|
12
|
+
src/zc_center/api/exam_notice.py
|
|
13
|
+
src/zc_center/api/ping.py
|
|
14
|
+
src/zc_center_sdk_python.egg-info/PKG-INFO
|
|
15
|
+
src/zc_center_sdk_python.egg-info/SOURCES.txt
|
|
16
|
+
src/zc_center_sdk_python.egg-info/dependency_links.txt
|
|
17
|
+
src/zc_center_sdk_python.egg-info/requires.txt
|
|
18
|
+
src/zc_center_sdk_python.egg-info/top_level.txt
|
|
19
|
+
tests/test_crypto.py
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
zc_center
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
from __future__ import annotations
|
|
2
|
+
|
|
3
|
+
from zc_center.crypto import Crypto
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
def test_canonical_request_matches_thinkphp_fixture() -> None:
|
|
7
|
+
crypto = Crypto()
|
|
8
|
+
query = {"z": "最后", "a": "first value"}
|
|
9
|
+
body = '{"echo":"hello"}'
|
|
10
|
+
canonical = crypto.canonical_request(
|
|
11
|
+
"post",
|
|
12
|
+
"/sapi/ping",
|
|
13
|
+
query,
|
|
14
|
+
"1787823238",
|
|
15
|
+
"g3N4RKzB9QMHYVqE4-ug_SDl",
|
|
16
|
+
body,
|
|
17
|
+
)
|
|
18
|
+
expected = (
|
|
19
|
+
"POST\n/sapi/ping\na=first%20value&z=%E6%9C%80%E5%90%8E\n"
|
|
20
|
+
"1787823238\ng3N4RKzB9QMHYVqE4-ug_SDl\n"
|
|
21
|
+
+ crypto.sha256_hex(body)
|
|
22
|
+
)
|
|
23
|
+
assert canonical == expected
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
def test_aes_gcm_round_trip() -> None:
|
|
27
|
+
crypto = Crypto()
|
|
28
|
+
secret = "sdk-test-secret"
|
|
29
|
+
aad = crypto.aad("sdk-test-app-key", "1787823238", "g3N4RKzB9QMHYVqE4-ug_SDl")
|
|
30
|
+
payload = {"hello": "世界"}
|
|
31
|
+
|
|
32
|
+
envelope = crypto.encrypt(payload, secret, aad)
|
|
33
|
+
decrypted = crypto.decrypt(envelope, secret, aad)
|
|
34
|
+
assert decrypted == payload
|
|
35
|
+
|
|
36
|
+
signature = crypto.sign(
|
|
37
|
+
"\n".join(
|
|
38
|
+
[
|
|
39
|
+
"1787823238",
|
|
40
|
+
"g3N4RKzB9QMHYVqE4-ug_SDl",
|
|
41
|
+
envelope["iv"],
|
|
42
|
+
envelope["tag"],
|
|
43
|
+
envelope["ciphertext"],
|
|
44
|
+
]
|
|
45
|
+
),
|
|
46
|
+
secret,
|
|
47
|
+
)
|
|
48
|
+
assert crypto.verify_encrypted_response(
|
|
49
|
+
envelope, signature, "1787823238", "g3N4RKzB9QMHYVqE4-ug_SDl", secret
|
|
50
|
+
)
|