# VWED在线脚本编辑模块接口文档 ## 概述 VWED在线脚本编辑模块提供了完整的Python脚本在线编辑、执行和管理功能。支持多脚本并发运行、实时日志推送、动态API注册、函数调用等特性,并可与VWED任务系统无缝集成。 **基础URL**: `/api/script` **版本**: v1.0 **支持的功能**: - 脚本项目和文件管理 - 实时脚本编辑和语法验证 - 多脚本并发执行引擎 - 实时日志推送和状态监控 - 动态API接口注册 - 自定义函数注册和调用 - VWED任务系统集成 --- ## 1. 脚本项目管理 ### 1.1 创建脚本项目 **接口地址**: `POST /api/script/projects` **功能说明**: 创建新的脚本项目,项目用于组织管理多个脚本文件。 **请求参数**: ```json { "project_name": "string", // 项目名称,必填,最大100字符 "description": "string", // 项目描述,可选 "created_by": "string" // 创建者,可选,最大100字符 } ``` **响应示例**: ```json { "success": true, "message": "项目 测试项目 创建成功", "data": { "id": 1, "project_name": "测试项目", "project_path": "projects/测试项目", "description": "这是一个测试项目", "status": "active", "created_by": "admin", "created_at": "2025-09-11T12:00:00", "updated_at": "2025-09-11T12:00:00" } } ``` ### 1.2 获取项目列表 **接口地址**: `GET /api/script/projects` **功能说明**: 获取所有脚本项目列表。 **查询参数**: - `status` (可选): 项目状态过滤,默认为 "active" **响应示例**: ```json { "success": true, "data": [ { "id": 1, "project_name": "测试项目", "project_path": "projects/测试项目", "description": "这是一个测试项目", "status": "active", "created_by": "admin", "created_at": "2025-09-11T12:00:00", "updated_at": "2025-09-11T12:00:00" } ] } ``` ### 1.3 获取项目文件列表 **接口地址**: `GET /api/script/projects/{project_id}/files` **功能说明**: 获取指定项目下的所有脚本文件。 **路径参数**: - `project_id`: 项目ID **查询参数**: - `include_content` (可选): 是否包含文件内容,默认为 false **响应示例**: ```json { "success": true, "data": { "project": { "id": 1, "project_name": "测试项目", "project_path": "projects/测试项目" }, "files": [ { "id": 1, "file_name": "main.py", "file_path": "main.py", "file_type": "python", "size": 1024, "has_boot_function": true, "status": "active", "created_at": "2025-09-11T12:00:00", "content": "def boot():\n pass" // 仅当include_content=true时包含 } ] } } ``` --- ## 2. 脚本文件管理 ### 2.1 创建脚本文件 **接口地址**: `POST /api/script/files` **功能说明**: 在指定项目中创建新的脚本文件。 **请求参数**: ```json { "project_id": 1, // 所属项目ID,必填 "file_name": "string", // 文件名,必填,最大255字符 "file_path": "string", // 文件相对路径,必填,最大500字符 "content": "string", // 文件内容,可选 "file_type": "python", // 文件类型,默认为"python" "created_by": "string" // 创建者,可选 } ``` **响应示例**: ```json { "success": true, "message": "文件 main.py 创建成功", "data": { "id": 1, "project_id": 1, "file_name": "main.py", "file_path": "main.py", "file_type": "python", "content": "def boot():\n print('Hello VWED!')", "size": 35, "has_boot_function": true, "status": "active", "created_by": "admin", "created_at": "2025-09-11T12:00:00", "updated_at": "2025-09-11T12:00:00" } } ``` ### 2.2 获取文件内容 **接口地址**: `GET /api/script/files/{file_id}` **功能说明**: 获取指定脚本文件的详细信息和内容。 **路径参数**: - `file_id`: 文件ID **响应示例**: ```json { "success": true, "data": { "file": { "id": 1, "project_id": 1, "file_name": "main.py", "file_path": "main.py", "file_type": "python", "size": 35, "has_boot_function": true, "status": "active", "created_at": "2025-09-11T12:00:00", "updated_at": "2025-09-11T12:00:00" }, "content": "def boot():\n print('Hello VWED!')" } } ``` ### 2.3 更新文件内容 **接口地址**: `PUT /api/script/files/{file_id}` **功能说明**: 更新指定脚本文件的内容,自动创建备份。 **路径参数**: - `file_id`: 文件ID **请求参数**: ```json { "content": "string", // 新的文件内容,必填 "updated_by": "string" // 更新者,可选 } ``` **响应示例**: ```json { "success": true, "message": "文件内容更新成功", "data": { "file": { "id": 1, "project_id": 1, "file_name": "main.py", "file_path": "main.py", "content": "def boot():\n VWED.log.sync_info('脚本启动成功')", "size": 45, "has_boot_function": true, "updated_at": "2025-09-11T12:30:00" }, "backup_path": "/path/to/backup/main.py.bak.1726059000" } } ``` ### 2.4 删除文件 **接口地址**: `DELETE /api/script/files/{file_id}` **功能说明**: 删除指定的脚本文件。 **路径参数**: - `file_id`: 文件ID **响应示例**: ```json { "success": true, "message": "文件 main.py 删除成功" } ``` ### 2.5 搜索文件 **接口地址**: `GET /api/script/files/search` **功能说明**: 根据关键字搜索脚本文件。 **查询参数**: - `keyword`: 搜索关键字,必填 - `project_id` (可选): 限制在指定项目中搜索 - `file_type` (可选): 文件类型过滤 - `has_boot` (可选): 是否包含boot函数 **响应示例**: ```json { "success": true, "data": { "files": [ { "id": 1, "file_name": "main.py", "file_path": "main.py", "project_name": "测试项目", "file_type": "python", "has_boot_function": true, "created_at": "2025-09-11T12:00:00" } ], "count": 1 } } ``` ### 2.6 语法验证 **接口地址**: `POST /api/script/validate-syntax` **功能说明**: 验证Python脚本的语法正确性。 **请求参数**: ```json { "content": "string" // 待验证的脚本内容,必填 } ``` **响应示例(成功)**: ```json { "success": true, "data": { "valid": true, "message": "语法检查通过" } } ``` **响应示例(失败)**: ```json { "success": true, "data": { "valid": false, "error": "语法错误: invalid syntax", "line": 5, "offset": 10 } } ``` ### 2.7 上传脚本文件 **接口地址**: `POST /api/script/upload` **功能说明**: 通过文件上传的方式创建脚本文件。 **请求参数** (Form Data): - `project_id`: 项目ID,必填 - `file`: 上传的脚本文件,必填 **响应示例**: ```json { "success": true, "message": "文件上传成功", "data": { "id": 1, "file_name": "uploaded_script.py", "file_path": "uploaded_script.py", "size": 256, "has_boot_function": false, "created_at": "2025-09-11T12:00:00" } } ``` --- ## 3. 脚本执行管理 ### 3.1 启动脚本服务 **接口地址**: `POST /api/script/scripts/start` **功能说明**: 启动脚本服务,执行脚本的boot函数并注册相关服务。每个脚本启动后会生成唯一的script_id用于标识。 **请求参数**: ```json { "script_path": "string", // 脚本相对路径,必填 "start_params": { // 启动参数,可选 "key": "value" } } ``` **响应示例(成功)**: ```json { "success": true, "script_id": "main.py_1726059000000_abc12345", "message": "脚本服务启动成功,已注册 2 个接口,3 个函数,1 个事件监听器", "registrations": { "apis": 2, "functions": 3, "events": 1, "timers": 0 } } ``` **响应示例(失败)**: ```json { "success": false, "error": "脚本文件不存在: invalid_script.py" } ``` ### 3.2 停止脚本服务 **接口地址**: `POST /api/script/scripts/{script_id}/stop` **功能说明**: 停止指定的脚本服务,清理所有注册项。 **路径参数**: - `script_id`: 脚本实例ID **响应示例**: ```json { "success": true, "message": "脚本服务已停止 (main.py),已清理 2 个接口、3 个函数、1 个事件监听器", "registrations": { "apis": 2, "functions": 3, "events": 1, "timers": 0 } } ``` ### 3.3 获取运行中的脚本 **接口地址**: `GET /api/script/scripts/running` **功能说明**: 获取当前所有运行中的脚本服务列表。 **响应示例**: ```json { "success": true, "data": [ { "script_id": "main.py_1726059000000_abc12345", "script_path": "main.py", "started_at": "2025-09-11T12:00:00", "status": "running", "registrations": { "apis": 2, "functions": 3, "events": 1, "timers": 0 } } ] } ``` ### 3.4 执行脚本函数 **接口地址**: `POST /api/script/scripts/execute-function` **功能说明**: 调用运行中脚本的指定函数。 **请求参数**: ```json { "script_id": "string", // 脚本实例ID,必填 "function_name": "string", // 函数名,必填 "function_args": "any" // 函数参数,可选 } ``` **响应示例(成功)**: ```json { "success": true, "result": "函数执行结果", "execution_time_ms": 125 } ``` **响应示例(失败)**: ```json { "success": false, "error": "函数 invalid_function 未注册", "execution_time_ms": 5 } ``` ### 3.5 获取注册中心状态 **接口地址**: `GET /api/script/registry/status` **功能说明**: 获取脚本注册中心的详细状态信息。 **响应示例**: ```json { "success": true, "data": { "api_routes": { "GET:/api/custom/test": { "path": "/api/custom/test", "method": "GET", "script_id": "main.py_1726059000000_abc12345", "description": "测试接口", "call_count": 5, "average_response_time_ms": 15, "registered_at": "2025-09-11T12:00:00" } }, "registered_functions": { "calculate": { "script_id": "main.py_1726059000000_abc12345", "description": "计算函数", "is_async": false, "call_count": 10, "success_count": 9, "error_count": 1, "average_execution_time_ms": 23 } }, "event_listeners": { "task_completed": [ { "script_id": "main.py_1726059000000_abc12345", "priority": 1, "registered_at": "2025-09-11T12:00:00" } ] }, "timers": {}, "active_scripts": { "main.py_1726059000000_abc12345": { "script_path": "main.py", "started_at": "2025-09-11T12:00:00", "status": "running", "heartbeat": 1726059300.123 } } } } ``` --- ## 4. WebSocket实时通信 ### 4.1 脚本日志WebSocket连接 **连接地址**: `ws://localhost:8000/api/script/ws/script-logs` **功能说明**: 建立WebSocket连接,接收实时脚本日志和状态更新。 **连接参数**: - `client_id`: 客户端ID,必填 - `client_type`: 客户端类型,默认为"web" **连接示例**: ```javascript const ws = new WebSocket('ws://localhost:8000/api/script/ws/script-logs?client_id=web-client-1&client_type=web'); ``` ### 4.2 客户端消息格式 **订阅脚本日志**: ```json { "type": "subscribe", "script_id": "main.py_1726059000000_abc12345" } ``` **取消订阅脚本日志**: ```json { "type": "unsubscribe", "script_id": "main.py_1726059000000_abc12345" } ``` **心跳检测**: ```json { "type": "ping", "timestamp": "2025-09-11T12:00:00Z" } ``` **获取连接状态**: ```json { "type": "get_status" } ``` ### 4.3 服务端消息格式 **欢迎消息**: ```json { "type": "welcome", "connection_id": "web_web-client-1_1726059000000", "server_time": "2025-09-11T12:00:00Z", "message": "连接建立成功" } ``` **脚本日志消息**: ```json { "type": "script_log", "script_id": "main.py_1726059000000_abc12345", "timestamp": "2025-09-11T12:00:00Z", "level": "INFO", "message": "脚本执行成功" } ``` **脚本状态变化**: ```json { "type": "script_status", "script_id": "main.py_1726059000000_abc12345", "timestamp": "2025-09-11T12:00:00Z", "status": "running", "message": "脚本启动成功" } ``` **函数执行结果**: ```json { "type": "function_execution", "script_id": "main.py_1726059000000_abc12345", "timestamp": "2025-09-11T12:00:00Z", "function_name": "calculate", "execution_type": "success", "result": { "success": true, "data": 42, "execution_time_ms": 15 } } ``` ### 4.4 获取WebSocket连接状态 **接口地址**: `GET /api/script/ws/connections/status` **功能说明**: 获取当前WebSocket连接的详细状态。 **响应示例**: ```json { "success": true, "data": { "total_connections": 3, "total_script_subscriptions": 2, "connections": [ { "connection_id": "web_client1_1726059000000", "client_id": "client1", "client_type": "web", "connected_at": "2025-09-11T12:00:00Z", "subscribed_scripts": ["main.py_1726059000000_abc12345"] } ], "script_subscriptions": { "main.py_1726059000000_abc12345": 2 } } } ``` ### 4.5 WebSocket测试页面 **接口地址**: `GET /api/script/ws/test-page` **功能说明**: 获取WebSocket测试页面,提供完整的测试界面。 **响应**: HTML页面,包含: - WebSocket连接控制 - 脚本订阅/取消订阅 - 实时日志显示 - 心跳检测功能 ### 4.6 测试广播消息 **接口地址**: `POST /api/script/ws/broadcast/test` **功能说明**: 向指定脚本的订阅者测试广播消息。 **请求参数**: ```json { "script_id": "main.py_1726059000000_abc12345", "message": "测试消息", "level": "info" } ``` **响应示例**: ```json { "success": true, "message": "测试消息已广播到脚本 main.py_1726059000000_abc12345 的订阅者" } ``` --- ## 5. VWED统一对象系统 ### 5.1 VWED对象结构 在脚本中可以使用全局的`VWED`对象,包含以下模块: ```python # VWED对象结构 VWED.api # API接口注册模块 VWED.function # 自定义函数注册模块 VWED.event # 事件系统模块 VWED.timer # 定时任务模块 VWED.log # 日志系统模块 VWED.task # 任务系统集成模块 VWED.data # 数据存储模块 VWED.util # 工具函数模块 ``` ### 5.2 API注册模块(VWED.api) **功能说明**: 用于动态注册HTTP API接口,支持GET、POST、PUT、DELETE等方法。 **使用示例**: ```python # 注册GET接口 @VWED.api.get("/test", description="测试接口") def handle_test(request_data): return {"message": "Hello from script!"} # 注册POST接口 @VWED.api.post("/calculate", description="计算接口") def handle_calculate(request_data): a = request_data["body"].get("a", 0) b = request_data["body"].get("b", 0) return {"result": a + b} # 通用注册方式 @VWED.api.register("/custom", "PUT", description="自定义接口") def handle_custom(request_data): return {"status": "success"} ``` **request_data结构**: ```python { "method": "GET", # HTTP方法 "path": "/api/custom/test", # 请求路径 "query_params": {"key": "value"}, # 查询参数 "path_params": {"id": "123"}, # 路径参数 "body": {"data": "value"}, # 请求体数据 "headers": {"Content-Type": "application/json"}, # 请求头 "client": "192.168.1.100" # 客户端IP } ``` ### 5.3 函数注册模块(VWED.function) **功能说明**: 注册自定义函数,供VWED任务系统或其他脚本调用。 **使用示例**: ```python # 注册同步函数 @VWED.function.register("add_numbers", description="数字相加") def add_numbers(args): return args["a"] + args["b"] # 注册异步函数 @VWED.function.register("async_process", description="异步处理") async def async_process(args): await VWED.util.async_sleep(1) return {"processed": True} # 带参数定义的函数注册 @VWED.function.register( "complex_calc", description="复杂计算", parameters=[ {"name": "x", "type": "number", "required": True}, {"name": "y", "type": "number", "required": True} ], return_schema={"type": "object", "properties": {"result": {"type": "number"}}}, tags=["math", "calculation"] ) def complex_calc(args): return {"result": args["x"] * args["y"] + 10} ``` ### 5.4 事件系统模块(VWED.event) **功能说明**: 事件监听和触发机制,支持系统事件和自定义事件。 **使用示例**: ```python # 监听任务完成事件 @VWED.event.listen("task_completed") def on_task_completed(event_data): VWED.log.sync_info(f"任务完成: {event_data['task_id']}") # 高优先级事件监听 @VWED.event.listen("critical_error", priority=0) # 优先级越低越先执行 def on_critical_error(event_data): VWED.log.sync_error(f"严重错误: {event_data['error']}") # 触发自定义事件 async def trigger_event(): await VWED.event.emit("custom_event", { "source": "script", "data": {"key": "value"}, "timestamp": VWED.util.now() }) # 事件监听器的别名用法 @VWED.event.on("user_login") def handle_user_login(event_data): VWED.log.sync_info(f"用户登录: {event_data['user_id']}") ``` ### 5.5 定时任务模块(VWED.timer) **功能说明**: 注册定时任务和周期性任务。 **使用示例**: ```python # 每30秒执行一次 @VWED.timer.interval(30) def heartbeat(): VWED.log.sync_info("心跳检测") # 延迟5秒后执行一次 @VWED.timer.once(delay=5) def delayed_task(): VWED.log.sync_info("延迟任务执行") # 复合定时任务 @VWED.timer.interval(60, repeat=True, delay=10) def monitor_system(): # 延迟10秒开始,然后每60秒执行一次 VWED.log.sync_info("系统监控检查") # 使用别名 @VWED.timer.every(120) # 每2分钟执行 def cleanup_temp_files(): VWED.log.sync_info("清理临时文件") ``` ### 5.6 日志系统模块(VWED.log) **功能说明**: 记录日志并实时推送到WebSocket客户端。 **使用示例**: ```python # 异步日志记录(推荐) async def async_log_example(): await VWED.log.info("信息日志", extra_data={"key": "value"}) await VWED.log.warning("警告日志", component="database") await VWED.log.error("错误日志", error_code=500) await VWED.log.debug("调试日志", debug_info="详细信息") # 同步日志记录(在非异步环境中使用) def sync_log_example(): VWED.log.sync_info("同步信息日志") VWED.log.sync_warning("同步警告日志") VWED.log.sync_error("同步错误日志") VWED.log.sync_debug("同步调试日志") # 带结构化数据的日志 def structured_log_example(): VWED.log.sync_info("用户操作", user_id="12345", action="login", ip_address="192.168.1.100", timestamp=VWED.util.now() ) ``` ### 5.7 任务系统集成模块(VWED.task) **功能说明**: 与VWED任务系统集成,支持任务创建和执行。 **使用示例**: ```python # 创建VWED任务(功能规划中) async def create_new_task(): result = await VWED.task.create_task("动态任务", { "blocks": [ {"type": "start", "config": {}}, {"type": "script", "config": {"function_name": "process_data"}}, {"type": "end", "config": {}} ] }) return result # 执行现有任务(功能规划中) async def execute_existing_task(): result = await VWED.task.execute_task(123, {"param1": "value1"}) return result # 获取任务状态(功能规划中) async def get_task_info(): result = await VWED.task.get_task_status(123) return result ``` ### 5.8 数据存储模块(VWED.data) **功能说明**: 脚本级别的数据存储和缓存。 **使用示例**: ```python # 基本数据操作 def data_operations(): # 存储数据 VWED.data.set("user_count", 100) VWED.data.set("config", {"host": "localhost", "port": 8080}) # 获取数据 count = VWED.data.get("user_count", 0) config = VWED.data.get("config", {}) # 检查键是否存在 if VWED.data.has("user_count"): VWED.log.sync_info(f"当前用户数: {count}") # 获取所有键 all_keys = VWED.data.keys() VWED.log.sync_info(f"存储的键: {all_keys}") # 删除数据 VWED.data.delete("user_count") # 清空所有数据 VWED.data.clear() # 数据缓存示例 def caching_example(): # 检查缓存 cached_result = VWED.data.get("calculation_result") if cached_result is None: # 计算并缓存 result = complex_calculation() VWED.data.set("calculation_result", result) return result else: return cached_result ``` ### 5.9 工具函数模块(VWED.util) **功能说明**: 提供常用的工具函数。 **使用示例**: ```python # 时间工具 def time_utils(): # 获取当前时间 current_time = VWED.util.now() # ISO格式字符串 timestamp = VWED.util.timestamp() # Unix时间戳 VWED.log.sync_info(f"当前时间: {current_time}") VWED.log.sync_info(f"时间戳: {timestamp}") # 睡眠工具 def sleep_utils(): # 同步睡眠 VWED.util.sleep(1) # 睡眠1秒 async def async_sleep_utils(): # 异步睡眠 await VWED.util.async_sleep(2) # 异步睡眠2秒 # UUID生成 def generate_uuid(): unique_id = VWED.util.uuid() VWED.log.sync_info(f"生成的UUID: {unique_id}") return unique_id ``` --- ## 6. VWED任务系统集成 ### 6.1 在任务中调用脚本函数 **功能说明**: VWED任务系统可以调用运行中脚本注册的函数。 **任务块配置示例**: ```json { "block_type": "script", "execution_mode": "function_call", "function_name": "calculate", "function_args": { "a": 10, "b": 20 }, "timeout": 5000, "retry_count": 1 } ``` **执行结果示例**: ```json { "success": true, "result": { "data": 30, "execution_time_ms": 15 }, "message": "脚本函数执行成功" } ``` ### 6.2 获取可用脚本函数 **接口地址**: `GET /api/script/integration/functions` **功能说明**: 获取当前可用的脚本函数列表,供任务编辑器使用。 **查询参数**: - `tags` (可选): 标签筛选,多个标签用逗号分隔 **响应示例**: ```json { "success": true, "data": [ { "function_name": "calculate", "script_id": "main.py_1726059000000_abc12345", "description": "计算函数", "parameters": [ { "name": "a", "type": "number", "required": true, "description": "第一个数字" }, { "name": "b", "type": "number", "required": true, "description": "第二个数字" } ], "return_schema": { "type": "object", "properties": { "result": {"type": "number"} } }, "is_async": false, "tags": ["math", "calculation"], "is_running": true, "stats": { "call_count": 10, "success_count": 9, "error_count": 1, "average_execution_time_ms": 23 } } ] } ``` --- ## 7. 脚本示例 ### 7.1 完整脚本示例 ```python # main.py - 完整的脚本示例 def boot(): """脚本启动函数,注册服务""" VWED.log.sync_info("脚本启动中...") # 注册API接口 setup_apis() # 注册自定义函数 setup_functions() # 设置事件监听器 setup_events() # 设置定时任务 setup_timers() VWED.log.sync_info("脚本服务注册完成") def setup_apis(): """设置API接口""" @VWED.api.get("/hello", description="问候接口") def hello(request_data): name = request_data["query_params"].get("name", "World") return {"message": f"Hello, {name}!"} @VWED.api.post("/process", description="数据处理接口") def process_data(request_data): data = request_data["body"] processed_count = len(data) if isinstance(data, list) else 1 # 记录处理日志 VWED.log.sync_info(f"处理数据: {processed_count} 项") return { "processed": True, "count": processed_count, "timestamp": VWED.util.now() } def setup_functions(): """设置自定义函数""" @VWED.function.register("calculate_sum", description="计算数组和") def calculate_sum(args): numbers = args.get("numbers", []) total = sum(numbers) VWED.log.sync_info(f"计算和: {numbers} = {total}") return {"sum": total, "count": len(numbers)} @VWED.function.register("async_task", description="异步任务") async def async_task(args): task_name = args.get("task_name", "unknown") await VWED.log.info(f"开始异步任务: {task_name}") # 模拟异步处理 await VWED.util.async_sleep(1) await VWED.log.info(f"异步任务完成: {task_name}") return { "completed": True, "task_id": VWED.util.uuid(), "task_name": task_name } @VWED.function.register( "data_validator", description="数据验证器", parameters=[ {"name": "data", "type": "object", "required": True}, {"name": "rules", "type": "array", "required": False} ], tags=["validation", "data"] ) def validate_data(args): data = args.get("data", {}) rules = args.get("rules", ["required"]) errors = [] if "required" in rules and not data: errors.append("数据不能为空") is_valid = len(errors) == 0 VWED.log.sync_info(f"数据验证结果: {'通过' if is_valid else '失败'}") return { "is_valid": is_valid, "errors": errors, "data_size": len(str(data)) } def setup_events(): """设置事件监听器""" @VWED.event.listen("task_completed") def on_task_completed(event_data): VWED.log.sync_info(f"任务完成通知: {event_data.get('task_id', 'unknown')}") # 存储完成任务统计 completed_count = VWED.data.get("completed_tasks", 0) VWED.data.set("completed_tasks", completed_count + 1) @VWED.event.listen("system_error", priority=0) # 高优先级 def on_system_error(event_data): error_msg = event_data.get("error", "未知错误") VWED.log.sync_error(f"系统错误: {error_msg}") # 触发告警事件 asyncio.create_task(VWED.event.emit("alert_required", { "level": "error", "message": error_msg, "source": "script_monitor" })) def setup_timers(): """设置定时任务""" @VWED.timer.interval(60) # 每分钟执行 def monitor_system(): # 检查系统状态 task_count = VWED.data.get("completed_tasks", 0) VWED.log.sync_info(f"系统监控 - 已完成任务数: {task_count}") # 每10个任务清理一次数据 if task_count > 0 and task_count % 10 == 0: VWED.data.set("last_cleanup", VWED.util.now()) @VWED.timer.once(delay=10) # 10秒后执行一次 def initialization_check(): VWED.log.sync_info("初始化检查完成") VWED.data.set("initialized", True) @VWED.timer.every(300) # 每5分钟 def heartbeat(): # 发送心跳事件 asyncio.create_task(VWED.event.emit("script_heartbeat", { "script_id": VWED.get_script_id(), "timestamp": VWED.util.now(), "status": "healthy" })) # 辅助函数示例 def process_sensor_data(sensor_data): """处理传感器数据""" try: # 数据处理逻辑 temperature = sensor_data.get("temperature", 0) humidity = sensor_data.get("humidity", 0) # 异常检测 if temperature > 80: VWED.log.sync_warning(f"温度过高: {temperature}°C") if humidity < 20: VWED.log.sync_warning(f"湿度过低: {humidity}%") # 存储处理结果 VWED.data.set("last_sensor_data", { "temperature": temperature, "humidity": humidity, "processed_at": VWED.util.now() }) return { "success": True, "processed_data": { "temperature": temperature, "humidity": humidity } } except Exception as e: VWED.log.sync_error(f"处理传感器数据失败: {str(e)}") return {"success": False, "error": str(e)} ``` ### 7.2 简单API服务脚本 ```python # api_service.py - 简单API服务示例 def boot(): """注册API服务""" VWED.log.sync_info("API服务启动") @VWED.api.get("/status", description="服务状态检查") def get_status(request_data): return { "status": "running", "timestamp": VWED.util.now(), "version": "1.0.0" } @VWED.api.post("/webhook", description="接收Webhook") def handle_webhook(request_data): webhook_data = request_data["body"] # 记录webhook数据 VWED.log.sync_info(f"收到Webhook: {webhook_data.get('event', 'unknown')}") # 处理不同类型的webhook event_type = webhook_data.get("event_type") if event_type == "user_created": handle_user_created(webhook_data) elif event_type == "order_completed": handle_order_completed(webhook_data) return {"received": True, "processed": True} def handle_user_created(data): """处理用户创建事件""" user_id = data.get("user_id") VWED.log.sync_info(f"新用户创建: {user_id}") # 发送欢迎事件 asyncio.create_task(VWED.event.emit("user_welcome", { "user_id": user_id, "created_at": VWED.util.now() })) def handle_order_completed(data): """处理订单完成事件""" order_id = data.get("order_id") VWED.log.sync_info(f"订单完成: {order_id}") ``` ### 7.3 数据处理脚本 ```python # data_processor.py - 数据处理脚本示例 def boot(): """注册数据处理函数""" VWED.log.sync_info("数据处理服务启动") @VWED.function.register("batch_process", description="批量数据处理") def batch_process(args): data_list = args.get("data_list", []) process_type = args.get("process_type", "default") results = [] for item in data_list: if process_type == "filter": if item.get("status") == "active": results.append(item) elif process_type == "transform": transformed = transform_data_item(item) results.append(transformed) else: results.append(item) VWED.log.sync_info(f"批量处理完成: {len(data_list)} -> {len(results)}") return {"processed_data": results, "original_count": len(data_list)} @VWED.function.register("data_aggregation", description="数据聚合") async def data_aggregation(args): data_source = args.get("data_source", "database") group_by = args.get("group_by", "category") # 模拟数据获取 await VWED.util.async_sleep(0.5) # 模拟聚合结果 aggregated_data = { "category_a": 100, "category_b": 150, "category_c": 75 } await VWED.log.info(f"数据聚合完成: {data_source} by {group_by}") return {"aggregated_data": aggregated_data, "total": sum(aggregated_data.values())} def transform_data_item(item): """转换单个数据项""" transformed = { "id": item.get("id"), "name": item.get("name", "").upper(), "processed_at": VWED.util.now(), "metadata": { "original_keys": list(item.keys()), "transformation_version": "1.0" } } return transformed ``` --- ## 8. 错误处理和调试 ### 8.1 常见错误码 | 错误码 | 说明 | 解决方案 | |--------|------|----------| | 400 | 请求参数错误 | 检查请求参数格式和必填字段 | | 404 | 资源不存在 | 检查项目ID、文件ID、脚本ID是否正确 | | 409 | 资源冲突 | 项目名或文件路径已存在,脚本已在运行 | | 500 | 服务器内部错误 | 查看服务器日志,检查数据库连接 | | 503 | 服务不可用 | 脚本服务未运行或系统繁忙 | ### 8.2 脚本错误示例 **语法错误**: ```json { "success": false, "error": "脚本加载失败: invalid syntax (