裕普智汇

SDK 使用教程

Python 和 Node.js 官方 SDK,快速集成裕普智汇能力

SDK 概述

裕普智汇提供官方 SDK 支持 Python 和 Node.js 两种主流语言,帮助开发者快速集成平台能力。SDK 封装了 API 调用细节,提供更友好的接口和自动重试、错误处理等功能。

Python SDK

安装:

pip install yupu-sdk

初始化:

from yupu import YupuClient

client = YupuClient(api_key='your_api_key')

创建项目

# 创建新项目
project = client.projects.create(
    name="网络巡检",
    description="生产环境定期巡检"
)
print(f"项目ID: {project.id}")

添加设备

# 添加设备
device = client.devices.create(
    project_id=project.id,
    host="192.168.1.1",
    type="cisco-switch",
    username="admin",
    password="your_password"
)
print(f"设备ID: {device.id}")

提交巡检任务

# 提交安全巡检任务
task = client.tasks.create(
    project_id=project.id,
    type="security_scan",
    device_ids=[device.id]
)
print(f"任务ID: {task.task_id}, 状态: {task.status}")

Node.js SDK

安装:

npm install @yupu/sdk

初始化:

import { YupuClient } from '@yupu/sdk';

const client = new YupuClient({ apiKey: 'your_api_key' });

创建项目

// 创建新项目
const project = await client.projects.create({
  name: '网络巡检',
  description: '生产环境定期巡检'
});
console.log(`项目ID: ${project.id}`);

添加设备

// 添加设备
const device = await client.devices.create({
  projectId: project.id,
  host: '192.168.1.1',
  type: 'cisco-switch',
  username: 'admin',
  password: 'your_password'
});
console.log(`设备ID: ${device.id}`);

提交巡检任务

// 提交安全巡检任务
const task = await client.tasks.create({
  projectId: project.id,
  type: 'security_scan',
  deviceIds: [device.id]
});
console.log(`任务ID: ${task.taskId}, 状态: ${task.status}`);

通用模式

分页查询

Python

for page in client.projects.list(limit=10):
    for project in page.items:
        print(project.name)

Node.js

let page = await client.projects.list({ limit: 10 });
for (const project of page.items) {
    console.log(project.name);
}

异步操作

Python

# 创建任务后轮询状态
task = client.tasks.create(...)
while task.status == 'pending':
    time.sleep(5)
    task = client.tasks.get(task.id)

Node.js

// 创建任务后轮询状态
let task = await client.tasks.create(...);
while (task.status === 'pending') {
    await new Promise(r => setTimeout(r, 5000));
    task = await client.tasks.get(task.id);
}

错误处理

Python

try:
    result = client.projects.get(999)
except YupuNotFoundError:
    print("项目不存在")
except YupuAPIError as e:
    print(f"API错误: {e.code}")

Node.js

try {
    const result = await client.projects.get(999);
} catch (error) {
    if (error.code === 'RESOURCE_NOT_FOUND') {
        console.log('项目不存在');
    } else {
        console.log(`API错误: ${error.code}`);
    }
}

常见问题

SDK 支持哪些 Python 版本?

Python SDK 支持 Python 3.8 及以上版本。

SDK 支持哪些 Node.js 版本?

Node.js SDK 支持 Node.js 16 及以上版本。

SDK 会自动处理重试吗?

是的,SDK 内置自动重试机制,对于网络错误和 429 限流错误会自动重试。

可以在浏览器中使用 Node.js SDK 吗?

不建议在浏览器中使用,API 密钥会暴露在前端代码中。