Files
Story-extractor/backend/app/api/stories.py
2026-04-24 16:02:16 +08:00

65 lines
2.2 KiB
Python
Raw Permalink 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 typing import Annotated
from fastapi import APIRouter, HTTPException, Depends
from sqlalchemy.ext.asyncio import AsyncSession
from sqlalchemy import select, update
from app.database import get_db
from app.models.story import Story
from app.schemas.schemas import StoryOut, StoryEdit
router = APIRouter(prefix="/stories", tags=["故事管理"])
@router.get("", response_model=list[StoryOut])
async def list_stories(db: Annotated[AsyncSession, Depends(get_db)], status: str = "all"):
"""获取故事列表支持筛选all/matched/pending"""
query = select(Story).where(Story.match_status != "deleted")
if status == "matched":
query = query.where(Story.match_status == "matched")
elif status == "pending":
query = query.where(Story.match_status == "pending")
query = query.order_by(Story.created_at.desc())
result = await db.execute(query)
return result.scalars().all()
@router.get("/{story_id}", response_model=StoryOut)
async def get_story(story_id: str, db: Annotated[AsyncSession, Depends(get_db)]):
"""获取故事详情"""
story = await db.get(Story, story_id)
if not story or story.match_status == "deleted":
raise HTTPException(404, "故事不存在")
return story
@router.put("/{story_id}", response_model=StoryOut)
async def edit_story(story_id: str, data: StoryEdit, db: Annotated[AsyncSession, Depends(get_db)]):
"""编辑故事"""
story = await db.get(Story, story_id)
if not story or story.match_status == "deleted":
raise HTTPException(404, "故事不存在")
if data.title is not None:
story.title = data.title
if data.summary is not None:
story.summary = data.summary
if data.content is not None:
story.content = data.content
await db.commit()
await db.refresh(story)
return story
@router.delete("/{story_id}")
async def delete_story(story_id: str, db: Annotated[AsyncSession, Depends(get_db)]):
"""删除故事(标记为 deleted"""
story = await db.get(Story, story_id)
if not story or story.match_status == "deleted":
raise HTTPException(404, "故事不存在")
story.match_status = "deleted"
story.person_id = None
await db.commit()
return {"message": "已删除"}