from fastapi import APIRouter from typing import List from fastapi import APIRouter, HTTPException # from app.routers import get_cached_data from app.schemas.user import ChapterRelationCreate, ChapterRelationResponse from app.services.user_service import get_graph_relations, search_chapters, \ get_relations_to_level_simple, get_chapter_relations router = APIRouter( prefix="/chapters", tags=["Chapters"], ) @router.get("/relations/", response_model=List[ChapterRelationResponse]) async def list_chapter_relations(): # cache_key = "all_chapter_relations" # cached_data = get_cached_data(cache_key) # 从缓存获取 # if cached_data: # return [ChapterRelationResponse(**data) for data in cached_data] # 缓存命中,返回数据 """ 查询所有章节关系 """ return await get_graph_relations() @router.get("/search_chapters", response_model=List[ChapterRelationResponse]) async def search_chapters_endpoint(q: str): """ API 端点:根据搜索关键字模糊查询章节及其相关章节 :param q: 搜索关键字 :return: 匹配的章节关系列表 """ # cache_key = f"search_chapters:{q}" # # 尝试从缓存中获取数据 # cached_data = get_cached_data(cache_key) # if cached_data: # # 如果缓存命中,直接返回缓存中的数据 # return [ChapterRelationResponse(**data) for data in cached_data] if not q: raise HTTPException(status_code=400, detail="搜索关键字不能为空") results = await search_chapters(q) if not results: raise HTTPException(status_code=404, detail="未找到匹配的章节关系") return results @router.get("/relations/level/{level}", response_model=List[ChapterRelationResponse]) async def get_relations_by_level_simple(level: int): """ 简化版:根据目标层级查询从 Root 到目标层级的所有节点和关系 :param level: 目标层级(1 -> Root & Subject, 2 -> Root, Subject, Topic, ..., 5 -> Problem) :return: 对应层级的节点和关系 """ # cache_key = f"level_{level}_relations" # cached_data = get_cached_data(cache_key) # 从缓存获取 # if cached_data: # return [ChapterRelationResponse(**data) for data in cached_data] # 缓存命中,返回数据 if level < 0 or level > 5: raise HTTPException(status_code=400, detail="层级参数必须在 0 到 5 之间") try: relations = await get_relations_to_level_simple(level) if not relations: raise HTTPException(status_code=404, detail="未找到相关节点关系") return relations except ValueError as e: raise HTTPException(status_code=400, detail=str(e)) @router.get("/{chapter}/relations", response_model=List[ChapterRelationResponse]) async def get_relations_by_chapter(chapter: str): """ 根据章节名称获取该章节及其相关关系,但排除 label 为 Subject 的 next_SB 关系 :param chapter_name: 章节名称 :return: 章节关系列表 """ # cache_key = f"chapter_relations:{chapter}" # 不使用分页,直接根据章节名称生成缓存键 # cached_data = get_cached_data(cache_key) # 从缓存中获取数据 # if cached_data: # return [ChapterRelationResponse(**data) for data in cached_data] # 如果缓存命中,直接返回缓存数据 relations = await get_chapter_relations(chapter) if not relations: raise HTTPException(status_code=404, detail=f"No relations found for chapter {chapter}") return relations