dxpos-openapi 0.0.1__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,6 @@
1
+ from dxpos_openapi.client import DxposClient
2
+ from dxpos_openapi.constants import DEFAULT_BASE_URL
3
+
4
+ __version__ = "0.0.1"
5
+
6
+ __all__ = ["DxposClient", "DEFAULT_BASE_URL", "__version__"]
dxpos_openapi/auth.py ADDED
@@ -0,0 +1,42 @@
1
+ import hashlib
2
+ import hmac
3
+ import time
4
+ import uuid
5
+
6
+ from dxpos_openapi.constants import (
7
+ HEADER_ACCESS_KEY,
8
+ HEADER_NONCE,
9
+ HEADER_SIGNATURE,
10
+ HEADER_TIMESTAMP,
11
+ )
12
+
13
+
14
+ def body_sha256_hex(body):
15
+ return hashlib.sha256(body or b"").hexdigest()
16
+
17
+
18
+ def build_sign_str(method, path, timestamp, nonce, body):
19
+ return "{}\n{}\n{}\n{}\n{}".format(
20
+ method,
21
+ path,
22
+ timestamp,
23
+ nonce,
24
+ body_sha256_hex(body),
25
+ )
26
+
27
+
28
+ def sign_headers(access_key, secret_key, method, path, body=b""):
29
+ timestamp = str(int(time.time()))
30
+ nonce = uuid.uuid4().hex
31
+ raw = build_sign_str(method, path, timestamp, nonce, body)
32
+ signature = hmac.new(
33
+ secret_key.encode("utf-8"),
34
+ raw.encode("utf-8"),
35
+ hashlib.sha256,
36
+ ).hexdigest()
37
+ return {
38
+ HEADER_ACCESS_KEY: access_key,
39
+ HEADER_TIMESTAMP: timestamp,
40
+ HEADER_NONCE: nonce,
41
+ HEADER_SIGNATURE: signature,
42
+ }
@@ -0,0 +1,174 @@
1
+ import json
2
+ import os
3
+
4
+ import requests
5
+
6
+ from dxpos_openapi.auth import sign_headers
7
+ from dxpos_openapi.constants import (
8
+ DEFAULT_BASE_URL,
9
+ IMAGE_TYPE_FILE_ID,
10
+ IMAGE_TYPE_URL,
11
+ MIME_BY_SUFFIX,
12
+ PATH_FILE,
13
+ PATH_SCENE_ENHANCEMENT,
14
+ PATH_THEME,
15
+ path_cancel,
16
+ path_task,
17
+ )
18
+
19
+
20
+ def _fail(msg, request_id=""):
21
+ return {"code": -1, "msg": msg, "data": {}, "request_id": request_id}
22
+
23
+
24
+ def _encode_json(payload):
25
+ return json.dumps(payload, ensure_ascii=False).encode("utf-8")
26
+
27
+
28
+ class DxposClient(object):
29
+ def __init__(self, access_key, secret_key, base_url=DEFAULT_BASE_URL, timeout=30):
30
+ if not access_key or not secret_key:
31
+ raise ValueError("access_key 和 secret_key 不能为空")
32
+ self.access_key = access_key
33
+ self.secret_key = secret_key
34
+ self.base_url = base_url.rstrip("/")
35
+ self.timeout = timeout
36
+ self._session = requests.Session()
37
+
38
+ def list_themes(self):
39
+ return self._request("GET", PATH_THEME)
40
+
41
+ def upload_file(self, image_path):
42
+ loaded = self._read_local_image(image_path)
43
+ if loaded["error"] is not None:
44
+ return loaded["error"]
45
+ created = self._request(
46
+ "POST",
47
+ PATH_FILE,
48
+ {
49
+ "size": loaded["size"],
50
+ "content_type": loaded["content_type"],
51
+ "filename": loaded["filename"],
52
+ },
53
+ )
54
+ if created.get("code") != 0:
55
+ return created
56
+ put_url = (created.get("data") or {}).get("put_url")
57
+ if not put_url:
58
+ return _fail("预创建成功但缺少 put_url")
59
+ put_error = self._put_cos(
60
+ put_url,
61
+ loaded["raw"],
62
+ loaded["content_type"],
63
+ loaded["size"],
64
+ )
65
+ if put_error is not None:
66
+ return put_error
67
+ return created
68
+
69
+ def create_scene_enhancement(self, theme_id, file_id=None, image_path=None, image_url=None):
70
+ picked = [item for item in (file_id, image_path, image_url) if item]
71
+ if len(picked) != 1:
72
+ return _fail("file_id、image_path、image_url 必须三选一")
73
+ if image_url:
74
+ return self._request(
75
+ "POST",
76
+ PATH_SCENE_ENHANCEMENT,
77
+ {
78
+ "theme_id": theme_id,
79
+ "image": {"type": IMAGE_TYPE_URL, "url": image_url},
80
+ },
81
+ )
82
+ if file_id:
83
+ return self._request(
84
+ "POST",
85
+ PATH_SCENE_ENHANCEMENT,
86
+ {
87
+ "theme_id": theme_id,
88
+ "image": {"type": IMAGE_TYPE_FILE_ID, "file_id": file_id},
89
+ },
90
+ )
91
+ uploaded = self.upload_file(image_path)
92
+ if uploaded.get("code") != 0:
93
+ return uploaded
94
+ new_file_id = (uploaded.get("data") or {}).get("file_id")
95
+ if not new_file_id:
96
+ return _fail("上传成功但缺少 file_id")
97
+ return self._request(
98
+ "POST",
99
+ PATH_SCENE_ENHANCEMENT,
100
+ {
101
+ "theme_id": theme_id,
102
+ "image": {"type": IMAGE_TYPE_FILE_ID, "file_id": new_file_id},
103
+ },
104
+ )
105
+
106
+ def get_task(self, task_id):
107
+ return self._request("GET", path_task(task_id))
108
+
109
+ def cancel_task(self, task_id):
110
+ return self._request("POST", path_cancel(task_id))
111
+
112
+ def _request(self, method, path, payload=None):
113
+ body = b"" if payload is None else _encode_json(payload)
114
+ headers = sign_headers(self.access_key, self.secret_key, method, path, body)
115
+ if payload is not None:
116
+ headers["Content-Type"] = "application/json"
117
+ try:
118
+ resp = self._session.request(
119
+ method,
120
+ self.base_url + path,
121
+ data=body,
122
+ headers=headers,
123
+ timeout=self.timeout,
124
+ )
125
+ except requests.RequestException as exc:
126
+ return _fail("请求失败: {}".format(exc))
127
+ try:
128
+ parsed = resp.json()
129
+ except ValueError:
130
+ return _fail("响应不是 JSON: HTTP {}".format(resp.status_code))
131
+ if not isinstance(parsed, dict):
132
+ return _fail("响应格式不正确")
133
+ return parsed
134
+
135
+ def _put_cos(self, put_url, raw, content_type, size):
136
+ try:
137
+ resp = self._session.put(
138
+ put_url,
139
+ data=raw,
140
+ headers={
141
+ "Content-Type": content_type,
142
+ "Content-Length": str(size),
143
+ },
144
+ timeout=self.timeout,
145
+ )
146
+ except requests.RequestException as exc:
147
+ return _fail("上传失败: {}".format(exc))
148
+ if resp.status_code not in (200, 204):
149
+ return _fail("上传失败: HTTP {}".format(resp.status_code))
150
+ return None
151
+
152
+ @staticmethod
153
+ def _read_local_image(image_path):
154
+ if not image_path or not os.path.isfile(image_path):
155
+ return {"error": _fail("本地文件不存在")}
156
+ content_type = MIME_BY_SUFFIX.get(os.path.splitext(image_path)[1].lower())
157
+ if content_type is None:
158
+ return {
159
+ "error": _fail("图片格式不支持,仅支持 image/jpeg、image/png、image/webp")
160
+ }
161
+ try:
162
+ with open(image_path, "rb") as handle:
163
+ raw = handle.read()
164
+ except OSError as exc:
165
+ return {"error": _fail("读取本地文件失败: {}".format(exc))}
166
+ if not raw:
167
+ return {"error": _fail("本地文件为空")}
168
+ return {
169
+ "error": None,
170
+ "raw": raw,
171
+ "content_type": content_type,
172
+ "filename": os.path.basename(image_path),
173
+ "size": len(raw),
174
+ }
@@ -0,0 +1,28 @@
1
+ DEFAULT_BASE_URL = "https://openapi.dxpos.co"
2
+
3
+ PATH_THEME = "/api/v1/theme"
4
+ PATH_FILE = "/api/v1/file"
5
+ PATH_SCENE_ENHANCEMENT = "/api/v1/task/scene_enhancement"
6
+
7
+ HEADER_ACCESS_KEY = "X-Access-Key"
8
+ HEADER_TIMESTAMP = "X-Timestamp"
9
+ HEADER_NONCE = "X-Nonce"
10
+ HEADER_SIGNATURE = "X-Signature"
11
+
12
+ IMAGE_TYPE_FILE_ID = "file_id"
13
+ IMAGE_TYPE_URL = "url"
14
+
15
+ MIME_BY_SUFFIX = {
16
+ ".jpg": "image/jpeg",
17
+ ".jpeg": "image/jpeg",
18
+ ".png": "image/png",
19
+ ".webp": "image/webp",
20
+ }
21
+
22
+
23
+ def path_task(task_id):
24
+ return "/api/v1/task/{}".format(task_id)
25
+
26
+
27
+ def path_cancel(task_id):
28
+ return "/api/v1/task/{}/cancel".format(task_id)
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 DXPOS
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,199 @@
1
+ Metadata-Version: 2.1
2
+ Name: dxpos-openapi
3
+ Version: 0.0.1
4
+ Summary: DXPOS OpenAPI Python SDK
5
+ Author-email: DXPOS <support@dxpos.co>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2026 DXPOS
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+
28
+ Project-URL: Homepage, https://openapi.dxpos.co
29
+ Project-URL: Documentation, https://openapi.dxpos.co
30
+ Keywords: dxpos,openapi,sdk
31
+ Classifier: Development Status :: 3 - Alpha
32
+ Classifier: Intended Audience :: Developers
33
+ Classifier: License :: OSI Approved :: MIT License
34
+ Classifier: Operating System :: OS Independent
35
+ Classifier: Programming Language :: Python :: 3
36
+ Classifier: Programming Language :: Python :: 3.8
37
+ Classifier: Programming Language :: Python :: 3.9
38
+ Classifier: Programming Language :: Python :: 3.10
39
+ Classifier: Programming Language :: Python :: 3.11
40
+ Classifier: Programming Language :: Python :: 3.12
41
+ Classifier: Programming Language :: Python :: 3.13
42
+ Classifier: Topic :: Software Development :: Libraries :: Python Modules
43
+ Requires-Python: >=3.8.16
44
+ Description-Content-Type: text/markdown
45
+ License-File: LICENSE
46
+ Requires-Dist: requests==2.31.0
47
+ Requires-Dist: urllib3==1.26.20
48
+ Requires-Dist: certifi==2024.8.30
49
+ Requires-Dist: charset-normalizer==3.3.2
50
+ Requires-Dist: idna==3.7
51
+ Provides-Extra: dev
52
+ Requires-Dist: pytest==8.3.5; extra == "dev"
53
+ Requires-Dist: build==1.2.2; extra == "dev"
54
+ Requires-Dist: twine==5.1.1; extra == "dev"
55
+ Requires-Dist: setuptools==75.3.0; extra == "dev"
56
+ Requires-Dist: wheel==0.45.1; extra == "dev"
57
+
58
+ # dxpos-openapi
59
+
60
+ DXPOS OpenAPI 的 Python SDK。安装后:
61
+
62
+ ```python
63
+ from dxpos_openapi import DxposClient
64
+ ```
65
+
66
+ 需要 Python 3.8.16 及以上。
67
+
68
+ ## 安装
69
+
70
+ ```bash
71
+ pip install dxpos-openapi
72
+ ```
73
+
74
+ 升级:
75
+
76
+ ```bash
77
+ pip install -U dxpos-openapi
78
+ ```
79
+
80
+ ## 初始化
81
+
82
+ 密钥和域名在构造 `DxposClient` 时传入,SDK 不读环境变量。`base_url` 默认生产域名。
83
+
84
+ ```python
85
+ from dxpos_openapi import DxposClient
86
+
87
+ client = DxposClient(
88
+ access_key="你的 Access Key",
89
+ secret_key="你的 Secret Key",
90
+ # base_url="https://openapi-test.dxpos.co", # 测试环境
91
+ )
92
+ ```
93
+
94
+ | 环境 | base_url |
95
+ |------|----------|
96
+ | 生产(默认) | `https://openapi.dxpos.co` |
97
+ | 测试 | `https://openapi-test.dxpos.co` |
98
+
99
+ 五个方法会自动做 HMAC 签名,不用自己算。
100
+
101
+ ## 返回值
102
+
103
+ 每个方法都返回接口原样字典,业务失败也不抛异常:
104
+
105
+ ```python
106
+ {
107
+ "code": 0,
108
+ "msg": "",
109
+ "data": {},
110
+ "request_id": "req_..."
111
+ }
112
+ ```
113
+
114
+ `code == 0` 为成功,读 `data`。本地文件不存在、格式不支持、COS 上传失败、网络错误等会合成 `code == -1`。
115
+
116
+ ## 方法
117
+
118
+ ### 主题列表
119
+
120
+ ```python
121
+ resp = client.list_themes()
122
+ theme_id = resp["data"]["items"][0]["theme_id"]
123
+ ```
124
+
125
+ ### 上传本地图片
126
+
127
+ 内部会预创建文件并 PUT 到 COS。成功时返回预创建接口的原样 JSON,`data` 里有 `file_id`。
128
+
129
+ ```python
130
+ resp = client.upload_file("/path/to/product.jpg")
131
+ file_id = resp["data"]["file_id"]
132
+ ```
133
+
134
+ 仅支持 `.jpg` / `.jpeg` / `.png` / `.webp`。
135
+
136
+ ### 创建场景增强任务
137
+
138
+ `file_id`、`image_path`、`image_url` 必须三选一。
139
+
140
+ ```python
141
+ # 已有公网 URL
142
+ resp = client.create_scene_enhancement(
143
+ theme_id=theme_id,
144
+ image_url="https://example.com/product.jpg",
145
+ )
146
+
147
+ # 已经 upload_file 拿到 file_id
148
+ resp = client.create_scene_enhancement(theme_id=theme_id, file_id=file_id)
149
+
150
+ # 本地路径:自动上传再建任务
151
+ resp = client.create_scene_enhancement(
152
+ theme_id=theme_id,
153
+ image_path="/path/to/product.jpg",
154
+ )
155
+
156
+ task_id = resp["data"]["task_id"]
157
+ ```
158
+
159
+ ### 查询任务
160
+
161
+ ```python
162
+ resp = client.get_task(task_id)
163
+ # data.status: waiting / processing / done / failed / canceled
164
+ ```
165
+
166
+ ### 取消任务
167
+
168
+ 仅排队中(`waiting`)可取消。
169
+
170
+ ```python
171
+ resp = client.cancel_task(task_id)
172
+ ```
173
+
174
+ ## 维护者:发布到 PyPI
175
+
176
+ 不需要把 token 写进仓库。本机配置 `~/.pypirc`,用 `__token__` 和 API token。
177
+
178
+ 开发依赖:
179
+
180
+ ```bash
181
+ pip install -e ".[dev]"
182
+ pytest
183
+ ```
184
+
185
+ 首次 `0.0.1`:
186
+
187
+ ```bash
188
+ rm -rf dist build src/*.egg-info
189
+ python -m build
190
+ twine check dist/*
191
+ twine upload -r testpypi dist/*
192
+ # 干净环境验证:
193
+ # pip install -i https://test.pypi.org/simple/ --extra-index-url https://pypi.org/simple dxpos-openapi==0.0.1
194
+ twine upload dist/*
195
+ git tag v0.0.1
196
+ git push origin main --tags
197
+ ```
198
+
199
+ 以后更新:同步改 `pyproject.toml` 的 `version` 和 `src/dxpos_openapi/__init__.py` 的 `__version__`,再走一遍 build / twine / tag。同一版本号不能覆盖重传。小改用 `0.0.x`,加方法或改入参用 `0.1.0`。
@@ -0,0 +1,9 @@
1
+ dxpos_openapi/__init__.py,sha256=3ChDNCNYzU6kw6IXq5m2b4jb_eZyMnt6WQCLPaYK7X4,183
2
+ dxpos_openapi/auth.py,sha256=nmARbBgQq6k6iNIzhdNR1Yndo3NfQORGVJtzrJRbxBc,950
3
+ dxpos_openapi/client.py,sha256=yaOh3fjIC2ETOrIsmAUhS9P_3erY9a-loh03cLejhOM,5861
4
+ dxpos_openapi/constants.py,sha256=asy51Q8UtrBX0FZS0FVUS4ZGpymIrIargjQqAjKyx5o,621
5
+ dxpos_openapi-0.0.1.dist-info/LICENSE,sha256=0EazA4qvynt-70-mNL0Q5vzQFwGuLMLRjgzrAmKsmMY,1062
6
+ dxpos_openapi-0.0.1.dist-info/METADATA,sha256=YqcDD44DmFaEQRIV4ZVRx2fPy2dOsSMgL60y0nemVQA,5655
7
+ dxpos_openapi-0.0.1.dist-info/WHEEL,sha256=P9jw-gEje8ByB7_hXoICnHtVCrEwMQh-630tKvQWehc,91
8
+ dxpos_openapi-0.0.1.dist-info/top_level.txt,sha256=w-2h_7jVu5SIf_rSTubE3wy50gW1QAvBngNVBjktuJ4,14
9
+ dxpos_openapi-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (75.3.0)
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
5
+
@@ -0,0 +1 @@
1
+ dxpos_openapi