Files
video_detect/service/device_danger_service.py
2025-09-30 17:17:20 +08:00

79 lines
2.6 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

from mysql.connector import Error as MySQLError
from ds.db import db
from schema.device_danger_schema import DeviceDangerCreateRequest, DeviceDangerResponse
# ------------------------------
# 内部工具方法 - 检查设备是否存在(复用设备表逻辑)
# ------------------------------
def check_device_exist(client_ip: str) -> bool:
"""
检查指定IP的设备是否在devices表中存在
:param client_ip: 设备IP地址
:return: 存在返回True、不存在返回False
"""
if not client_ip:
raise ValueError("设备IP不能为空")
conn = None
cursor = None
try:
conn = db.get_connection()
cursor = conn.cursor(dictionary=True)
cursor.execute("SELECT id FROM devices WHERE client_ip = %s", (client_ip,))
return cursor.fetchone() is not None
except MySQLError as e:
raise Exception(f"检查设备存在性失败: {str(e)}") from e
finally:
db.close_connection(conn, cursor)
# ------------------------------
# 内部工具方法 - 创建设备危险记录(核心插入逻辑)
# ------------------------------
def create_danger_record(danger_data: DeviceDangerCreateRequest) -> DeviceDangerResponse:
"""
内部工具方法向device_danger表插入新的危险记录
:param danger_data: 危险记录创建请求数据
:return: 创建成功的危险记录模型对象
"""
# 先检查设备是否存在
if not check_device_exist(danger_data.client_ip):
raise ValueError(f"IP为 {danger_data.client_ip} 的设备不存在、无法创建危险记录")
conn = None
cursor = None
try:
conn = db.get_connection()
cursor = conn.cursor(dictionary=True)
# 插入危险记录id自增、时间自动填充
insert_query = """
INSERT INTO device_danger
(client_ip, type, result, created_at, updated_at)
VALUES (%s, %s, %s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
"""
cursor.execute(insert_query, (
danger_data.client_ip,
danger_data.type,
danger_data.result
))
conn.commit()
# 获取刚创建的记录用自增ID查询
danger_id = cursor.lastrowid
cursor.execute("SELECT * FROM device_danger WHERE id = %s", (danger_id,))
new_danger = cursor.fetchone()
return DeviceDangerResponse(**new_danger)
except MySQLError as e:
if conn:
conn.rollback()
raise Exception(f"插入危险记录失败: {str(e)}") from e
finally:
db.close_connection(conn, cursor)