Commit b5ca2246 authored by uuo00_n's avatar uuo00_n

fix(services): 修复敏感词记录中用户ID和对话ID的类型转换问题

refactor(services): 重构敏感词记录功能以包含详细敏感词信息
refactor(cors): 根据配置动态设置CORS允许的源和凭证
style: 移除不必要的注释和空行
parent 59d1878e
......@@ -15,8 +15,6 @@ from app.services.sensitive_word import (
delete_category, bulk_import_sensitive_words
)
from app.models.sensitive_word import SENSITIVE_WORD_CATEGORIES, SENSITIVE_WORD_SUBCATEGORIES
# 在路由层挂载版别运行模式依赖,确保仅在当前模式的版别下进行管理操作
router = APIRouter(dependencies=[Depends(require_edition_for_mode())])
@router.post("/sensitive-words", response_model=dict, status_code=status.HTTP_201_CREATED)
......@@ -109,14 +107,6 @@ async def list_sensitive_words(
max_severity: Optional[int] = None,
_: dict = Depends(get_current_admin_user)
):
"""获取所有敏感词(仅管理员)
可选筛选参数:
- category: 主分类
- subcategory: 子分类
- min_severity: 最小严重程度
- max_severity: 最大严重程度
"""
return await get_all_sensitive_words(category, subcategory, min_severity, max_severity)
@router.get("/sensitive-records", response_model=List[SensitiveRecordResponse])
......
......@@ -29,4 +29,3 @@ class Settings(BaseSettings):
# 注意:不再提供混合模式(mixed),如需混合请显式设置并在依赖中放行
APP_MODE: str = os.getenv("APP_MODE", "edu")
settings = Settings()
\ No newline at end of file
......@@ -31,11 +31,13 @@ app = FastAPI(
redoc_url=None # 禁用默认的/redoc
)
# 配置CORS
origins_cfg = settings.CORS_ALLOWED_ORIGINS
origins = [o.strip() for o in origins_cfg.split(",") if o.strip()] if origins_cfg and origins_cfg != "*" else ["*"]
allow_credentials = False if origins == ["*"] else True
app.add_middleware(
CORSMiddleware,
allow_origins=["*"], # 在生产环境中应该限制为特定域名
allow_credentials=True,
allow_origins=origins,
allow_credentials=allow_credentials,
allow_methods=["*"],
allow_headers=["*"],
)
......@@ -55,13 +57,11 @@ app.include_router(api_router, prefix=settings.API_V1_STR)
@app.on_event("startup")
async def startup_db_client():
"""应用启动时连接数据库并加载敏感词"""
await connect_to_mongo()
await sensitive_word_filter.load_sensitive_words()
@app.on_event("shutdown")
async def shutdown_db_client():
"""应用关闭时断开数据库连接"""
await close_mongo_connection()
@app.get("/")
......
......@@ -69,16 +69,31 @@ async def add_message(conversation_id: str, user_id: str, content: str) -> Dict[
# 如果包含敏感词,记录并返回拒绝回复
if contains_sensitive:
# 创建敏感词记录
# 补充敏感词详细信息
detailed_words = []
if sensitive_words:
cursor = db.db.sensitive_words.find({"word": {"$in": sensitive_words}})
async for doc in cursor:
detailed_words.append({
"word": doc.get("word"),
"category": doc.get("category"),
"subcategory": doc.get("subcategory"),
"severity": doc.get("severity", 1),
})
highest = highest_severity
if detailed_words:
highest = max([dw.get("severity", 1) for dw in detailed_words])
# 创建敏感词记录(包含详细信息)
sensitive_record = {
"user_id": ObjectId(user_id),
"conversation_id": ObjectId(conversation_id),
"message_content": content,
"sensitive_words_found": sensitive_words,
"highest_severity": highest_severity,
"sensitive_words_found": detailed_words,
"highest_severity": highest,
"timestamp": datetime.now()
}
await db.db.sensitive_records.insert_one(sensitive_record)
# 创建系统回复
......
......@@ -168,11 +168,17 @@ async def get_sensitive_records(
# 按用户ID筛选
if user_id:
query["user_id"] = user_id
try:
query["user_id"] = ObjectId(user_id)
except Exception:
query["user_id"] = user_id
# 按对话ID筛选
if conversation_id:
query["conversation_id"] = conversation_id
try:
query["conversation_id"] = ObjectId(conversation_id)
except Exception:
query["conversation_id"] = conversation_id
# 按时间范围筛选
if start_date and end_date:
......@@ -203,10 +209,10 @@ async def get_sensitive_records(
async for document in cursor:
records.append({
"id": str(document["_id"]),
"user_id": document["user_id"],
"conversation_id": document["conversation_id"],
"user_id": str(document["user_id"]),
"conversation_id": str(document["conversation_id"]),
"message_content": document["message_content"],
"sensitive_words_found": document["sensitive_words_found"],
"sensitive_words_found": document.get("sensitive_words_found", []),
"highest_severity": document.get("highest_severity", 1),
"timestamp": document["timestamp"]
})
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment