Metadata-Version: 2.4
Name: py-hikvision-toolkit
Version: 1.0.1
Summary: 一个用于与海康威视 iSecure Center (ISC) API 交互的 Python 客户端库
Author-email: Guolei <174000902@qq.com>
License: MIT License
        
        Copyright (c) 2026 郭磊
        
        Permission is hereby granted, free of charge, to any person obtaining a copy
        of this software and associated documentation files (the "Software"), to deal
        in the Software without restriction, including without limitation the rights
        to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
        copies of the Software, and to permit persons to whom the Software is
        furnished to do so, subject to the following conditions:
        
        The above copyright notice and this permission notice shall be included in all
        copies or substantial portions of the Software.
        
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
        IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
        AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
        LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
        OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
        SOFTWARE.
        
Project-URL: Homepage, https://gitee.com/guolei19850528/py_hikvision_toolkit
Project-URL: Repository, https://gitee.com/guolei19850528/py_hikvision_toolkit.git
Keywords: isc,hikvision,python,client,api,海康威视,iSecure Center
Classifier: License :: OSI Approved :: MIT License
Classifier: Development Status :: 4 - Beta
Classifier: Intended Audience :: Developers
Classifier: Programming Language :: Python :: 3
Classifier: Programming Language :: Python :: 3.10
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Operating System :: OS Independent
Requires-Python: >=3.10
Description-Content-Type: text/markdown
License-File: LICENSE
Requires-Dist: pydantic>=2.0
Requires-Dist: jsonpath-ng>=1.5.3
Requires-Dist: jsonschema>=4.21.0
Requires-Dist: py-httpx-toolkit>=1.0.1
Provides-Extra: dev
Requires-Dist: pytest>=7.0; extra == "dev"
Requires-Dist: pytest-cov>=4.0; extra == "dev"
Requires-Dist: setuptools>=61.0; extra == "dev"
Requires-Dist: twine>=4.0; extra == "dev"
Dynamic: license-file

# py-hikvision-toolkit

一个用于与海康威视 iSecure Center (ISC) API 交互的 Python 客户端库。

---

## 项目主页

- **Gitee**: [https://gitee.com/guolei19850528/py_hikvision_toolkit](https://gitee.com/guolei19850528/py_hikvision_toolkit)
- **文档**: [海康威视开放平台](https://open.hikvision.com/osp#%E7%BB%BC%E5%90%88%E5%AE%89%E9%98%B2%E7%AE%A1%E7%90%86%E5%B9%B3%E5%8F%B0)

---

## 功能特性

- **HMAC-SHA256 签名算法**：符合 Artemis 网关规范的请求签名
- **同步/异步支持**：同时支持同步和异步 HTTP 请求
- **请求头自动生成**：自动处理认证信息（Access Key、Nonce、Timestamp、Signature）
- **响应数据模型**：基于 Pydantic 的响应数据验证和类型提示
- **工具函数集**：提供 JSONPath 查询、图片处理、URL 处理等辅助功能

---

## 安装

### 使用 uv（推荐）

```bash
uv add py-hikvision-toolkit
```

### 使用 pip

```bash
pip install py-hikvision-toolkit
```


## 快速开始

```python
from py_hikvision_toolkit.isc import Isc
from py_hikvision_toolkit.isc.utils import build_success_instance, url_add_artemis_prefix

# 初始化 ISC 客户端
isc = Isc(
    host="https://isc.example.com:1443",
    ak="your_access_key",
    sk="your_secret_key"
)

# 发送同步请求
response = isc.request_with_headers(
    url=url_add_artemis_prefix("/api/resource/v1/org/orgInfo"),
    json={"orgIndexCodes": ["root000000"]}
)

# 解析响应
result = build_success_instance(response)
print(result.data)
```

---

## API 说明

### Isc 客户端类

#### 初始化

```python
from py_hikvision_toolkit.isc import Isc

isc = Isc(
    host="https://isc.example.com:1443",    # ISC 服务器地址
    ak="your_ak",                           # Access Key
    sk="your_sk",                           # Secret Key
    client_kwargs={"timeout": 30}           # 可选：客户端配置
)
```

#### 核心方法

| 方法 | 说明 | 参数 |
|------|------|------|
| `signature(string)` | 生成 HMAC-SHA256 签名 | `string`: 待签名字符串 |
| `headers(method, path, headers)` | 生成认证请求头 | `method`: HTTP 方法, `path`: 请求路径, `headers`: 额外请求头 |
| `request_with_headers(**kwargs)` | 发送同步请求 | 支持 httpx.Client.request 的所有参数 |
| `async_request_with_headers(**kwargs)` | 发送异步请求 | 支持 httpx.AsyncClient.request 的所有参数 |

#### 认证机制

ISC API 使用基于 HMAC-SHA256 的签名机制：

1. 构建签名字符串（按顺序拼接）：
   - HTTP 方法（如 POST）
   - Accept 头值
   - Content-Type 头值
   - x-ca-key
   - x-ca-nonce（随机 UUID）
   - x-ca-timestamp（毫秒时间戳）
   - 请求路径

2. 使用 Secret Key 对签名字符串进行 HMAC-SHA256 签名

3. 将签名放入 `x-ca-signature` 请求头中

---

## utils 工具函数

| 函数 | 说明 | 参数 | 返回值 |
|------|------|------|--------|
| `timestamp()` | 生成毫秒时间戳 | - | `int` |
| `nonce()` | 生成随机 UUID（无连字符） | - | `str` |
| `url_add_artemis_prefix(url)` | 添加 Artemis 前缀 | `url`: 请求路径 | `str` |
| `json_find_first(expression, data)` | JSONPath 查询首个匹配项 | `expression`: JSONPath 表达式, `data`: 数据 | `Any` |
| `json_is_valid(schema, data)` | JSON Schema 校验 | `schema`: Schema 字典, `data`: 待校验数据 | `bool` |
| `image_to_base64_and_md5(image_path)` | 图片转 Base64 和 MD5 | `image_path`: 图片路径 | `Tuple[str, str]` |
| `build_success_instance(response)` | 构建 Success 模型 | `response`: HTTP 响应或字典 | `Success` |
| `success_is_valid(response, schema)` | 校验成功响应 | `response`: 响应数据, `schema`: Schema | `bool` |

---

## 响应数据模型

### Base 模型

```python
from py_hikvision_toolkit.isc.responses import Base

response = {"code": 0, "msg": "success"}
base = Base(**response)
```

字段说明：
- `code`: 错误码，0 表示成功（支持整数和字符串）
- `msg`: 错误信息描述

### Success 模型

```python
from py_hikvision_toolkit.isc.responses import Success

response = {"code": 0, "msg": "success", "data": {"items": []}}
success = Success(**response)
print(success.data)
```

字段说明：
- `code`: 固定为 0 或 "0"
- `msg`: 成功消息（可选）
- `data`: 返回的实际数据

---

## 示例代码

### 示例 1：获取组织信息

```python
from py_hikvision_toolkit.isc import Isc
from py_hikvision_toolkit.isc.utils import build_success_instance, url_add_artemis_prefix

isc = Isc(host="https://isc.example.com:1443", ak="your_ak", sk="your_sk")

response = isc.request_with_headers(
    url=url_add_artemis_prefix("/api/resource/v2/org/advance/orgList"),
    json={"orgIndexCodes": "root000000", "pageNo": 1, "pageSize": 100}
)

result = build_success_instance(response)
print(result.data)
```

### 示例 2：异步请求

```python
import asyncio
from py_hikvision_toolkit.isc import Isc
from py_hikvision_toolkit.isc.utils import build_success_instance

async def main():
    isc = Isc(host="https://isc.example.com:1443", ak="your_ak", sk="your_sk")
    response = await isc.async_request_with_headers(
        url="/api/resource/v1/org/orgInfo",
        json={"orgIndexCodes": ["root000000"]}
    )
    result = build_success_instance(response)
    print(result.data)

asyncio.run(main())
```

### 示例 3：添加人脸

```python
from py_hikvision_toolkit.isc import Isc
from py_hikvision_toolkit.isc.utils import url_add_artemis_prefix, image_to_base64_and_md5

isc = Isc(host="https://isc.example.com:1443", ak="your_ak", sk="your_sk")

# 将图片转换为 Base64
base64_str, md5_str = image_to_base64_and_md5("/path/to/face.jpg")

response = isc.request_with_headers(
    url=url_add_artemis_prefix("/api/resource/v1/person/single/add"),
    json={
        "tagId": "frs",
        "personName": "张三",
        "certificateType": "111",
        "certificateNo": "110101199001011234",
        "orgIndexCode": "e5b44598-9b9f-4273-8540-3209eaf4c7a1",
        "faces": [{"faceData": base64_str}]
    }
)
```

### 示例 4：JSONPath 查询

```python
from py_hikvision_toolkit.isc.utils import json_find_first

data = {
    "store": {
        "book": [
            {"title": "Python", "price": 29},
            {"title": "Java", "price": 35}
        ]
    }
}

# 获取第一本书的标题
title = json_find_first("$.store.book[0].title", data)
print(title)  # "Python"
```

---

## 项目结构

```
py_hikvision_toolkit/
├── src/
│   └── py_hikvision_toolkit/
│       ├── __init__.py
│       └── isc/
│           ├── __init__.py       # Isc 客户端类
│           ├── responses.py      # 响应数据模型
│           └── utils.py          # 工具函数
├── pyproject.toml
├── LICENSE
└── README.md
```

---

## 许可证

MIT License

---

## 作者

Guolei (<174000902@qq.com>)
