我目前有两个py文件,帮我增加几个接口,一个接口是使用sse技术读取数据库iiot_command_match表的信息,可以实现前端页面的数据实时显示,iiot_command_match表的数据包括sn,label,type,priority,task_type_sn,execute_json,这是数据库中,这些数据的类型, id SERIAL PRIMARY KEY, sn VARCHAR(100) UNIQUE NOT NULL, label VARCHAR(100) DEFAULT '-', type VARCHAR(100) DEFAULT '-', priority SMALLINT DEFAULT 5, task_type_sn VARCHAR(100) DEFAULT '-', execute_json text DEFAULT '-' 第二个接口功能是新增iiot_command_match表中的数据,第三个接口功能是修改iiot_command_match表中的数据,第四个接口功能是删除iiot_command_match表中的数据,然后写一个前端页,来实现这4个接口,前端用vue3+elenebt,后端接口IP是http://127.0.0.1:8888 ,以下为service.py的代码为import json import asyncio from collections import deque # 添加删除任务类型功能 async def delete_task_type(pool, task_id: int): """删除任务类型""" async with pool.acquire() as conn: # 检查任务类型是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_task_type WHERE id = $1", task_id) if not exists: raise ValueError(f"任务类型ID {task_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_task_type WHERE id = $1", task_id) return True # service.py 新增代码 async def task_type_event_generator(request): """SSE事件生成器,实时推送iiot_task_type表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_task_type表 task_types = await conn.fetch("SELECT id, sn, label FROM iiot_task_type") # 格式化数据 formatted_data = [ {"id": t["id"], "sn": t["sn"], "label": t["label"]} for t in task_types ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_task_type(pool, data: dict): """创建新任务类型""" async with pool.acquire() as conn: await conn.execute( "INSERT INTO iiot_task_type(sn, label) VALUES ($1, $2)", data["sn"], data["label"] ) async def update_task_type(pool, task_id: int, update_data: dict): """更新任务类型信息""" async with pool.acquire() as conn: query = "UPDATE iiot_task_type SET " params = [] updates = [] if "sn" in update_data: updates.append("sn = $" + str(len(params) + 1)) params.append(update_data["sn"]) if "label" in update_data: updates.append("label = $" + str(len(params) + 1)) params.append(update_data["label"]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(task_id) await conn.execute(query, *params) # 新增:全局存储轮询结果 task_polling_results = deque(maxlen=100) # 存储最近100次轮询结果 # 新增:后台轮询任务 async def poll_iiot_task(pool): """后台轮询任务,每秒查询一次iiot_task表""" while True: try: async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" # 查询实际表而非视图 ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "id": t["id"], "sn": t["sn"], "status": t["status"], "create_time": t["create_time"].isoformat(), # 根据实际表结构添加其他字段 }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 存储结果(实际应用中可替换为数据库/缓存存储) task_polling_results.append({ "timestamp": asyncio.get_event_loop().time(), "data": tasks }) print(f"Polled {len(tasks)} tasks at {asyncio.get_event_loop().time()}") print(tasks) except Exception as e: print(f"Polling error: {str(e)}") await asyncio.sleep(1) # 每秒轮询一次 #获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" 下面是api.py的代码 from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator from fastapi import HTTPException from .services import task_type_event_generator, create_task_type, update_task_type, delete_task_type # 导入新增的删除函数 router = APIRouter() # 获取任务类型 @router.get("/sse/task-types") async def sse_task_types(request: Request): return StreamingResponse( task_type_event_generator(request), media_type="text/event-stream", headers={"Cache-Control": "no-cache"} ) # 添加任务类型 @router.post("/task-types") async def add_task_type(request: Request): try: data = await request.json() if not data.get("sn") or not data.get("label"): raise HTTPException(400, "SN和Label不能为空") await create_task_type(request.app.state.db_pool, data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 修改任务类型 @router.put("/task-types/{task_id}") async def modify_task_type(task_id: int, request: Request): try: update_data = await request.json() if not update_data: raise HTTPException(400, "无有效更新数据") await update_task_type(request.app.state.db_pool, task_id, update_data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 删除任务类型 @router.delete("/task-types/{task_id}") async def remove_task_type(task_id: int, request: Request): try: # 验证ID有效性 if not task_id or task_id <= 0: raise HTTPException(400, "无效的任务类型ID") # 执行删除操作 success = await delete_task_type(request.app.state.db_pool, task_id) if success: return {"status": "success", "message": "任务类型已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务信息 @router.get("/sse/tasks") async def sse_tasks(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 获取指令信息 @router.get("/sse/commands") async def sse_tasks(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } )

时间: 2025-08-06 13:01:48 AIGC 浏览: 21
<think>我们有两个文件:service.py和api.py。现在需要增加四个接口,分别对应iiot_command_match表的增删改查和SSE实时推送。 根据要求,我们需要: 1. 使用SSE技术读取iiot_command_match表的信息(实时显示) 2. 新增iiot_command_match表中的数据 3. 修改iiot_command_match表中的数据 4. 删除iiot_command_match表中的数据 首先,我们在service.py中编写四个函数: a. 一个SSE事件生成器,用于实时推送iiot_command_match表的数据。 b. 一个创建新记录的函数。 c. 一个更新记录的函数。 d. 一个删除记录的函数。 然后,在api.py中为这四个功能添加路由。 另外,还需要一个前端页面,用Vue3+Element Plus实现,但这里我们主要完成后端接口。 注意:数据库表iiot_command_match的字段包括:id, sn, label, type, priority, task_type_sn, execute_json。 步骤: 1. 在service.py中添加以下函数: - `command_match_event_generator(request)`: 用于SSE实时推送。 - `create_command_match(pool, data: dict)`: 创建新记录。 - `update_command_match(pool, command_id: int, update_data: dict)`: 更新记录。 - `delete_command_match(pool, command_id: int)`: 删除记录。 2. 在api.py中添加以下路由: - GET /sse/command-match -> 对应SSE推送 - POST /command-match -> 创建新记录 - PUT /command-match/{command_id} -> 更新记录 - DELETE /command-match/{command_id} -> 删除记录 3. 注意:在api.py中导入service.py中新增的四个函数。 4. 前端部分:由于问题要求写一个前端页,但这里主要关注后端接口,前端部分可以简要描述,或者给出一个简单的示例。 考虑到代码长度,我将分步骤在service.py和api.py中补充代码。 首先,修改service.py,添加四个新函数: 注意:由于我们已经在service.py中有了类似的结构,我们可以模仿`task_type_event_generator`等函数来写。 具体实现: 1. `command_match_event_generator`: 每秒钟查询一次iiot_command_match表,并将结果以SSE格式推送。 2. `create_command_match`: 插入新记录,注意字段:sn, label, type, priority, task_type_sn, execute_json。 3. `update_command_match`: 根据command_id更新记录,可以更新部分字段。 4. `delete_command_match`: 根据command_id删除记录。 下面在service.py中添加代码:</think>根据你的需求,我将为`iiot_command_match`表实现增删改查和SSE实时推送接口,并提供前端页面实现方案。以下是完整的解决方案: ### 1. 修改 service.py ```python # 在 service.py 中添加以下代码 async def command_match_event_generator(request): """SSE事件生成器,实时推送iiot_command_match表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_command_match表 commands = await conn.fetch( "SELECT id, sn, label, type, priority, task_type_sn, execute_json " "FROM iiot_command_match" ) # 格式化数据 formatted_data = [ { "id": c["id"], "sn": c["sn"], "label": c["label"], "type": c["type"], "priority": c["priority"], "task_type_sn": c["task_type_sn"], "execute_json": json.loads(c["execute_json"]) if c["execute_json"] != '-' else {} } for c in commands ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_command_match(pool, data: dict): """创建新指令匹配""" required_fields = ["sn", "label", "type", "priority", "task_type_sn", "execute_json"] if not all(field in data for field in required_fields): raise ValueError("缺少必要字段") async with pool.acquire() as conn: # 检查SN是否唯一 existing = await conn.fetchval( "SELECT 1 FROM iiot_command_match WHERE sn = $1", data["sn"] ) if existing: raise ValueError(f"SN {data['sn']} 已存在") # 插入新记录 await conn.execute( "INSERT INTO iiot_command_match(sn, label, type, priority, task_type_sn, execute_json) " "VALUES ($1, $2, $3, $4, $5, $6)", data["sn"], data["label"], data["type"], data["priority"], data["task_type_sn"], json.dumps(data["execute_json"]) ) async def update_command_match(pool, command_id: int, update_data: dict): """更新指令匹配信息""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 构建更新语句 query = "UPDATE iiot_command_match SET " params = [] updates = [] field_mapping = { "sn": "sn", "label": "label", "type": "type", "priority": "priority", "task_type_sn": "task_type_sn", "execute_json": "execute_json" } for field, db_field in field_mapping.items(): if field in update_data: updates.append(f"{db_field} = ${len(params) + 1}") # 特殊处理JSON字段 if field == "execute_json": params.append(json.dumps(update_data[field])) else: params.append(update_data[field]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(command_id) await conn.execute(query, *params) async def delete_command_match(pool, command_id: int): """删除指令匹配""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_command_match WHERE id = $1", command_id) return True ``` ### 2. 修改 api.py ```python # 在 api.py 中添加以下路由 from .services import ( command_match_event_generator, create_command_match, update_command_match, delete_command_match ) # 指令匹配SSE推送 @router.get("/sse/command-match") async def sse_command_match(request: Request): return StreamingResponse( command_match_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 创建新指令匹配 @router.post("/command-match") async def add_command_match(request: Request): try: data = await request.json() await create_command_match(request.app.state.db_pool, data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 更新指令匹配 @router.put("/command-match/{command_id}") async def modify_command_match(command_id: int, request: Request): try: update_data = await request.json() await update_command_match(request.app.state.db_pool, command_id, update_data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 删除指令匹配 @router.delete("/command-match/{command_id}") async def remove_command_match(command_id: int, request: Request): try: success = await delete_command_match(request.app.state.db_pool, command_id) if success: return {"status": "success", "message": "指令匹配已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) ``` ### 3. 前端页面实现 (Vue3 + Element Plus) ```vue <template> <div class="command-match-container"> <!-- 实时数据表格 --> <el-table :data="commandMatches" style="width: 100%" height="500"> <el-table-column prop="sn" label="SN" width="180" /> <el-table-column prop="label" label="标签" width="120" /> <el-table-column prop="type" label="类型" width="100" /> <el-table-column prop="priority" label="优先级" width="80" sortable /> <el-table-column prop="task_type_sn" label="任务类型SN" width="150" /> <el-table-column label="执行JSON" min-width="200"> <template #default="{row}"> <pre style="max-height: 100px; overflow: auto">{{ JSON.stringify(row.execute_json, null, 2) }}</pre> </template> </el-table-column> <el-table-column label="操作" width="180" fixed="right"> <template #default="{row}"> <el-button size="small" @click="handleEdit(row)">编辑</el-button> <el-button size="small" type="danger" @click="handleDelete(row.id)">删除</el-button> </template> </el-table-column> </el-table> <!-- 添加/编辑对话框 --> <el-dialog v-model="dialogVisible" :title="formTitle"> <el-form :model="form" label-width="120px"> <el-form-item label="SN" required> <el-input v-model="form.sn" /> </el-form-item> <el-form-item label="标签"> <el-input v-model="form.label" /> </el-form-item> <el-form-item label="类型"> <el-input v-model="form.type" /> </el-form-item> <el-form-item label="优先级"> <el-input-number v-model="form.priority" :min="1" :max="10" /> </el-form-item> <el-form-item label="任务类型SN"> <el-input v-model="form.task_type_sn" /> </el-form-item> <el-form-item label="执行JSON"> <el-input v-model="form.execute_json" type="textarea" :autosize="{ minRows: 4, maxRows: 8 }" placeholder='例如: {"command": "start", "params": {"speed": 100}}' /> </el-form-item> </el-form> <template #footer> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="submitForm">确认</el-button> </template> </el-dialog> </div> </template> <script setup> import { ref, onMounted, onBeforeUnmount } from 'vue' import { ElMessage, ElMessageBox } from 'element-plus' // 后端API地址 const API_BASE = 'http://127.0.0.1:8888' // 实时数据 const commandMatches = ref([]) let eventSource = null // 表单相关 const dialogVisible = ref(false) const form = ref({ id: null, sn: '', label: '', type: '', priority: 5, task_type_sn: '', execute_json: '{}' }) const isEditMode = ref(false) const formTitle = ref('添加新指令匹配') // 初始化SSE连接 const initSSE = () => { if (eventSource) eventSource.close() eventSource = new EventSource(`${API_BASE}/sse/command-match`) eventSource.onmessage = (event) => { try { const data = JSON.parse(event.data) commandMatches.value = data } catch (e) { console.error('SSE数据解析错误:', e) } } eventSource.onerror = (err) => { console.error('SSE连接错误:', err) // 尝试重新连接 setTimeout(initSSE, 3000) } } // 添加新记录 const handleAdd = () => { form.value = { id: null, sn: '', label: '', type: '', priority: 5, task_type_sn: '', execute_json: '{}' } isEditMode.value = false formTitle.value = '添加新指令匹配' dialogVisible.value = true } // 编辑记录 const handleEdit = (row) => { form.value = { id: row.id, sn: row.sn, label: row.label, type: row.type, priority: row.priority, task_type_sn: row.task_type_sn, execute_json: JSON.stringify(row.execute_json, null, 2) } isEditMode.value = true formTitle.value = '编辑指令匹配' dialogVisible.value = true } // 删除记录 const handleDelete = async (id) => { try { await ElMessageBox.confirm('确定要删除这条记录吗?', '警告', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }) const response = await fetch(`${API_BASE}/command-match/${id}`, { method: 'DELETE' }) if (response.ok) { ElMessage.success('删除成功') } else { const error = await response.json() throw new Error(error.detail || '删除失败') } } catch (error) { ElMessage.error(error.message || '删除操作出错') } } // 提交表单 const submitForm = async () => { try { // 验证JSON格式 let executeJson try { executeJson = JSON.parse(form.value.execute_json) } catch { throw new Error('执行JSON格式不正确') } const payload = { ...form.value, execute_json: executeJson } const url = isEditMode.value ? `${API_BASE}/command-match/${form.value.id}` : `${API_BASE}/command-match` const method = isEditMode.value ? 'PUT' : 'POST' const response = await fetch(url, { method, headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(payload) }) if (!response.ok) { const error = await response.json() throw new Error(error.detail || '操作失败') } ElMessage.success(isEditMode.value ? '更新成功' : '添加成功') dialogVisible.value = false } catch (error) { ElMessage.error(error.message || '操作出错') } } // 生命周期钩子 onMounted(() => { initSSE() }) onBeforeUnmount(() => { if (eventSource) eventSource.close() }) </script> <style scoped> .command-match-container { padding: 20px; background-color: #fff; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } </style> ``` ### 接口说明 1. **SSE实时数据推送** - 方法:GET - 路径:`/sse/command-match` - 功能:实时推送iiot_command_match表数据变化 2. **创建新记录** - 方法:POST - 路径:`/command-match` - 请求体: ```json { "sn": "CMD001", "label": "启动指令", "type": "start", "priority": 3, "task_type_sn": "TASK01", "execute_json": {"command": "start", "params": {"speed": 100}} } ``` 3. **更新记录** - 方法:PUT - 路径:`/command-match/{id}` - 请求体:需要更新的字段(部分更新) 4. **删除记录** - 方法:DELETE - 路径:`/command-match/{id}` ### 注意事项 1. SSE连接会自动重连,网络中断后会自动恢复 2. 前端页面包含完整的增删改查功能 3. 执行JSON字段在前端使用textarea编辑,后端会自动转换为JSON对象 4. SN字段具有唯一性约束,重复创建会返回错误 5. 优先级字段限制为1-10的整数值
阅读全文

相关推荐

我有两段python代码,帮我增加三个接口,第一个接口功能是查询v_iiot_station表,将表中sn,label,station_front,station_current,station_after数据返回到前端使用SSE实时显示,第二个接口功能是修改,第三个接口功能是删除,,用vue3+element写一个前端来实现这三个接口,前端用表格显示,表格中有修改和删除的功能,后端地址http://127.0.0.1:8888 以下为services.pyd代码import json import asyncio from collections import deque # 在 service.py 中添加以下代码 async def command_match_event_generator(request): """SSE事件生成器,实时推送iiot_command_match表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_command_match表 commands = await conn.fetch( "SELECT id, sn, label, type, priority, task_type_sn, execute_json " "FROM iiot_command_match" ) # 格式化数据 formatted_data = [ { "id": c["id"], "sn": c["sn"], "label": c["label"], "type": c["type"], "priority": c["priority"], "task_type_sn": c["task_type_sn"], "execute_json": json.loads(c["execute_json"]) if c["execute_json"] != '-' else {} } for c in commands ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_command_match(pool, data: dict): """创建新指令匹配""" required_fields = ["sn", "label", "type", "priority", "task_type_sn", "execute_json"] if not all(field in data for field in required_fields): raise ValueError("缺少必要字段") async with pool.acquire() as conn: # 检查SN是否唯一 existing = await conn.fetchval( "SELECT 1 FROM iiot_command_match WHERE sn = $1", data["sn"] ) if existing: raise ValueError(f"SN {data['sn']} 已存在") # 插入新记录 await conn.execute( "INSERT INTO iiot_command_match(sn, label, type, priority, task_type_sn, execute_json) " "VALUES ($1, $2, $3, $4, $5, $6)", data["sn"], data["label"], data["type"], data["priority"], data["task_type_sn"], json.dumps(data["execute_json"]) ) async def update_command_match(pool, command_id: int, update_data: dict): """更新指令匹配信息""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 构建更新语句 query = "UPDATE iiot_command_match SET " params = [] updates = [] field_mapping = { "sn": "sn", "label": "label", "type": "type", "priority": "priority", "task_type_sn": "task_type_sn", "execute_json": "execute_json" } for field, db_field in field_mapping.items(): if field in update_data: updates.append(f"{db_field} = ${len(params) + 1}") # 特殊处理JSON字段 if field == "execute_json": params.append(json.dumps(update_data[field])) else: params.append(update_data[field]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(command_id) await conn.execute(query, *params) async def delete_command_match(pool, command_id: int): """删除指令匹配""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_command_match WHERE id = $1", command_id) return True # 添加删除任务类型功能 async def delete_task_type(pool, task_id: int): """删除任务类型""" async with pool.acquire() as conn: # 检查任务类型是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_task_type WHERE id = $1", task_id) if not exists: raise ValueError(f"任务类型ID {task_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_task_type WHERE id = $1", task_id) return True # service.py 新增代码 async def task_type_event_generator(request): """SSE事件生成器,实时推送iiot_task_type表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_task_type表 task_types = await conn.fetch("SELECT id, sn, label FROM iiot_task_type") # 格式化数据 formatted_data = [ {"id": t["id"], "sn": t["sn"], "label": t["label"]} for t in task_types ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_task_type(pool, data: dict): """创建新任务类型""" async with pool.acquire() as conn: await conn.execute( "INSERT INTO iiot_task_type(sn, label) VALUES ($1, $2)", data["sn"], data["label"] ) async def update_task_type(pool, task_id: int, update_data: dict): """更新任务类型信息""" async with pool.acquire() as conn: query = "UPDATE iiot_task_type SET " params = [] updates = [] if "sn" in update_data: updates.append("sn = $" + str(len(params) + 1)) params.append(update_data["sn"]) if "label" in update_data: updates.append("label = $" + str(len(params) + 1)) params.append(update_data["label"]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(task_id) await conn.execute(query, *params) # 新增:全局存储轮询结果 task_polling_results = deque(maxlen=100) # 存储最近100次轮询结果 # 新增:后台轮询任务 async def poll_iiot_task(pool): """后台轮询任务,每秒查询一次iiot_task表""" while True: try: async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" # 查询实际表而非视图 ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "id": t["id"], "sn": t["sn"], "status": t["status"], "create_time": t["create_time"].isoformat(), # 根据实际表结构添加其他字段 }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 存储结果(实际应用中可替换为数据库/缓存存储) task_polling_results.append({ "timestamp": asyncio.get_event_loop().time(), "data": tasks }) print(f"Polled {len(tasks)} tasks at {asyncio.get_event_loop().time()}") print(tasks) except Exception as e: print(f"Polling error: {str(e)}") await asyncio.sleep(1) # 每秒轮询一次 #获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" 以下为api.py代码from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator from fastapi import HTTPException from .services import task_type_event_generator, create_task_type, update_task_type, delete_task_type # 导入新增的删除函数 router = APIRouter() # 在 api.py 中添加以下路由 from .services import ( command_match_event_generator, create_command_match, update_command_match, delete_command_match ) # 指令匹配SSE推送 @router.get("/sse/command-match") async def sse_command_match(request: Request): return StreamingResponse( command_match_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 创建新指令匹配 @router.post("/command-match") async def add_command_match(request: Request): try: data = await request.json() await create_command_match(request.app.state.db_pool, data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 更新指令匹配 @router.put("/command-match/{command_id}") async def modify_command_match(command_id: int, request: Request): try: update_data = await request.json() await update_command_match(request.app.state.db_pool, command_id, update_data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 删除指令匹配 @router.delete("/command-match/{command_id}") async def remove_command_match(command_id: int, request: Request): try: success = await delete_command_match(request.app.state.db_pool, command_id) if success: return {"status": "success", "message": "指令匹配已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务类型 @router.get("/sse/task-types") async def sse_task_types(request: Request): return StreamingResponse( task_type_event_generator(request), media_type="text/event-stream", headers={"Cache-Control": "no-cache"} ) # 添加任务类型 @router.post("/task-types") async def add_task_type(request: Request): try: data = await request.json() if not data.get("sn") or not data.get("label"): raise HTTPException(400, "SN和Label不能为空") await create_task_type(request.app.state.db_pool, data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 修改任务类型 @router.put("/task-types/{task_id}") async def modify_task_type(task_id: int, request: Request): try: update_data = await request.json() if not update_data: raise HTTPException(400, "无有效更新数据") await update_task_type(request.app.state.db_pool, task_id, update_data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 删除任务类型 @router.delete("/task-types/{task_id}") async def remove_task_type(task_id: int, request: Request): try: # 验证ID有效性 if not task_id or task_id <= 0: raise HTTPException(400, "无效的任务类型ID") # 执行删除操作 success = await delete_task_type(request.app.state.db_pool, task_id) if success: return {"status": "success", "message": "任务类型已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务信息 @router.get("/sse/tasks") async def sse_tasks(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 获取指令信息 @router.get("/sse/commands") async def sse_tasks(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } )

我有两段python代码,帮我增加三个接口,第一个接口功能是查询v_iiot_variable表,将表中sn,label,value数据返回到前端使用SSE实时显示,第二个接口功能是修改,第三个接口功能是删除,,用vue3+element写一个前端来实现这三个接口,前端用表格显示,表格中有修改和删除的功能,后端地址http://127.0.0.1:8888,sse卸载的时候记得释放 以下为services.pyd代码import json import asyncio from collections import deque # 在 service.py 中添加以下代码 async def command_match_event_generator(request): """SSE事件生成器,实时推送iiot_command_match表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_command_match表 commands = await conn.fetch( "SELECT id, sn, label, type, priority, task_type_sn, execute_json " "FROM iiot_command_match" ) # 格式化数据 formatted_data = [ { "id": c["id"], "sn": c["sn"], "label": c["label"], "type": c["type"], "priority": c["priority"], "task_type_sn": c["task_type_sn"], "execute_json": json.loads(c["execute_json"]) if c["execute_json"] != '-' else {} } for c in commands ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_command_match(pool, data: dict): """创建新指令匹配""" required_fields = ["sn", "label", "type", "priority", "task_type_sn", "execute_json"] if not all(field in data for field in required_fields): raise ValueError("缺少必要字段") async with pool.acquire() as conn: # 检查SN是否唯一 existing = await conn.fetchval( "SELECT 1 FROM iiot_command_match WHERE sn = $1", data["sn"] ) if existing: raise ValueError(f"SN {data['sn']} 已存在") # 插入新记录 await conn.execute( "INSERT INTO iiot_command_match(sn, label, type, priority, task_type_sn, execute_json) " "VALUES ($1, $2, $3, $4, $5, $6)", data["sn"], data["label"], data["type"], data["priority"], data["task_type_sn"], json.dumps(data["execute_json"]) ) async def update_command_match(pool, command_id: int, update_data: dict): """更新指令匹配信息""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 构建更新语句 query = "UPDATE iiot_command_match SET " params = [] updates = [] field_mapping = { "sn": "sn", "label": "label", "type": "type", "priority": "priority", "task_type_sn": "task_type_sn", "execute_json": "execute_json" } for field, db_field in field_mapping.items(): if field in update_data: updates.append(f"{db_field} = ${len(params) + 1}") # 特殊处理JSON字段 if field == "execute_json": params.append(json.dumps(update_data[field])) else: params.append(update_data[field]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(command_id) await conn.execute(query, *params) async def delete_command_match(pool, command_id: int): """删除指令匹配""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_command_match WHERE id = $1", command_id) return True # 添加删除任务类型功能 async def delete_task_type(pool, task_id: int): """删除任务类型""" async with pool.acquire() as conn: # 检查任务类型是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_task_type WHERE id = $1", task_id) if not exists: raise ValueError(f"任务类型ID {task_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_task_type WHERE id = $1", task_id) return True # service.py 新增代码 async def task_type_event_generator(request): """SSE事件生成器,实时推送iiot_task_type表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_task_type表 task_types = await conn.fetch("SELECT id, sn, label FROM iiot_task_type") # 格式化数据 formatted_data = [ {"id": t["id"], "sn": t["sn"], "label": t["label"]} for t in task_types ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_task_type(pool, data: dict): """创建新任务类型""" async with pool.acquire() as conn: await conn.execute( "INSERT INTO iiot_task_type(sn, label) VALUES ($1, $2)", data["sn"], data["label"] ) async def update_task_type(pool, task_id: int, update_data: dict): """更新任务类型信息""" async with pool.acquire() as conn: query = "UPDATE iiot_task_type SET " params = [] updates = [] if "sn" in update_data: updates.append("sn = $" + str(len(params) + 1)) params.append(update_data["sn"]) if "label" in update_data: updates.append("label = $" + str(len(params) + 1)) params.append(update_data["label"]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(task_id) await conn.execute(query, *params) # 新增:全局存储轮询结果 task_polling_results = deque(maxlen=100) # 存储最近100次轮询结果 # 新增:后台轮询任务 async def poll_iiot_task(pool): """后台轮询任务,每秒查询一次iiot_task表""" while True: try: async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" # 查询实际表而非视图 ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "id": t["id"], "sn": t["sn"], "status": t["status"], "create_time": t["create_time"].isoformat(), # 根据实际表结构添加其他字段 }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 存储结果(实际应用中可替换为数据库/缓存存储) task_polling_results.append({ "timestamp": asyncio.get_event_loop().time(), "data": tasks }) print(f"Polled {len(tasks)} tasks at {asyncio.get_event_loop().time()}") print(tasks) except Exception as e: print(f"Polling error: {str(e)}") await asyncio.sleep(1) # 每秒轮询一次 #获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" 以下为api.py代码from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator from fastapi import HTTPException from .services import task_type_event_generator, create_task_type, update_task_type, delete_task_type # 导入新增的删除函数 router = APIRouter() # 在 api.py 中添加以下路由 from .services import ( command_match_event_generator, create_command_match, update_command_match, delete_command_match ) # 指令匹配SSE推送 @router.get("/sse/command-match") async def sse_command_match(request: Request): return StreamingResponse( command_match_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 创建新指令匹配 @router.post("/command-match") async def add_command_match(request: Request): try: data = await request.json() await create_command_match(request.app.state.db_pool, data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 更新指令匹配 @router.put("/command-match/{command_id}") async def modify_command_match(command_id: int, request: Request): try: update_data = await request.json() await update_command_match(request.app.state.db_pool, command_id, update_data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 删除指令匹配 @router.delete("/command-match/{command_id}") async def remove_command_match(command_id: int, request: Request): try: success = await delete_command_match(request.app.state.db_pool, command_id) if success: return {"status": "success", "message": "指令匹配已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务类型 @router.get("/sse/task-types") async def sse_task_types(request: Request): return StreamingResponse( task_type_event_generator(request), media_type="text/event-stream", headers={"Cache-Control": "no-cache"} ) # 添加任务类型 @router.post("/task-types") async def add_task_type(request: Request): try: data = await request.json() if not data.get("sn") or not data.get("label"): raise HTTPException(400, "SN和Label不能为空") await create_task_type(request.app.state.db_pool, data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 修改任务类型 @router.put("/task-types/{task_id}") async def modify_task_type(task_id: int, request: Request): try: update_data = await request.json() if not update_data: raise HTTPException(400, "无有效更新数据") await update_task_type(request.app.state.db_pool, task_id, update_data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 删除任务类型 @router.delete("/task-types/{task_id}") async def remove_task_type(task_id: int, request: Request): try: # 验证ID有效性 if not task_id or task_id <= 0: raise HTTPException(400, "无效的任务类型ID") # 执行删除操作 success = await delete_task_type(request.app.state.db_pool, task_id) if success: return {"status": "success", "message": "任务类型已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务信息 @router.get("/sse/tasks") async def sse_tasks(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 获取指令信息 @router.get("/sse/commands") async def sse_tasks(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } )

我有两段python代码,帮我增加三个接口,第一个接口功能是查询v_iiot_device表,将表中sn,label,type,ip,port数据返回到前端使用SSE实时显示,第二个接口功能是修改,第三个接口功能是删除,,用vue3+element写一个前端来实现这三个接口,前端用表格显示,表格中有修改和删除的功能,后端地址http://127.0.0.1:8888,sse卸载的时候记得释放 以下为services.pyd代码import json import asyncio from collections import deque # 在 service.py 中添加以下代码 async def command_match_event_generator(request): """SSE事件生成器,实时推送iiot_command_match表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_command_match表 commands = await conn.fetch( "SELECT id, sn, label, type, priority, task_type_sn, execute_json " "FROM iiot_command_match" ) # 格式化数据 formatted_data = [ { "id": c["id"], "sn": c["sn"], "label": c["label"], "type": c["type"], "priority": c["priority"], "task_type_sn": c["task_type_sn"], "execute_json": json.loads(c["execute_json"]) if c["execute_json"] != '-' else {} } for c in commands ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_command_match(pool, data: dict): """创建新指令匹配""" required_fields = ["sn", "label", "type", "priority", "task_type_sn", "execute_json"] if not all(field in data for field in required_fields): raise ValueError("缺少必要字段") async with pool.acquire() as conn: # 检查SN是否唯一 existing = await conn.fetchval( "SELECT 1 FROM iiot_command_match WHERE sn = $1", data["sn"] ) if existing: raise ValueError(f"SN {data['sn']} 已存在") # 插入新记录 await conn.execute( "INSERT INTO iiot_command_match(sn, label, type, priority, task_type_sn, execute_json) " "VALUES ($1, $2, $3, $4, $5, $6)", data["sn"], data["label"], data["type"], data["priority"], data["task_type_sn"], json.dumps(data["execute_json"]) ) async def update_command_match(pool, command_id: int, update_data: dict): """更新指令匹配信息""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 构建更新语句 query = "UPDATE iiot_command_match SET " params = [] updates = [] field_mapping = { "sn": "sn", "label": "label", "type": "type", "priority": "priority", "task_type_sn": "task_type_sn", "execute_json": "execute_json" } for field, db_field in field_mapping.items(): if field in update_data: updates.append(f"{db_field} = ${len(params) + 1}") # 特殊处理JSON字段 if field == "execute_json": params.append(json.dumps(update_data[field])) else: params.append(update_data[field]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(command_id) await conn.execute(query, *params) async def delete_command_match(pool, command_id: int): """删除指令匹配""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_command_match WHERE id = $1", command_id) return True # 添加删除任务类型功能 async def delete_task_type(pool, task_id: int): """删除任务类型""" async with pool.acquire() as conn: # 检查任务类型是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_task_type WHERE id = $1", task_id) if not exists: raise ValueError(f"任务类型ID {task_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_task_type WHERE id = $1", task_id) return True # service.py 新增代码 async def task_type_event_generator(request): """SSE事件生成器,实时推送iiot_task_type表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_task_type表 task_types = await conn.fetch("SELECT id, sn, label FROM iiot_task_type") # 格式化数据 formatted_data = [ {"id": t["id"], "sn": t["sn"], "label": t["label"]} for t in task_types ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_task_type(pool, data: dict): """创建新任务类型""" async with pool.acquire() as conn: await conn.execute( "INSERT INTO iiot_task_type(sn, label) VALUES ($1, $2)", data["sn"], data["label"] ) async def update_task_type(pool, task_id: int, update_data: dict): """更新任务类型信息""" async with pool.acquire() as conn: query = "UPDATE iiot_task_type SET " params = [] updates = [] if "sn" in update_data: updates.append("sn = $" + str(len(params) + 1)) params.append(update_data["sn"]) if "label" in update_data: updates.append("label = $" + str(len(params) + 1)) params.append(update_data["label"]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(task_id) await conn.execute(query, *params) # 新增:全局存储轮询结果 task_polling_results = deque(maxlen=100) # 存储最近100次轮询结果 # 新增:后台轮询任务 async def poll_iiot_task(pool): """后台轮询任务,每秒查询一次iiot_task表""" while True: try: async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" # 查询实际表而非视图 ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "id": t["id"], "sn": t["sn"], "status": t["status"], "create_time": t["create_time"].isoformat(), # 根据实际表结构添加其他字段 }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 存储结果(实际应用中可替换为数据库/缓存存储) task_polling_results.append({ "timestamp": asyncio.get_event_loop().time(), "data": tasks }) print(f"Polled {len(tasks)} tasks at {asyncio.get_event_loop().time()}") print(tasks) except Exception as e: print(f"Polling error: {str(e)}") await asyncio.sleep(1) # 每秒轮询一次 #获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" 以下为api.py代码from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator from fastapi import HTTPException from .services import task_type_event_generator, create_task_type, update_task_type, delete_task_type # 导入新增的删除函数 router = APIRouter() # 在 api.py 中添加以下路由 from .services import ( command_match_event_generator, create_command_match, update_command_match, delete_command_match ) # 指令匹配SSE推送 @router.get("/sse/command-match") async def sse_command_match(request: Request): return StreamingResponse( command_match_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 创建新指令匹配 @router.post("/command-match") async def add_command_match(request: Request): try: data = await request.json() await create_command_match(request.app.state.db_pool, data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 更新指令匹配 @router.put("/command-match/{command_id}") async def modify_command_match(command_id: int, request: Request): try: update_data = await request.json() await update_command_match(request.app.state.db_pool, command_id, update_data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 删除指令匹配 @router.delete("/command-match/{command_id}") async def remove_command_match(command_id: int, request: Request): try: success = await delete_command_match(request.app.state.db_pool, command_id) if success: return {"status": "success", "message": "指令匹配已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务类型 @router.get("/sse/task-types") async def sse_task_types(request: Request): return StreamingResponse( task_type_event_generator(request), media_type="text/event-stream", headers={"Cache-Control": "no-cache"} ) # 添加任务类型 @router.post("/task-types") async def add_task_type(request: Request): try: data = await request.json() if not data.get("sn") or not data.get("label"): raise HTTPException(400, "SN和Label不能为空") await create_task_type(request.app.state.db_pool, data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 修改任务类型 @router.put("/task-types/{task_id}") async def modify_task_type(task_id: int, request: Request): try: update_data = await request.json() if not update_data: raise HTTPException(400, "无有效更新数据") await update_task_type(request.app.state.db_pool, task_id, update_data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 删除任务类型 @router.delete("/task-types/{task_id}") async def remove_task_type(task_id: int, request: Request): try: # 验证ID有效性 if not task_id or task_id <= 0: raise HTTPException(400, "无效的任务类型ID") # 执行删除操作 success = await delete_task_type(request.app.state.db_pool, task_id) if success: return {"status": "success", "message": "任务类型已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务信息 @router.get("/sse/tasks") async def sse_tasks(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 获取指令信息 @router.get("/sse/commands") async def sse_tasks(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } )

我有两段python代码,帮我增加一个接口,接口功能是查询v_iiot_log表,将表中sn,type,type_label,label,message数据返回到前端使用SSE实时显示,帮我用vue3+element写一个前端来实现这个接口,前端有一个下拉框,可以选择type,来显示不同类型的数据,后端地址为http://127.0.0.1:8888, 以下为services.pyd代码import json import asyncio from collections import deque # 在 service.py 中添加以下代码 async def command_match_event_generator(request): """SSE事件生成器,实时推送iiot_command_match表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_command_match表 commands = await conn.fetch( "SELECT id, sn, label, type, priority, task_type_sn, execute_json " "FROM iiot_command_match" ) # 格式化数据 formatted_data = [ { "id": c["id"], "sn": c["sn"], "label": c["label"], "type": c["type"], "priority": c["priority"], "task_type_sn": c["task_type_sn"], "execute_json": json.loads(c["execute_json"]) if c["execute_json"] != '-' else {} } for c in commands ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_command_match(pool, data: dict): """创建新指令匹配""" required_fields = ["sn", "label", "type", "priority", "task_type_sn", "execute_json"] if not all(field in data for field in required_fields): raise ValueError("缺少必要字段") async with pool.acquire() as conn: # 检查SN是否唯一 existing = await conn.fetchval( "SELECT 1 FROM iiot_command_match WHERE sn = $1", data["sn"] ) if existing: raise ValueError(f"SN {data['sn']} 已存在") # 插入新记录 await conn.execute( "INSERT INTO iiot_command_match(sn, label, type, priority, task_type_sn, execute_json) " "VALUES ($1, $2, $3, $4, $5, $6)", data["sn"], data["label"], data["type"], data["priority"], data["task_type_sn"], json.dumps(data["execute_json"]) ) async def update_command_match(pool, command_id: int, update_data: dict): """更新指令匹配信息""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 构建更新语句 query = "UPDATE iiot_command_match SET " params = [] updates = [] field_mapping = { "sn": "sn", "label": "label", "type": "type", "priority": "priority", "task_type_sn": "task_type_sn", "execute_json": "execute_json" } for field, db_field in field_mapping.items(): if field in update_data: updates.append(f"{db_field} = ${len(params) + 1}") # 特殊处理JSON字段 if field == "execute_json": params.append(json.dumps(update_data[field])) else: params.append(update_data[field]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(command_id) await conn.execute(query, *params) async def delete_command_match(pool, command_id: int): """删除指令匹配""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_command_match WHERE id = $1", command_id) return True # 添加删除任务类型功能 async def delete_task_type(pool, task_id: int): """删除任务类型""" async with pool.acquire() as conn: # 检查任务类型是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_task_type WHERE id = $1", task_id) if not exists: raise ValueError(f"任务类型ID {task_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_task_type WHERE id = $1", task_id) return True # service.py 新增代码 async def task_type_event_generator(request): """SSE事件生成器,实时推送iiot_task_type表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_task_type表 task_types = await conn.fetch("SELECT id, sn, label FROM iiot_task_type") # 格式化数据 formatted_data = [ {"id": t["id"], "sn": t["sn"], "label": t["label"]} for t in task_types ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_task_type(pool, data: dict): """创建新任务类型""" async with pool.acquire() as conn: await conn.execute( "INSERT INTO iiot_task_type(sn, label) VALUES ($1, $2)", data["sn"], data["label"] ) async def update_task_type(pool, task_id: int, update_data: dict): """更新任务类型信息""" async with pool.acquire() as conn: query = "UPDATE iiot_task_type SET " params = [] updates = [] if "sn" in update_data: updates.append("sn = $" + str(len(params) + 1)) params.append(update_data["sn"]) if "label" in update_data: updates.append("label = $" + str(len(params) + 1)) params.append(update_data["label"]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(task_id) await conn.execute(query, *params) # 新增:全局存储轮询结果 task_polling_results = deque(maxlen=100) # 存储最近100次轮询结果 # 新增:后台轮询任务 async def poll_iiot_task(pool): """后台轮询任务,每秒查询一次iiot_task表""" while True: try: async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" # 查询实际表而非视图 ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "id": t["id"], "sn": t["sn"], "status": t["status"], "create_time": t["create_time"].isoformat(), # 根据实际表结构添加其他字段 }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 存储结果(实际应用中可替换为数据库/缓存存储) task_polling_results.append({ "timestamp": asyncio.get_event_loop().time(), "data": tasks }) print(f"Polled {len(tasks)} tasks at {asyncio.get_event_loop().time()}") print(tasks) except Exception as e: print(f"Polling error: {str(e)}") await asyncio.sleep(1) # 每秒轮询一次 #获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" 以下为api.py代码from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator from fastapi import HTTPException from .services import task_type_event_generator, create_task_type, update_task_type, delete_task_type # 导入新增的删除函数 router = APIRouter() # 在 api.py 中添加以下路由 from .services import ( command_match_event_generator, create_command_match, update_command_match, delete_command_match ) # 指令匹配SSE推送 @router.get("/sse/command-match") async def sse_command_match(request: Request): return StreamingResponse( command_match_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 创建新指令匹配 @router.post("/command-match") async def add_command_match(request: Request): try: data = await request.json() await create_command_match(request.app.state.db_pool, data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 更新指令匹配 @router.put("/command-match/{command_id}") async def modify_command_match(command_id: int, request: Request): try: update_data = await request.json() await update_command_match(request.app.state.db_pool, command_id, update_data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 删除指令匹配 @router.delete("/command-match/{command_id}") async def remove_command_match(command_id: int, request: Request): try: success = await delete_command_match(request.app.state.db_pool, command_id) if success: return {"status": "success", "message": "指令匹配已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务类型 @router.get("/sse/task-types") async def sse_task_types(request: Request): return StreamingResponse( task_type_event_generator(request), media_type="text/event-stream", headers={"Cache-Control": "no-cache"} ) # 添加任务类型 @router.post("/task-types") async def add_task_type(request: Request): try: data = await request.json() if not data.get("sn") or not data.get("label"): raise HTTPException(400, "SN和Label不能为空") await create_task_type(request.app.state.db_pool, data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 修改任务类型 @router.put("/task-types/{task_id}") async def modify_task_type(task_id: int, request: Request): try: update_data = await request.json() if not update_data: raise HTTPException(400, "无有效更新数据") await update_task_type(request.app.state.db_pool, task_id, update_data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 删除任务类型 @router.delete("/task-types/{task_id}") async def remove_task_type(task_id: int, request: Request): try: # 验证ID有效性 if not task_id or task_id <= 0: raise HTTPException(400, "无效的任务类型ID") # 执行删除操作 success = await delete_task_type(request.app.state.db_pool, task_id) if success: return {"status": "success", "message": "任务类型已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务信息 @router.get("/sse/tasks") async def sse_tasks(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 获取指令信息 @router.get("/sse/commands") async def sse_tasks(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } )

我目前有两个py文件,帮我增加几个接口,一个接口是使用sse技术读取数据库iiot_task_type表的信息,可以实现前端页面的数据实时显示,iiot_task_type表中的数据有sn和label,第二个接口功能是新增iiot_task_type表的数据,第三个接口功能是修改iiot_task_type表的sn或者label信息,然后写一个前端页,来实现这些功能,后端接口IP是http://127.0.0.1:8888 ,以下为service.py的代码import json import asyncio from collections import deque # 新增:全局存储轮询结果 task_polling_results = deque(maxlen=100) # 存储最近100次轮询结果 # 新增:后台轮询任务 async def poll_iiot_task(pool): """后台轮询任务,每秒查询一次iiot_task表""" while True: try: async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" # 查询实际表而非视图 ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "id": t["id"], "sn": t["sn"], "status": t["status"], "create_time": t["create_time"].isoformat(), # 根据实际表结构添加其他字段 }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 存储结果(实际应用中可替换为数据库/缓存存储) task_polling_results.append({ "timestamp": asyncio.get_event_loop().time(), "data": tasks }) print(f"Polled {len(tasks)} tasks at {asyncio.get_event_loop().time()}") print(tasks) except Exception as e: print(f"Polling error: {str(e)}") await asyncio.sleep(1) # 每秒轮询一次 #获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" 下面是api.py的代码 from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator router = APIRouter() @router.get("/sse/tasks") async def sse_tasks(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) @router.get("/sse/commands") async def sse_tasks(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } )

目前我有个前端代码,现在的功能是显示iiot_command_match表的所有数据,增加一个下拉框,里面显示的iiot_task_type表中的所有sn,iiot_task_type中的sn,和iiot_command_match中的task_type_sn是对应的,我希望选中这个下拉框的值,显示的是跟这个SN相匹配的数据,另外增加数据时,其中有一个,任务类型SN,的位置,现在是手动输入,改成下拉框选,选择的项跟前面下拉框的数据一样,都是iiot_task_type的sn,后台接口目前我有这些功能的接口,不用新写,但我会把代码给你,这样前端你知道调用什么。以下为前端代码<template> <el-button type="primary" @click="handleAdd">添加新记录</el-button> <el-table :data="commandMatches" style="width: 100%" height="500"> <el-table-column prop="sn" label="SN" width="180" /> <el-table-column prop="label" label="标签" width="120" /> <el-table-column prop="type" label="类型" width="100" /> <el-table-column prop="priority" label="优先级" width="80" sortable /> <el-table-column prop="task_type_sn" label="任务类型SN" width="150" /> <el-table-column label="执行JSON" min-width="200"> <template #default="{ row }"> {{ JSON.stringify(row.execute_json, null, 2) }} </template> </el-table-column> <el-table-column label="操作" width="180" fixed="right"> <template #default="{ row }"> <el-button size="small" @click="handleEdit(row)">编辑</el-button> <el-button size="small" type="danger" @click="handleDelete(row.id)" >删除</el-button > </template> </el-table-column> </el-table> <el-dialog v-model="dialogVisible" :title="formTitle"> <el-form :model="form" label-width="120px"> <el-form-item label="SN" required> <el-input v-model="form.sn" /> </el-form-item> <el-form-item label="标签"> <el-input v-model="form.label" /> </el-form-item> <el-form-item label="类型"> <el-input v-model="form.type" /> </el-form-item> <el-form-item label="优先级"> <el-input-number v-model="form.priority" :min="1" :max="10" /> </el-form-item> <el-form-item label="任务类型SN"> <el-input v-model="form.task_type_sn" /> </el-form-item> <el-form-item label="执行JSON"> <el-input v-model="form.execute_json" type="textarea" :autosize="{ minRows: 4, maxRows: 8 }" placeholder='例如: {"command": "start", "params": {"speed": 100}}' /> </el-form-item> </el-form> <template #footer> <el-button @click="dialogVisible = false">取消</el-button> <el-button type="primary" @click="submitForm">确认</el-button> </template> </el-dialog> </template> <script setup> import { ref, onMounted, onBeforeUnmount } from "vue"; import { ElMessage, ElMessageBox } from "element-plus"; // 后端API地址 const API_BASE = "http://127.0.0.1:8888"; // 实时数据 const commandMatches = ref([]); let eventSource = null; // 表单相关 const dialogVisible = ref(false); const form = ref({ id: null, sn: "", label: "", type: "", priority: 5, task_type_sn: "", execute_json: "{}", }); const isEditMode = ref(false); const formTitle = ref("添加新指令匹配"); // 初始化SSE连接 const initSSE = () => { if (eventSource) eventSource.close(); eventSource = new EventSource(${API_BASE}/sse/command-match); eventSource.onmessage = (event) => { try { const data = JSON.parse(event.data); commandMatches.value = data; } catch (e) { console.error("SSE数据解析错误:", e); } }; eventSource.onerror = (err) => { console.error("SSE连接错误:", err); // 尝试重新连接 setTimeout(initSSE, 3000); }; }; // 添加新记录 const handleAdd = () => { form.value = { id: null, sn: "", label: "", type: "", priority: 5, task_type_sn: "", execute_json: "{}", }; isEditMode.value = false; formTitle.value = "添加新指令匹配"; dialogVisible.value = true; }; // 编辑记录 const handleEdit = (row) => { form.value = { id: row.id, sn: row.sn, label: row.label, type: row.type, priority: row.priority, task_type_sn: row.task_type_sn, execute_json: JSON.stringify(row.execute_json, null, 2), }; isEditMode.value = true; formTitle.value = "编辑指令匹配"; dialogVisible.value = true; }; // 删除记录 const handleDelete = async (id) => { try { await ElMessageBox.confirm("确定要删除这条记录吗?", "警告", { confirmButtonText: "确定", cancelButtonText: "取消", type: "warning", }); const response = await fetch(${API_BASE}/command-match/${id}, { method: "DELETE", }); if (response.ok) { ElMessage.success("删除成功"); } else { const error = await response.json(); throw new Error(error.detail || "删除失败"); } } catch (error) { ElMessage.error(error.message || "删除操作出错"); } }; // 提交表单 const submitForm = async () => { try { // 验证JSON格式 let executeJson; try { executeJson = JSON.parse(form.value.execute_json); } catch { throw new Error("执行JSON格式不正确"); } const payload = { ...form.value, execute_json: executeJson, }; const url = isEditMode.value ? ${API_BASE}/command-match/${form.value.id} : ${API_BASE}/command-match; const method = isEditMode.value ? "PUT" : "POST"; const response = await fetch(url, { method, headers: { "Content-Type": "application/json" }, body: JSON.stringify(payload), }); if (!response.ok) { const error = await response.json(); throw new Error(error.detail || "操作失败"); } ElMessage.success(isEditMode.value ? "更新成功" : "添加成功"); dialogVisible.value = false; } catch (error) { ElMessage.error(error.message || "操作出错"); } }; // 生命周期钩子 onMounted(() => { initSSE(); }); onBeforeUnmount(() => { if (eventSource) eventSource.close(); }); </script> <style scoped> .command-match-container { padding: 20px; background-color: #fff; border-radius: 4px; box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1); } </style> 以下为service.py代码 import json import asyncio from collections import deque # 在 service.py 中添加以下代码 async def command_match_event_generator(request): """SSE事件生成器,实时推送iiot_command_match表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_command_match表 commands = await conn.fetch( "SELECT id, sn, label, type, priority, task_type_sn, execute_json " "FROM iiot_command_match" ) # 格式化数据 formatted_data = [ { "id": c["id"], "sn": c["sn"], "label": c["label"], "type": c["type"], "priority": c["priority"], "task_type_sn": c["task_type_sn"], "execute_json": json.loads(c["execute_json"]) if c["execute_json"] != '-' else {} } for c in commands ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_command_match(pool, data: dict): """创建新指令匹配""" required_fields = ["sn", "label", "type", "priority", "task_type_sn", "execute_json"] if not all(field in data for field in required_fields): raise ValueError("缺少必要字段") async with pool.acquire() as conn: # 检查SN是否唯一 existing = await conn.fetchval( "SELECT 1 FROM iiot_command_match WHERE sn = $1", data["sn"] ) if existing: raise ValueError(f"SN {data['sn']} 已存在") # 插入新记录 await conn.execute( "INSERT INTO iiot_command_match(sn, label, type, priority, task_type_sn, execute_json) " "VALUES ($1, $2, $3, $4, $5, $6)", data["sn"], data["label"], data["type"], data["priority"], data["task_type_sn"], json.dumps(data["execute_json"]) ) async def update_command_match(pool, command_id: int, update_data: dict): """更新指令匹配信息""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 构建更新语句 query = "UPDATE iiot_command_match SET " params = [] updates = [] field_mapping = { "sn": "sn", "label": "label", "type": "type", "priority": "priority", "task_type_sn": "task_type_sn", "execute_json": "execute_json" } for field, db_field in field_mapping.items(): if field in update_data: updates.append(f"{db_field} = ${len(params) + 1}") # 特殊处理JSON字段 if field == "execute_json": params.append(json.dumps(update_data[field])) else: params.append(update_data[field]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(command_id) await conn.execute(query, *params) async def delete_command_match(pool, command_id: int): """删除指令匹配""" async with pool.acquire() as conn: # 检查记录是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_command_match WHERE id = $1", command_id) if not exists: raise ValueError(f"指令ID {command_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_command_match WHERE id = $1", command_id) return True # 添加删除任务类型功能 async def delete_task_type(pool, task_id: int): """删除任务类型""" async with pool.acquire() as conn: # 检查任务类型是否存在 exists = await conn.fetchval("SELECT 1 FROM iiot_task_type WHERE id = $1", task_id) if not exists: raise ValueError(f"任务类型ID {task_id} 不存在") # 执行删除操作 await conn.execute("DELETE FROM iiot_task_type WHERE id = $1", task_id) return True # service.py 新增代码 async def task_type_event_generator(request): """SSE事件生成器,实时推送iiot_task_type表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_task_type表 task_types = await conn.fetch("SELECT id, sn, label FROM iiot_task_type") # 格式化数据 formatted_data = [ {"id": t["id"], "sn": t["sn"], "label": t["label"]} for t in task_types ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_task_type(pool, data: dict): """创建新任务类型""" async with pool.acquire() as conn: await conn.execute( "INSERT INTO iiot_task_type(sn, label) VALUES ($1, $2)", data["sn"], data["label"] ) async def update_task_type(pool, task_id: int, update_data: dict): """更新任务类型信息""" async with pool.acquire() as conn: query = "UPDATE iiot_task_type SET " params = [] updates = [] if "sn" in update_data: updates.append("sn = $" + str(len(params) + 1)) params.append(update_data["sn"]) if "label" in update_data: updates.append("label = $" + str(len(params) + 1)) params.append(update_data["label"]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(task_id) await conn.execute(query, *params) # 新增:全局存储轮询结果 task_polling_results = deque(maxlen=100) # 存储最近100次轮询结果 # 新增:后台轮询任务 async def poll_iiot_task(pool): """后台轮询任务,每秒查询一次iiot_task表""" while True: try: async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" # 查询实际表而非视图 ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "id": t["id"], "sn": t["sn"], "status": t["status"], "create_time": t["create_time"].isoformat(), # 根据实际表结构添加其他字段 }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 存储结果(实际应用中可替换为数据库/缓存存储) task_polling_results.append({ "timestamp": asyncio.get_event_loop().time(), "data": tasks }) print(f"Polled {len(tasks)} tasks at {asyncio.get_event_loop().time()}") print(tasks) except Exception as e: print(f"Polling error: {str(e)}") await asyncio.sleep(1) # 每秒轮询一次 #获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" 以下为api.py代码 from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator from fastapi import HTTPException from .services import task_type_event_generator, create_task_type, update_task_type, delete_task_type # 导入新增的删除函数 router = APIRouter() # 在 api.py 中添加以下路由 from .services import ( command_match_event_generator, create_command_match, update_command_match, delete_command_match ) # 指令匹配SSE推送 @router.get("/sse/command-match") async def sse_command_match(request: Request): return StreamingResponse( command_match_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 创建新指令匹配 @router.post("/command-match") async def add_command_match(request: Request): try: data = await request.json() await create_command_match(request.app.state.db_pool, data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 更新指令匹配 @router.put("/command-match/{command_id}") async def modify_command_match(command_id: int, request: Request): try: update_data = await request.json() await update_command_match(request.app.state.db_pool, command_id, update_data) return {"status": "success"} except ValueError as ve: raise HTTPException(400, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 删除指令匹配 @router.delete("/command-match/{command_id}") async def remove_command_match(command_id: int, request: Request): try: success = await delete_command_match(request.app.state.db_pool, command_id) if success: return {"status": "success", "message": "指令匹配已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务类型 @router.get("/sse/task-types") async def sse_task_types(request: Request): return StreamingResponse( task_type_event_generator(request), media_type="text/event-stream", headers={"Cache-Control": "no-cache"} ) # 添加任务类型 @router.post("/task-types") async def add_task_type(request: Request): try: data = await request.json() if not data.get("sn") or not data.get("label"): raise HTTPException(400, "SN和Label不能为空") await create_task_type(request.app.state.db_pool, data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 修改任务类型 @router.put("/task-types/{task_id}") async def modify_task_type(task_id: int, request: Request): try: update_data = await request.json() if not update_data: raise HTTPException(400, "无有效更新数据") await update_task_type(request.app.state.db_pool, task_id, update_data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) # 删除任务类型 @router.delete("/task-types/{task_id}") async def remove_task_type(task_id: int, request: Request): try: # 验证ID有效性 if not task_id or task_id <= 0: raise HTTPException(400, "无效的任务类型ID") # 执行删除操作 success = await delete_task_type(request.app.state.db_pool, task_id) if success: return {"status": "success", "message": "任务类型已删除"} else: raise HTTPException(500, "删除操作未成功") except ValueError as ve: raise HTTPException(404, str(ve)) except Exception as e: raise HTTPException(500, str(e)) # 获取任务信息 @router.get("/sse/tasks") async def sse_tasks(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) # 获取指令信息 @router.get("/sse/commands") async def sse_tasks(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } )

我给你两个py文件代码,帮我增加一个写入数据库的接口功能,表名为iiot_task_type ,以下为services.py的代码import json import asyncio from collections import deque # 新增:全局存储轮询结果 task_polling_results = deque(maxlen=100) # 存储最近100次轮询结果 # 获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" #"SELECT id, sn, label, type, status, priority, " #"create_time, start_point, end_point " #"FROM v_iiot_task ORDER BY create_time DESC" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 获取任务配置(任务类型) async def taskType_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM iiot_task_type" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "id": str(t["id"]), "sn": str(t["sn"]), "label": str(t["label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 新增:后台轮询任务 async def poll_iiot_task(pool): """后台轮询任务,每秒查询一次iiot_task表""" while True: try: async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" # 查询实际表而非视图 ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "id": t["id"], "sn": t["sn"], "status": t["status"], "create_time": t["create_time"].isoformat(), # 根据实际表结构添加其他字段 }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 存储结果(实际应用中可替换为数据库/缓存存储) task_polling_results.append({ "timestamp": asyncio.get_event_loop().time(), "data": tasks }) print(f"Polled {len(tasks)} tasks at {asyncio.get_event_loop().time()}") print(tasks) except Exception as e: print(f"Polling error: {str(e)}") await asyncio.sleep(1) # 每秒轮询一次 以下为api.py的代码from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator from .services import taskType_event_generator router = APIRouter() @router.get("/sse/tasks") async def sse_read(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) @router.get("/sse/commands") async def sse_read(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) @router.get("/sse/taskType") async def sse_read(request: Request): return StreamingResponse( taskType_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } )

我这有4个py文件,现在的整体功能使用sse实时显示数据库中的数据,我现在想加一个功能,不用sse,轮询一秒一次,读取postgre中 iiot_task表中的数据,现有功能不变,以下为现有代码 api.py from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator router = APIRouter() @router.get("/sse/tasks") async def sse_tasks(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) @router.get("/sse/commands") async def sse_tasks(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) database.py import asyncpg from contextlib import asynccontextmanager DB_CONFIG = { "database": "iiot", "user": "postgres", "password": "123456", "host": "127.0.0.1", "port": "5000" } @asynccontextmanager async def lifespan(app): app.state.db_pool = await asyncpg.create_pool(**DB_CONFIG) yield await app.state.db_pool.close() main.py from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from .database import lifespan from .api import router app = FastAPI(lifespan=lifespan) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"] ) app.include_router(router) services.py import json import asyncio # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "start_point": str(t["start_point"]), "end_point": str(t["end_point"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" #获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" #"SELECT id, sn, label, type, status, priority, " #"create_time, start_point, end_point " #"FROM v_iiot_task ORDER BY create_time DESC" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "start_point": str(t["start_point"]), "end_point": str(t["end_point"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n"

我这有4个py文件,现在的整体功能使用sse实时显示数据库中的数据,我现在想加一个功能,不用sse,在后台自动轮询一秒一次,读取postgre中 iiot_task表中的数据,现有功能不变,以下为现有代码 api.py from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator router = APIRouter() @router.get("/sse/tasks") async def sse_tasks(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) @router.get("/sse/commands") async def sse_tasks(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) database.py import asyncpg from contextlib import asynccontextmanager DB_CONFIG = { "database": "iiot", "user": "postgres", "password": "123456", "host": "127.0.0.1", "port": "5000" } @asynccontextmanager async def lifespan(app): app.state.db_pool = await asyncpg.create_pool(**DB_CONFIG) yield await app.state.db_pool.close() main.py from fastapi import FastAPI from fastapi.middleware.cors import CORSMiddleware from .database import lifespan from .api import router app = FastAPI(lifespan=lifespan) app.add_middleware( CORSMiddleware, allow_origins=["*"], allow_credentials=True, allow_methods=["*"], allow_headers=["*"] ) app.include_router(router) services.py import json import asyncio # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "start_point": str(t["start_point"]), "end_point": str(t["end_point"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" #获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" #"SELECT id, sn, label, type, status, priority, " #"create_time, start_point, end_point " #"FROM v_iiot_task ORDER BY create_time DESC" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "start_point": str(t["start_point"]), "end_point": str(t["end_point"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n"

我创建的4张表,帮我建立一个视图,名字叫v_iiot_task , 添加iiot_task,iiot_command,iiot_status,iiot_task_type这4张表, 其中iiot_task表中的status 绑定 iiot_status的sn, iiot_task表中的current_command_sn绑定iiot_command的sn, iiot_task表中的type绑定iiot_task_type的sn, 以下为我创建4张表的sql CREATE TABLE IF NOT EXISTS iiot_task ( id SERIAL PRIMARY KEY, sn VARCHAR(100) UNIQUE NOT NULL, label VARCHAR(100) DEFAULT '-', --描述 type SMALLINT DEFAULT 0, --任务类型,有可能用不到 current_command_sn VARCHAR(100) DEFAULT 0, --当前指令sn status SMALLINT DEFAULT 0, --0:待执行,1:正在执行,2:取消,3:挂起,4:异常结束,5:完成 priority SMALLINT DEFAULT 5, --优先级0-10,数越高优先级越高 create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, --创建时间 completion_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, --完成时间 start_point VARCHAR(100) DEFAULT '-' NOT NULL, --起始点 end_point VARCHAR(100) DEFAULT '-' NOT NULL, --目标点 param VARCHAR(100) DEFAULT '-', --参数 param_extra_1 VARCHAR(100) DEFAULT '-', --额外参数1 param_extra_2 VARCHAR(100) DEFAULT '-', --额外参数2 param_extra_3 VARCHAR(100) DEFAULT '-', --额外参数3 param_extra_4 VARCHAR(100) DEFAULT '-', --额外参数4 param_extra_5 VARCHAR(100) DEFAULT '-' --额外参数5 ); CREATE TABLE IF NOT EXISTS iiot_command ( id SERIAL PRIMARY KEY, sn VARCHAR(100) UNIQUE NOT NULL, label VARCHAR(100) DEFAULT '-', --描述 type SMALLINT DEFAULT 0, --任务类型,有可能用不到 task_sn VARCHAR(100) DEFAULT 0, --当前指令sn status SMALLINT DEFAULT 0, --0:待执行,1:正在执行,2:取消,3:挂起,4:异常结束,5:完成 priority SMALLINT DEFAULT 1, --执行顺序 create_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, --创建时间 completion_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP, --完成时间 start_point VARCHAR(100) DEFAULT '-' NOT NULL, --起始点 end_point VARCHAR(100) DEFAULT '-' NOT NULL, --目标点 param VARCHAR(100) DEFAULT '-', --参数 param_extra_1 VARCHAR(100) DEFAULT '-', --额外参数1 param_extra_2 VARCHAR(100) DEFAULT '-', --额外参数2 param_extra_3 VARCHAR(100) DEFAULT '-', --额外参数3 param_extra_4 VARCHAR(100) DEFAULT '-', --额外参数4 param_extra_5 VARCHAR(100) DEFAULT '-' --额外参数5 ); CREATE TABLE IF NOT EXISTS iiot_status ( id SERIAL PRIMARY KEY, sn VARCHAR(100) UNIQUE NOT NULL, label VARCHAR(100) DEFAULT '-' ); CREATE TABLE IF NOT EXISTS iiot_task_type ( id SERIAL PRIMARY KEY, sn VARCHAR(100) UNIQUE NOT NULL, label VARCHAR(100) DEFAULT '-' );

这个前端页的删除功能,我后台目前没有,我把两个后台py给你,你帮我加一下,service.py的代码为import json import asyncio from collections import deque # service.py 新增代码 async def task_type_event_generator(request): """SSE事件生成器,实时推送iiot_task_type表变更""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): async with pool.acquire() as conn: # 查询iiot_task_type表 task_types = await conn.fetch("SELECT id, sn, label FROM iiot_task_type") # 格式化数据 formatted_data = [ {"id": t["id"], "sn": t["sn"], "label": t["label"]} for t in task_types ] # 生成SSE事件 yield f"data: {json.dumps(formatted_data)}\n\n" await asyncio.sleep(1) # 每秒更新 except Exception as e: yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" async def create_task_type(pool, data: dict): """创建新任务类型""" async with pool.acquire() as conn: await conn.execute( "INSERT INTO iiot_task_type(sn, label) VALUES ($1, $2)", data["sn"], data["label"] ) async def update_task_type(pool, task_id: int, update_data: dict): """更新任务类型信息""" async with pool.acquire() as conn: query = "UPDATE iiot_task_type SET " params = [] updates = [] if "sn" in update_data: updates.append("sn = $" + str(len(params) + 1)) params.append(update_data["sn"]) if "label" in update_data: updates.append("label = $" + str(len(params) + 1)) params.append(update_data["label"]) if not updates: return query += ", ".join(updates) + " WHERE id = $" + str(len(params) + 1) params.append(task_id) await conn.execute(query, *params) # 新增:全局存储轮询结果 task_polling_results = deque(maxlen=100) # 存储最近100次轮询结果 # 新增:后台轮询任务 async def poll_iiot_task(pool): """后台轮询任务,每秒查询一次iiot_task表""" while True: try: async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" # 查询实际表而非视图 ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "id": t["id"], "sn": t["sn"], "status": t["status"], "create_time": t["create_time"].isoformat(), # 根据实际表结构添加其他字段 }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 存储结果(实际应用中可替换为数据库/缓存存储) task_polling_results.append({ "timestamp": asyncio.get_event_loop().time(), "data": tasks }) print(f"Polled {len(tasks)} tasks at {asyncio.get_event_loop().time()}") print(tasks) except Exception as e: print(f"Polling error: {str(e)}") await asyncio.sleep(1) # 每秒轮询一次 #获取全部任务 async def task_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_task" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_type_label": str(t["task_type_label"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" # 获取全部指令 async def command_event_generator(request): """合并后的SSE事件生成器,包含数据库查询和数据转换逻辑""" pool = request.app.state.db_pool try: while not await request.is_disconnected(): # 直接执行数据库查询 async with pool.acquire() as conn: db_tasks = await conn.fetch( "SELECT * FROM v_iiot_command" ) # 处理查询结果 tasks = [] for t in db_tasks: try: tasks.append({ "label": str(t["label"]), "sn": str(t["sn"]), "task_sn": str(t["task_sn"]), "priority": int(t["priority"]), "create_time": t["create_time"].isoformat(), "status_label": str(t["status_label"]) }) except Exception as e: print(f"Error processing task {t.get('id', 'unknown')}: {str(e)}") # 生成SSE事件 yield f"data: {json.dumps(tasks)}\n\n" await asyncio.sleep(2) except Exception as e: # 异常处理 yield f"event: error\ndata: {json.dumps({'error': str(e)})}\n\n" api.py的代码为from fastapi import APIRouter, Request from fastapi.responses import StreamingResponse from .services import task_event_generator from .services import command_event_generator from fastapi import HTTPException from .services import task_type_event_generator, create_task_type, update_task_type router = APIRouter() @router.get("/sse/task-types") async def sse_task_types(request: Request): """实时获取任务类型数据流""" return StreamingResponse( task_type_event_generator(request), media_type="text/event-stream", headers={"Cache-Control": "no-cache"} ) @router.post("/task-types") async def add_task_type(request: Request): """添加新任务类型""" try: data = await request.json() if not data.get("sn") or not data.get("label"): raise HTTPException(400, "SN和Label不能为空") await create_task_type(request.app.state.db_pool, data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) @router.put("/task-types/{task_id}") async def modify_task_type(task_id: int, request: Request): """修改任务类型信息""" try: update_data = await request.json() if not update_data: raise HTTPException(400, "无有效更新数据") await update_task_type(request.app.state.db_pool, task_id, update_data) return {"status": "success"} except Exception as e: raise HTTPException(500, str(e)) @router.get("/sse/tasks") async def sse_tasks(request: Request): return StreamingResponse( task_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } ) @router.get("/sse/commands") async def sse_tasks(request: Request): return StreamingResponse( command_event_generator(request), media_type="text/event-stream", headers={ "Cache-Control": "no-cache", "Connection": "keep-alive", "X-Accel-Buffering": "no" } )

最新推荐

recommend-type

tika-parser-font-module-3.1.0.jar中文-英文对照文档.zip

1、压缩文件中包含: 中文-英文对照文档、jar包下载地址、Maven依赖、Gradle依赖、源代码下载地址。 2、使用方法: 解压最外层zip,再解压其中的zip包,双击 【index.html】 文件,即可用浏览器打开、进行查看。 3、特殊说明: (1)本文档为人性化翻译,精心制作,请放心使用; (2)只翻译了该翻译的内容,如:注释、说明、描述、用法讲解 等; (3)不该翻译的内容保持原样,如:类名、方法名、包名、类型、关键字、代码 等。 4、温馨提示: (1)为了防止解压后路径太长导致浏览器无法打开,推荐在解压时选择“解压到当前文件夹”(放心,自带文件夹,文件不会散落一地); (2)有时,一套Java组件会有多个jar,所以在下载前,请仔细阅读本篇描述,以确保这就是你需要的文件。 5、本文件关键字: jar中文-英文对照文档.zip,java,jar包,Maven,第三方jar包,组件,开源组件,第三方组件,Gradle,中文API文档,手册,开发手册,使用手册,参考手册。
recommend-type

perl-SelfLoader-1.23-420.el8.tar.gz

# 适用操作系统:Centos8 #Step1、解压 tar -zxvf xxx.el8.tar.gz #Step2、进入解压后的目录,执行安装 sudo rpm -ivh *.rpm
recommend-type

HTML时间格式化工具及测试页面介绍

标题 "BoolStudio.github.io" 暗示这是一个与GitHub相关的在线资源,具体来说是与BoolStudio相关的网页地址。GitHub是一个著名的代码托管平台,它支持Git版本控制系统,允许用户在云端存储和共享代码。BoolStudio可能是GitHub上的一个用户或组织账户名称,而该页面可能是他们托管的项目或个人页面的入口。 描述中的信息包含了HTML元素和JavaScript代码片段。这段描述展示了一个测试页文件的部分代码,涉及到HTML的标题(title)和内嵌框架(iframe)的使用,以及JavaScript中Date对象的扩展功能。 从描述中我们可以分析出以下知识点: 1. HTML标题(Title): 在HTML中,`<title>`标签用于定义网页的标题,它会显示在浏览器的标题栏或页面的标签上。在描述中出现了`<title>现在时间</title>`,这表明网页的标题被设置为了“现在时间”。 2. 微软时间: 这可能指的是在网页中嵌入微软产品的日期和时间显示。尽管这部分内容在描述中被删除了,但微软时间通常与Windows操作系统的日期和时间显示相关联。 3. iframe元素: `<iframe>`标签定义了一个内嵌框架,可以在网页中嵌入另一个文档。在描述中出现的是`<iframe src"></iframe>`,这表示创建了一个空的iframe元素,其src属性为空,实际上没有嵌入任何内容。通常src属性会被设置为另一个HTML文档的URL,用来在当前页面中显示外部页面的内容。 4. JavaScript日期格式化: 描述中包含了一段JavaScript代码,这段代码扩展了Date对象的功能,允许它根据提供的格式字符串(fmt)返回格式化的日期和时间。例如,如果fmt是'y年M月d日 h时m分s秒',则该函数会按照这个格式返回当前日期和时间。 具体到代码实现,以下步骤展示了如何在JavaScript中扩展Date对象并格式化日期: - 首先创建了一个对象o,该对象包含日期和时间的不同部分,例如年(y)、月(M)、日(d)、时(h)、分(m)、秒(s)。 - 使用正则表达式检查格式字符串fmt中是否包含年份的占位符(y+),如果存在则将其替换为四位数的年份,不足部分用0补齐。 - 使用for...in循环遍历对象o中的每一个键值对,并使用正则表达式测试这些键(如年、月、日等)是否在格式字符串中存在。如果存在,则替换为相应的日期时间值。 这个知识点展示了在JavaScript中如何自定义对象的方法,以及如何使用正则表达式进行字符串的搜索和替换。 标签 "HTML" 表明这个文件主要涉及到超文本标记语言(HTML),这是构建网页内容的标准标记语言,它允许开发者使用标签来定义网页的结构和内容。HTML文件通常包含各种元素,如段落、链接、图片、表格和表单等。 压缩包子文件的文件名称列表中的 "BoolStudio.github.io-main" 可能指的是一个包含 "BoolStudio.github.io" 网站主要文件的压缩包。通常,网站项目会包含多个文件和资源,为了便于管理和分发,开发者会将这些文件打包成一个压缩文件。在本例中,"main" 可能表示该压缩包包含了网站的主要文件和代码。 通过对给定文件信息的分析,我们可以了解到网页设计和开发的相关知识点,特别是HTML文档结构、JavaScript对象和函数扩展以及如何在网站项目中组织文件。这些知识对于前端开发者来说是非常重要的,能够帮助他们创建更加动态和功能丰富的网页应用。
recommend-type

Elixir测试:从用例执行到覆盖率分析

### Elixir 测试:从用例执行到覆盖率分析 #### 1. 测试用例执行 在测试中,以 `Test` 结尾且包含 `use ExUnit` 的模块被视为测试用例。测试用例本质上是设置回调和测试的集合。测试用例的执行方式有两种:并发执行或顺序执行。使用 `async: true` 选项的测试用例将并发执行,其余的则按定义顺序(默认随机)顺序执行。 测试用例的执行流程如下: 1. 执行所有 `setup_all` 回调。 2. 执行所有测试及其特定的设置和拆卸回调。 `setup_all` 回调按定义顺序在同一进程中执行。在运行任何测试之前,测试用例将生成一个进程,在该进程中运行所有
recommend-type

Android Studio 时间延时

<think> 我们参考多个引用,总结在Android Studio中实现时间延时的方法。根据引用[1]和[2],我们知道有几种常见的延时方法,包括使用Handler的postDelayed方法、使用Timer和TimerTask以及使用Thread.sleep。引用[3]和[5]则展示了具体代码示例。 具体方法如下: 1. **使用Handler的postDelayed方法**(推荐在主线程中使用,避免直接操作UI线程的问题): ```java new Handler().postDelayed(new Runnable() { @Override
recommend-type

IMS Open Corpus Workbench:打造高效大型文本语料库管理工具

IMS Open Corpus Workbench(以下简称CWB)是一个强大的开源工具集,它专门用于管理和查询大型的、带有语言注释的文本语料库。这项工具有着广泛的应用领域,包括语言学研究、自然语言处理、人文科学研究等。 ### 标题知识点: #### 大型文本语料库的索引和查询工具 大型文本语料库指的是含有大量文本数据的数据库,其中包含的文本量通常以百万计。这些数据可能是书面文本、口语录音文字转写等形式。对于如此庞大的数据集,索引是必要的,它可以帮助研究者快速定位到感兴趣的片段,而查询工具则提供了从这些大量数据中提取特定信息的能力。 #### 开源 CWB作为一个开源工具,意味着其源代码对所有人开放,并且可以免费使用和修改。开源项目通常是由社区驱动,有着活跃的开发者和用户群体,不断对工具进行改进和拓展。这种模式促进了创新,并且有利于长期维护和升级。 ### 描述知识点: #### 管理和查询带有语言注释的文本 在语料库中,文本数据经常会被加上各种形式的语言注释,比如句法结构、词性标注、语义角色等。CWB支持管理这类富含语言信息的语料库,使其不仅仅保存原始文本信息,还整合了深层的语言知识。此外,CWB提供了多种查询语言注释数据的方式,使得用户可以针对特定的注释信息进行精确查询。 #### 核心组件:CQP(Corpus Query Processor) CQP是CWB中的核心组件,是一个高度灵活和高效的查询处理器。它支持在终端会话中交互式地使用,这为熟悉命令行界面的用户提供了一个强大的工具。同时,CQP也可以嵌入到其他程序中,比如Perl脚本,从而提供编程式的语料库访问方式。这为高级用户提供了一个强大的平台,可以编写复杂的查询,并将查询结果集成到其他程序中。 #### 基于Web的GUI CQPweb 除了命令行界面外,CWB还提供了一个基于Web的图形用户界面CQPweb,使得不熟悉命令行的用户也能够方便地使用CWB的强大功能。CQPweb通常允许用户通过网页直接构建查询,并展示查询结果,极大地降低了使用门槛。 ### 标签知识点: #### 开源软件 CWB作为开源软件,其主要特点和优势包括: - **社区支持**:开放源代码鼓励了全球开发者共同参与,提供错误修正、功能增强、新特性开发等。 - **定制化**:用户可以根据自己的需求对源代码进行修改,从而实现定制化的功能。 - **透明性**:源代码的开放确保了软件工作的透明性,用户可以清楚了解软件的工作原理和数据处理方式。 - **可靠性**:由于代码的公开性,很多用户和开发者可以共同审查代码,提高了软件的可靠性和安全性。 - **成本效益**:开源软件通常不需要支付昂贵的许可费用,对预算有限的个人和机构特别友好。 ### 压缩包子文件的文件名称列表知识点: #### cwb-3.0.0-osx-10.5-universal 这个文件名提供了关于该软件包的重要信息: - **cwb**:表示这是IMS Open Corpus Workbench的软件包。 - **3.0.0**:表示这个包的版本号,了解版本信息对于获取支持、查看更新日志、了解新特性等方面很重要。 - **osx**:表示这个软件包是为Mac OS X操作系统设计的。 - **10.5**:这个数字指明了这个软件包支持的操作系统版本至少是Mac OS X 10.5。 - **universal**:表明这个软件包是为不同架构的处理器(比如32位和64位)设计的通用二进制文件,提高了软件包的兼容性和可移植性。 综上所述,IMS Open Corpus Workbench是一个为处理带有语言注释的大型文本语料库而设计的开源工具集,它以高效且灵活的查询处理器CQP为核心,提供了命令行和基于Web的两种交互方式,极大地促进了语言学和语言技术领域的研究与应用。由于其开源特性,CWB得到了广泛的使用和不断的改进。
recommend-type

基于属性测试的深入解析与策略探讨

### 基于属性测试的深入解析与策略探讨 #### 1. 基于属性测试中的收缩机制 在基于属性的测试中,当测试失败时,像 `stream_data` 这样的框架会执行收缩(Shrinking)操作。收缩的目的是简化导致测试失败的输入,同时确保简化后的输入仍然会使测试失败,这样能更方便地定位问题。 为了说明这一点,我们来看一个简单的排序函数测试示例。我们实现了一个糟糕的排序函数,实际上就是恒等函数,它只是原封不动地返回输入列表: ```elixir defmodule BadSortTest do use ExUnit.Case use ExUnitProperties pro
recommend-type

ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key && \

<think> 根据用户的问题要求,我需要详细解释命令`ssh-keygen -t rsa -f /etc/ssh/ssh_host_rsa_key`的含义、后续操作、常见问题及解决办法。同时,我需要参考提供的引用内容,并遵循系统级指令(如LaTeX格式、中文回答、生成相关问题等)。 首先,分析命令的组成部分: - `ssh-keygen`:生成、管理和转换SSH密钥的工具。 - `-t rsa`:指定密钥类型为RSA算法。 - `-f /etc/ssh/ssh_host_rsa_key`:指定生成的私钥文件路径为`/etc/ssh/ssh_host_rsa_key`。对应的公钥文件会在同一
recommend-type

挑战性开源平台游戏YAGAC:无故事忍者冒险

Y.A.G.A.C(Yet Another Great Arcade Classic),是一款免费的开源伪2D平台游戏,它在传统平台游戏的基础上融入了3D游戏元素,让玩家在一个拥有2D精灵的3D环境中进行操作。YAGAC游戏以其高挑战性和上瘾性而著称,吸引了众多游戏爱好者和编程高手的关注。 首先,让我们深入了解这款游戏的核心玩法。YAGAC的最大特点是在一个基本的2D平面内,玩家可以控制角色进行运动,但游戏环境却是3D制作的。这种设计为玩家带来了全新的视觉体验和操作感受。在YAGAC中,玩家扮演的是一个身手敏捷的忍者,任务是在错综复杂的地牢中生存下来,地牢充满了各种陷阱和敌人,如机器人等。为了逃生,玩家需要在各种关卡中寻找隐藏的彩球,这些彩球决定了玩家能够到达的区域范围。 在游戏过程中,收集到的彩球会改变对应颜色平台的属性,使原本脆弱的平台变得牢固,从而为玩家打开新的道路。这样的设计不仅考验玩家的反应和速度,还考验他们的策略和记忆能力。YAGAC的游戏关卡设计非常巧妙,经常需要玩家反复尝试,每一次尝试都可能发现新的线索和策略,这样的设计增加了游戏的重复可玩性。 YAGAC使用的引擎在游戏流畅性方面表现出色,这也是游戏的一大强项。一款游戏引擎的强大与否直接关系到游戏体验的好坏,YAGAC的开发团队选择或者开发了一个能够高效处理3D图形和2D动作的引擎,确保了游戏在各种配置的计算机上都能保持良好的运行状态和响应速度。 接下来,我们来探讨YAGAC的开源属性。由于YAGAC是开源的,这意味着游戏的源代码是开放的,任何个人或组织都可以访问、修改并重新分发该软件。开源软件通常由社区维护,并且鼓励用户贡献代码,共同改进游戏。对于像YAGAC这样的游戏来说,开源可以吸引更多的开发者参与进来,共同完善游戏体验。玩家和开发者可以对游戏进行本地化、修改游戏机制,甚至是增加新的内容和关卡。 开源平台游戏的概念不仅限于提供免费的游戏体验,它还鼓励创新和协作。开源文化促进知识共享和技术进步,这在软件开发领域尤为重要。同时,玩家也可以从中学到编程知识,因为游戏的开源性质允许用户查看和学习游戏背后的代码。 最后,关于YAGAC的文件名称“yagac”,这很可能是游戏的主程序文件名或者主目录名。当玩家在计算机上进行下载和安装时,可能会遇到这样的文件名,识别这一点有助于玩家快速定位和管理游戏文件。 总的来说,Y.A.G.A.C.作为一款开源平台游戏,在游戏玩法设计、开源文化和3D游戏引擎的流畅性等方面,都显示出其独特的优势。游戏的挑战性和上瘾性,以及社区驱动的开发模式,都为游戏爱好者和开源爱好者提供了一个理想的游戏和学习平台。对于对游戏开发感兴趣的玩家来说,YAGAC无疑是一个研究和实践的良好起点。
recommend-type

状态化属性测试与测试数据随机化及测试生命周期解析

# 状态化属性测试与测试数据随机化及测试生命周期解析 ## 状态化属性测试 ### 状态化系统测试的引入 之前我们主要探讨了针对纯无状态函数的属性测试,这类函数接收输入并返回输出。然而,属性测试同样适用于有状态系统的测试。有状态系统是指那些会携带状态的系统,例如数据库。 在之前的示例中,我们仅使用属性测试来生成数据,然后将其输入到代码中并对结果进行断言。但对于有状态系统,情况有所不同:我们需要处理状态的设置,并仅在系统处于特定状态时执行某些操作。 ### 对有状态系统进行建模 我们可以利用属性测试框架生成随机数据的能力,为有状态系统生成随机命令。例如,若有状态系统是数据库,我们就能生成针