优化代码风格

This commit is contained in:
ZZX9599
2025-09-08 17:34:23 +08:00
parent 9b3d20511a
commit 8ceb92c572
20 changed files with 223 additions and 192 deletions

View File

@ -1,4 +1,4 @@
from fastapi import APIRouter, Query
from fastapi import APIRouter, Query, Path
from mysql.connector import Error as MySQLError
from ds.db import db
@ -9,7 +9,6 @@ from schema.device_action_schema import (
)
from schema.response_schema import APIResponse
# 路由配置
router = APIRouter(
prefix="/device/actions",
@ -18,11 +17,11 @@ router = APIRouter(
# ------------------------------
# 内部方法新增设备操作记录适配id自增
# 内部方法: 新增设备操作记录适配id自增
# ------------------------------
def add_device_action(action_data: DeviceActionCreate) -> DeviceActionResponse:
"""
新增设备操作记录(内部方法非接口)
新增设备操作记录(内部方法非接口)
:param action_data: 含client_ip和action0/1
:return: 新增的完整记录
"""
@ -32,7 +31,7 @@ def add_device_action(action_data: DeviceActionCreate) -> DeviceActionResponse:
conn = db.get_connection()
cursor = conn.cursor(dictionary=True)
# 插入SQLid自增依赖数据库自动生成)
# 插入SQLid自增依赖数据库自动生成)
insert_query = """
INSERT INTO device_action
(client_ip, action, created_at, updated_at)
@ -54,20 +53,20 @@ def add_device_action(action_data: DeviceActionCreate) -> DeviceActionResponse:
except MySQLError as e:
if conn:
conn.rollback()
raise Exception(f"新增记录失败{str(e)}") from e
raise Exception(f"新增记录失败: {str(e)}") from e
finally:
db.close_connection(conn, cursor)
# ------------------------------
# 接口分页查询操作记录列表(仅返回 total + device_actions
# 接口: 分页查询操作记录列表(仅返回 total + device_actions
# ------------------------------
@router.get("/list", response_model=APIResponse, summary="分页查询设备操作记录")
async def get_device_action_list(
page: int = Query(1, ge=1, description="页码默认1"),
page_size: int = Query(10, ge=1, le=100, description="每页条数1-100"),
page: int = Query(1, ge=1, description="页码默认1"),
page_size: int = Query(10, ge=1, le=100, description="每页条数1-100"),
client_ip: str = Query(None, description="按客户端IP筛选"),
action: int = Query(None, ge=0, le=1, description="按状态筛选0=离线1=上线)")
action: int = Query(None, ge=0, le=1, description="按状态筛选0=离线1=上线)")
):
conn = None
cursor = None
@ -75,7 +74,7 @@ async def get_device_action_list(
conn = db.get_connection()
cursor = conn.cursor(dictionary=True)
# 1. 构建筛选条件(参数化查询避免注入)
# 1. 构建筛选条件(参数化查询避免注入)
where_clause = []
params = []
if client_ip:
@ -92,13 +91,13 @@ async def get_device_action_list(
cursor.execute(count_sql, params)
total = cursor.fetchone()["total"]
# 3. 分页查询记录(按创建时间倒序确保最新记录在前)
# 3. 分页查询记录(按创建时间倒序确保最新记录在前)
offset = (page - 1) * page_size
list_sql = "SELECT * FROM device_action"
if where_clause:
list_sql += " WHERE " + " AND ".join(where_clause)
list_sql += " ORDER BY created_at DESC LIMIT %s OFFSET %s"
params.extend([page_size, offset]) # 追加分页参数page/page_size仅用于查询不返回)
params.extend([page_size, offset]) # 追加分页参数page/page_size仅用于查询不返回)
cursor.execute(list_sql, params)
action_list = cursor.fetchall()
@ -114,6 +113,46 @@ async def get_device_action_list(
)
except MySQLError as e:
raise Exception(f"查询记录失败{str(e)}") from e
raise Exception(f"查询记录失败: {str(e)}") from e
finally:
db.close_connection(conn, cursor)
db.close_connection(conn, cursor)
@router.get("/{client_ip}", response_model=APIResponse, summary="根据IP查询设备操作记录")
async def get_device_actions_by_ip(
client_ip: str = Path(..., description="客户端IP地址")
):
conn = None
cursor = None
try:
conn = db.get_connection()
cursor = conn.cursor(dictionary=True)
# 1. 查询总记录数
count_sql = "SELECT COUNT(*) AS total FROM device_action WHERE client_ip = %s"
cursor.execute(count_sql, (client_ip,))
total = cursor.fetchone()["total"]
# 2. 查询该IP的所有记录按创建时间倒序
list_sql = """
SELECT * FROM device_action
WHERE client_ip = %s
ORDER BY created_at DESC
"""
cursor.execute(list_sql, (client_ip,))
action_list = cursor.fetchall()
# 3. 返回结果
return APIResponse(
code=200,
message="查询成功",
data=DeviceActionListResponse(
total=total,
device_actions=[DeviceActionResponse(**item) for item in action_list]
)
)
except MySQLError as e:
raise Exception(f"查询记录失败: {str(e)}") from e
finally:
db.close_connection(conn, cursor)