Skip to main content

py-hikvision-sdk

Python ISC Lint Type

海康威视 iSecure Center OpenAPI Python SDK。纯 AK/SK 签名认证 + 同步 HTTP 请求,覆盖区域 / 资源 / 人员 / 车辆 / 停车场 等核心业务域。


目录


功能特性

  • ✅ 覆盖 55 个官方接口 — 区域 / 资源 / 人员 / 车辆 / 停车场
  • ✅ AK/SK 摘要认证 — 纯函数实现 X-Ca-* 头生成,无额外依赖
  • ✅ 全类型注解 — Pydantic v2 + Mypy strict + from __future__ import annotations
  • ✅ 响应模型 — 统一 ISCCommonResponse / ISCPageResponse,自动异常映射
  • ✅ 增量同步 — timeRange 系列接口,ISO 8601 时间格式
  • ✅ 版本兼容 — HTTP 404 / 组件未装 自动 pytest.skip
  • ✅ 相对导入 — src/ 内部 0 绝对导入残留
  • ✅ 工具链就绪 — uv + hatchling + ruff + mypy + pytest

接口覆盖

ISCRegionAPI — 区域信息(6 个)

方法 说明
get_rootregion() 获取根区域信息
listregions(page_no, page_size) 分页获取区域列表
queryregions_v2(resource_type, ...) 高级查询区域列表
query_subregions_v2(parent_index_code, ...) 获取下一级子区域
getregions_by_codes(index_codes) 按编号批量查询区域
queryregions_by_time_range(start_time, end_time, ...) 增量获取区域

ISCResourceAPI — 设备资源(4 个)

方法 说明
queryresources_v2(resource_type, ...) 按条件查询资源
listresources_v2(resource_type, ...) 全量同步资源
query_subresources_v2(region_index_code, ...) 按区域获取下级资源
queryresources_by_time_range(resource_type, start_time, end_time, ...) 增量获取资源

ISCPersonAPI — 人员 / 组织 / 卡片 / 人脸(26 个)

分组 方法
组织(8) batch_add_orgs / update_org / batch_delete_orgs / get_root_org / query_orgs / query_orgs_v2 / query_sub_orgs / query_orgs_by_time_range
人员(6) add_person_v2 / batch_addpersons / update_person / batch_deletepersons / querypersons / querypersons_by_time_range
卡片(8) batch_bind_cards / delete_card / batch_loss_cards / batch_unloss_cards / generate_card_barcode / get_card / query_cards / query_cards_v2
人脸(3) add_face / update_face / delete_face
其他(1) getresource_properties

ISCVehicleAPI — 车辆 / 车库(7 个)

方法 说明
batch_add_vehicles(vehicles) 批量添加车辆
updatevehicle(vehicle_id, ...) 修改车辆
batch_deletevehicles(vehicle_ids) 批量删除车辆
queryvehicle_list_v2(page_no, page_size, ...) 高级查询车辆
queryvehicles_by_time_range(start_time, end_time, ...) 增量获取车辆
query_park_list() 获取停车库列表
query_park_nodes(page_no, page_size, ...) 查询停车库节点

ISCParkingAPI — 停车场功能(12 个)

分组 方法
查询(7) query_temp_car_in_records / query_parking_record / query_cross_records / query_vehicle_image / query_vehicle_charge_info / queryvehicle_categories / query_park_list
缴费(3) query_account_charge_records / query_car_charge_records / query_charge_bill_records
固定车(3) charge_vehicle / cancel_vehicle_charge / query_vehicle_charge_info
车辆分类(1) bind_vehicle_category

注:ParkingAPI 依赖 pmsweb 停车服务组件。服务端未安装时返回 0x0240103a,测试用例自动 skip。


快速开始

安装

# uv(推荐)
uv add py-hikvision-sdk

# pip
pip install py-hikvision-sdk

# 源码开发
git clone https://gitee.com/guolei19850528/py_hikvision_sdk.git
cd py_hikvision_sdk
uv sync

配置

复制 .env.example → .env,填入真实参数:

# 必需
ISC_HOST=202.97.177.116
ISC_PORT=1443
ISC_AK=your_access_key
ISC_SK=your_secret_key
ISC_HTTPS=true
ISC_VERIFY_SSL=false
ISC_TIMEOUT=30

# 可选(pytest)
ISC_DESTRUCTIVE_TESTS=false   # 写操作测试需显式开启

调用

from py_hikvision_sdk import provider
from py_hikvision_sdk.core.isc.base.config import ISCAPIConfig

cfg = ISCAPIConfig(
    host="202.97.177.116", port=1443,
    ak="your_access_key", sk="your_secret_key",
    https=True, verify_ssl=False,
)

# context manager 自动关闭 httpx.Client
with provider.ISCAPIProvider(config=cfg) as p:

    # 区域:查询根区域
    resp = p.region_api.get_rootregion()
    resp.raise_for_status()
    print(resp.data)
    # → {"indexCode": "root000000", "name": "金泰学府三期", ...}

    # 资源:查询摄像机列表
    resp = p.resource_api.queryresources_v2(resource_type="camera", page_no=1, page_size=20)
    resp.raise_for_status()
    print(f"共 {resp.data['total']} 台摄像机")

    # 人员:批量添加组织
    resp = p.person_api.batch_add_orgs(orgs=[
        {"orgIndexCode": "dept_001", "orgName": "研发部", "parentOrgIndexCode": "root000000"},
    ])
    resp.raise_for_status()
    print("组织添加成功")

    # 车辆:查询车辆列表
    resp = p.vehicle_api.queryvehicle_list_v2(page_no=1, page_size=50)
    resp.raise_for_status()

# ISCCommonResponse 统一响应结构
# ├── .ok          bool, code == "0"
# ├── .code        str, 海康返回码
# ├── .msg         str, 执行说明
# ├── .data        Any, 业务数据(dict / list / None)
# └── .raise_for_status()  按错误码抛对应异常

项目结构

py_hikvision_sdk/
├── pyproject.toml                  # uv + hatchling + ruff + mypy + pytest
├── .env.example                    # 环境变量模板
├── src/py_hikvision_sdk/
│   ├── __init__.py                 # 包入口(只导 __version__ / provider)
│   ├── _version.py                 # SDK 版本号
│   ├── provider.py                 # ISCAPIProvider(继承 ISCBaseAPI + 挂载 5 业务 API)
│   └── core/isc/
│       ├── base/                   # 底层能力
│       │   ├── config.py           # ISCAPIConfig(Pydantic)
│       │   ├── signature.py        # AK/SK 纯函数(4 个)
│       │   ├── api.py              # ISCBaseAPI / ISCAPI
│       │   ├── models.py           # ISCBaseResponse / ISCCommonResponse / ISCPageResponse
│       │   └── exceptions.py       # ISCError + 6 子类 + raise_for_code
│       ├── resource_directory/
│       │   ├── region.py           # ISCRegionAPI(6)
│       │   ├── resource.py         # ISCResourceAPI(4)
│       │   └── person.py           # ISCPersonAPI(26)
│       └── vehicle_control/
│           ├── parking.py          # ISCParkingAPI(12)
│           └── vehicle.py          # ISCVehicleAPI(7)
└── tests/
    ├── conftest.py                 # 只负责读 .env + pytest hook
    ├── test_readonly.py            # 33 个只读查询用例(默认执行)
    └── test_destructive.py         # 4 个写操作用例(默认 skip)

分层架构

┌──────────────────────────────────────────────────────────┐
│             调用方(业务代码)                            │
│         from py_hikvision_sdk import provider            │
│         from py_hikvision_sdk.core.isc.base.config       │
└──────────────────────────────────────────────────────────┘
                          │
                          ▼
┌──────────────────────────────────────────────────────────┐
│              ISCAPIProvider(主入口)                    │
│  继承 ISCBaseAPI,组合持有 5 个业务 API                  │
│                                                          │
│  p.base_api           ISCAPI(请求能力直接可用)          │
│  p.region_api         ISCRegionAPI                        │
│  p.person_api         ISCPersonAPI                        │
│  p.resource_api       ISCResourceAPI                      │
│  p.parking_api        ISCParkingAPI                       │
│  p.vehicle_api        ISCVehicleAPI                       │
└──────────────────────────────────────────────────────────┘
                          │
                          ▼
┌──────────────────────────────────────────────────────────┐
│               ISCBaseAPI(请求基类)                     │
│  _post_json(path, body) → ISCCommonResponse              │
│  - AK/SK 签名 → X-Ca-* 头                                │
│  - httpx.Client 发送 HTTPS                               │
│  - raise_for_status → ISCError                            │
└──────────────────────────────────────────────────────────┘

依赖关系

业务 API  ──组合──▶  ISCAPIProvider.base_api(ISCBaseAPI)
                       │
                       ├── ISCAPIConfig    (Pydantic 配置)
                       ├── signature.*     (签名纯函数)
                       ├── httpx           (HTTP 客户端)
                       └── pydantic        (响应模型校验)

配置说明

ISCAPIConfig

字段 类型 必需 默认值 说明
host str ✅ — iSecure Center IP / 域名
port int ✅ — 端口
ak str ✅ — Access Key
sk str ✅ — Secret Key
https bool ❌ True 是否 HTTPS
verify_ssl bool ❌ False 证书校验
timeout int ❌ 30 请求超时(秒)

响应模型

ISCCommonResponse(
    code="0",           # "0" 表示成功
    msg="success",
    data={...},         # dict / list / None
)

resp.ok                          # code == "0"
resp.raise_for_status()          # 按 code 抛对应异常

异常体系

ISCError                       # 基类
├── ISCAuthError               # 鉴权错误
├── ISCParamError              # 参数格式错误(如 0x00072003)
├── ISCPermissionError         # 权限不足
├── ISCResourceError           # 资源不存在
├── ISCServiceError            # 服务不可用(如 0x0240103a 组件未装)
└── ISCGatewayError            # 网关错误

raise_for_code(code, msg, data) # 工厂函数

测试

# 1. 默认:只读查询(33 个用例,不修改服务端数据)
pytest tests/test_readonly.py -v

# 2. 含 destructive skip 标记一起跑
pytest tests/ -v

# 3. 开启写操作测试(⚠️ 会修改真实数据)
ISC_DESTRUCTIVE_TESTS=true pytest tests/test_destructive.py -v

# 4. 仅跑某个业务类
pytest tests/test_readonly.py::TestRegionAPI -v

实测结果(目标:202.97.177.116:1443)

22 passed, 11 skipped in 3.66s

SKIPPED 原因:
  - HTTP 404  query_sub_orgs / querypersons_by_time_range    # 接口版本不支持
  - 0x0240103a  ParkingAPI 全部                               # pmsweb 组件未安装
  - 前置数据   query_charge_bill_records                     # 无停车库

实测数据规模

资源类型 数量
区域节点 1714
摄像机 449
人员 4099
卡片 6185
停车库 0

开发命令

# 环境
uv sync                              # 安装依赖
uv run python -c "from py_hikvision_sdk import provider; print('OK')"

# 代码检查
uv run ruff check src/ tests/        # Lint
uv run ruff format src/ tests/       # 格式化
uv run mypy src/                     # 类型检查

# 测试
uv run pytest tests/ -v              # 默认只读
ISC_DESTRUCTIVE_TESTS=true uv run pytest tests/test_destructive.py -v

# 打包
uv build                             # 生成 dist/*.whl

技术栈

工具 版本 用途
Python ≥ 3.10 运行时
httpx ≥ 0.27 HTTP 客户端
pydantic ≥ 2.7 配置 & 响应模型
hatchling — 构建后端
uv — 包管理
ruff ≥ 0.5 Lint + Format
mypy ≥ 1.10 类型检查(strict)
pytest ≥ 8 集成测试
python-dotenv ≥ 1.2 .env 加载

官方文档


License

MIT © guolei

Metadata

Release files for py-hikvision-sdk 0.1.2

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for py-hikvision-sdk 0.1.2
File Size Uploaded Provenance Actions
py_hikvision_sdk-0.1.2.tar.gz 91.2 kB Without provenance Details for py_hikvision_sdk-0.1.2.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for py-hikvision-sdk 0.1.2
File Interpreter ABI Platform Actions
py_hikvision_sdk-0.1.2-py3-none-any.whl Python 3 none any Details for py_hikvision_sdk-0.1.2-py3-none-any.whl

Total release size: 131.4 kB

Release files / py_hikvision_sdk-0.1.2.tar.gz

Download URL py_hikvision_sdk-0.1.2.tar.gz
Size 91.2 kB
Tags Source
SHA-256 checksum
How to use checksums
8c95dd50e2298f47fc2057e2cd782217d958fec6c0302d947aed459b25b3218a
BLAKE2b-256 checksum
How to use checksums
5d0da3d846b53aceab74661125c7dafbd6fab0a4a621f9cbf0e42aaea711347b
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Release files / py_hikvision_sdk-0.1.2-py3-none-any.whl

Download URL py_hikvision_sdk-0.1.2-py3-none-any.whl
Size 40.3 kB
Tags Python 3
SHA-256 checksum
How to use checksums
133f6386106041428e6894ca626fef3a6c44865ce39420a6acb13f4c604b8007
BLAKE2b-256 checksum
How to use checksums
383b290f7d65ed96c888c20773a6a7e0eb1db73fd3c6933764794d15137815f7
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
No
Uploaded via uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"macOS","version":null,"id":null,"libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}

Security for py-hikvision-sdk 0.1.2

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

No provenance found

None of the files in this release were uploaded with provenance metadata.

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page