模型添加置信度设置,敏感词分页

This commit is contained in:
2025-09-15 17:43:36 +08:00
parent d9192bd964
commit 5959f9994c
4 changed files with 156 additions and 81 deletions

View File

@ -1,8 +1,14 @@
from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Query
from mysql.connector import Error as MySQLError
from typing import Optional
from ds.db import db
from schema.sensitive_schema import SensitiveCreateRequest, SensitiveUpdateRequest, SensitiveResponse
from schema.sensitive_schema import (
SensitiveCreateRequest,
SensitiveUpdateRequest,
SensitiveResponse,
SensitiveListResponse # 导入新增的分页响应模型
)
from schema.response_schema import APIResponse
from middle.auth_middleware import get_current_user
from schema.user_schema import UserResponse
@ -19,9 +25,11 @@ router = APIRouter(
# ------------------------------
@router.post("", response_model=APIResponse, summary="创建敏感信息记录")
async def create_sensitive(
sensitive: SensitiveCreateRequest): # 添加了登录认证依赖
sensitive: SensitiveCreateRequest,
current_user: UserResponse = Depends(get_current_user) # 补充登录认证依赖(与其他接口保持一致)
):
"""
创建敏感信息记录:
创建敏感信息记录:
- 需登录认证
- 插入新的敏感信息记录到数据库ID由数据库自动生成
- 返回创建成功信息
@ -34,8 +42,8 @@ async def create_sensitive(
# 插入新敏感信息记录到数据库不包含ID、由数据库自动生成
insert_query = """
INSERT INTO sensitives (name)
VALUES (%s)
INSERT INTO sensitives (name, created_at, updated_at)
VALUES (%s, CURRENT_TIMESTAMP, CURRENT_TIMESTAMP)
"""
cursor.execute(insert_query, (sensitive.name,))
conn.commit()
@ -56,12 +64,14 @@ async def create_sensitive(
except MySQLError as e:
if conn:
conn.rollback()
raise Exception(f"创建敏感信息记录失败: {str(e)}") from e
raise HTTPException(
status_code=500,
detail=f"创建敏感信息记录失败: {str(e)}"
) from e
finally:
db.close_connection(conn, cursor)
# 以下接口代码保持不变
# ------------------------------
# 2. 获取单个敏感信息记录
# ------------------------------
@ -71,7 +81,7 @@ async def get_sensitive(
current_user: UserResponse = Depends(get_current_user) # 需登录认证
):
"""
获取单个敏感信息记录:
获取单个敏感信息记录:
- 需登录认证
- 根据ID查询敏感信息记录
- 返回查询到的敏感信息
@ -98,21 +108,29 @@ async def get_sensitive(
data=SensitiveResponse(**sensitive)
)
except MySQLError as e:
raise Exception(f"查询敏感信息记录失败: {str(e)}") from e
raise HTTPException(
status_code=500,
detail=f"查询敏感信息记录失败: {str(e)}"
) from e
finally:
db.close_connection(conn, cursor)
# ------------------------------
# 3. 获取所有敏感信息记录
# 3. 获取敏感信息分页列表(重构:支持分页+关键词搜索)
# ------------------------------
@router.get("", response_model=APIResponse, summary="获取所有敏感信息记录")
async def get_all_sensitives():
@router.get("", response_model=APIResponse, summary="获取敏感信息分页列表(支持关键词搜索)")
async def get_sensitive_list(
page: int = Query(1, ge=1, description="页码默认1最小1"),
page_size: int = Query(10, ge=1, le=100, description="每页条数默认101-100"),
name: Optional[str] = Query(None, description="敏感词关键词搜索(模糊匹配)"),
current_user: UserResponse = Depends(get_current_user) # 需登录认证
):
"""
获取所有敏感信息记录:
获取敏感信息分页列表:
- 需登录认证
- 查询所有敏感信息记录(不需要分页
- 返回所有敏感信息列表
- 支持分页page/page_size和敏感词关键词模糊搜索name
- 返回总记录数+当前页数据
"""
conn = None
cursor = None
@ -120,17 +138,49 @@ async def get_all_sensitives():
conn = db.get_connection()
cursor = conn.cursor(dictionary=True)
query = "SELECT * FROM sensitives ORDER BY id"
cursor.execute(query)
sensitives = cursor.fetchall()
# 1. 构建查询条件(支持关键词搜索)
where_clause = []
params = []
if name:
where_clause.append("name LIKE %s")
params.append(f"%{name}%") # 模糊匹配关键词
# 2. 查询总记录数(用于分页计算)
count_sql = "SELECT COUNT(*) AS total FROM sensitives"
if where_clause:
count_sql += " WHERE " + " AND ".join(where_clause)
cursor.execute(count_sql, params.copy()) # 复制参数列表,避免后续污染
total = cursor.fetchone()["total"]
# 3. 计算分页偏移量
offset = (page - 1) * page_size
# 4. 分页查询敏感词数据(按更新时间倒序,最新的在前)
list_sql = "SELECT * FROM sensitives"
if where_clause:
list_sql += " WHERE " + " AND ".join(where_clause)
# 排序+分页LIMIT 条数 OFFSET 偏移量)
list_sql += " ORDER BY updated_at DESC LIMIT %s OFFSET %s"
# 补充分页参数page_size和offset
params.extend([page_size, offset])
cursor.execute(list_sql, params)
sensitive_list = cursor.fetchall()
# 5. 构造分页响应数据
return APIResponse(
code=200,
message="所有敏感信息记录查询成功",
data=[SensitiveResponse(**sensitive) for sensitive in sensitives]
message=f"敏感信息列表查询成功(共{total}条记录,当前第{page}页)",
data=SensitiveListResponse(
total=total,
sensitives=[SensitiveResponse(**item) for item in sensitive_list]
)
)
except MySQLError as e:
raise Exception(f"查询所有敏感信息记录失败: {str(e)}") from e
raise HTTPException(
status_code=500,
detail=f"查询敏感信息列表失败: {str(e)}"
) from e
finally:
db.close_connection(conn, cursor)
@ -145,7 +195,7 @@ async def update_sensitive(
current_user: UserResponse = Depends(get_current_user) # 需登录认证
):
"""
更新敏感信息记录:
更新敏感信息记录:
- 需登录认证
- 根据ID更新敏感信息记录
- 返回更新后的敏感信息
@ -177,14 +227,16 @@ async def update_sensitive(
if not update_fields:
raise HTTPException(
status_code=400,
detail="至少需要提供一个字段进行更新"
detail="至少需要提供一个字段进行更新name"
)
params.append(sensitive_id) # WHERE条件参数
# 补充更新时间和WHERE条件参数
update_fields.append("updated_at = CURRENT_TIMESTAMP")
params.append(sensitive_id)
update_query = f"""
UPDATE sensitives
SET {', '.join(update_fields)}, updated_at = CURRENT_TIMESTAMP
SET {', '.join(update_fields)}
WHERE id = %s
"""
cursor.execute(update_query, params)
@ -203,7 +255,10 @@ async def update_sensitive(
except MySQLError as e:
if conn:
conn.rollback()
raise Exception(f"更新敏感信息记录失败: {str(e)}") from e
raise HTTPException(
status_code=500,
detail=f"更新敏感信息记录失败: {str(e)}"
) from e
finally:
db.close_connection(conn, cursor)
@ -217,7 +272,7 @@ async def delete_sensitive(
current_user: UserResponse = Depends(get_current_user) # 需登录认证
):
"""
删除敏感信息记录:
删除敏感信息记录:
- 需登录认证
- 根据ID删除敏感信息记录
- 返回删除成功信息
@ -251,14 +306,20 @@ async def delete_sensitive(
except MySQLError as e:
if conn:
conn.rollback()
raise Exception(f"删除敏感信息记录失败: {str(e)}") from e
raise HTTPException(
status_code=500,
detail=f"删除敏感信息记录失败: {str(e)}"
) from e
finally:
db.close_connection(conn, cursor)
# ------------------------------
# 6. 业务辅助函数:获取所有敏感词(供其他模块调用)
# ------------------------------
def get_all_sensitive_words() -> list[str]:
"""
获取所有敏感词返回字符串数组
获取所有敏感词返回字符串列表,用于过滤业务)
返回:
list[str]: 包含所有敏感词的数组
@ -273,17 +334,17 @@ def get_all_sensitive_words() -> list[str]:
conn = db.get_connection()
cursor = conn.cursor(dictionary=True)
# 执行查询只获取敏感词字段
# 执行查询只获取敏感词字段按ID排序
query = "SELECT name FROM sensitives ORDER BY id"
cursor.execute(query)
sensitive_records = cursor.fetchall()
# 提取敏感词到数组
# 提取敏感词到纯字符串数组
return [record['name'] for record in sensitive_records]
except MySQLError as e:
# 数据库错误处理
raise MySQLError(f"查询敏感词失败: {str(e)}") from e
# 数据库错误向上抛出,由调用方处理
raise MySQLError(f"查询敏感词列表失败: {str(e)}") from e
finally:
# 确保资源正确释放
# 确保数据库连接正确释放
db.close_connection(conn, cursor)