Initial commit: 浼佷笟寰俊 AI 鏈哄櫒浜哄姪鐞?MVP
Co-authored-by: Cursor <cursoragent@cursor.com>
This commit is contained in:
53
backend/app/routers/sessions.py
Normal file
53
backend/app/routers/sessions.py
Normal file
@@ -0,0 +1,53 @@
|
||||
"""会话列表与消息:从 DB 读取,需登录。"""
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from app.database import get_db
|
||||
from app.deps import get_current_user_id
|
||||
from app.logging_config import get_trace_id
|
||||
from app.models import ChatSession, Message
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
|
||||
def _session_row(s: ChatSession) -> dict:
|
||||
return {
|
||||
"id": s.id,
|
||||
"external_user_id": s.external_user_id,
|
||||
"external_name": s.external_name,
|
||||
"status": s.status,
|
||||
"created_at": s.created_at.isoformat() if s.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
def _message_row(m: Message) -> dict:
|
||||
return {
|
||||
"id": m.id,
|
||||
"role": m.role,
|
||||
"content": m.content,
|
||||
"created_at": m.created_at.isoformat() if m.created_at else None,
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_sessions(
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_user: str = Depends(get_current_user_id),
|
||||
):
|
||||
"""会话列表。"""
|
||||
r = await db.execute(select(ChatSession).order_by(ChatSession.updated_at.desc()))
|
||||
rows = r.scalars().all()
|
||||
return {"code": 0, "message": "ok", "data": [_session_row(s) for s in rows], "trace_id": get_trace_id()}
|
||||
|
||||
|
||||
@router.get("/{session_id}/messages")
|
||||
async def list_messages(
|
||||
session_id: int,
|
||||
db: AsyncSession = Depends(get_db),
|
||||
_user: str = Depends(get_current_user_id),
|
||||
):
|
||||
"""某会话消息列表。"""
|
||||
r = await db.execute(select(Message).where(Message.session_id == session_id).order_by(Message.id))
|
||||
rows = r.scalars().all()
|
||||
return {"code": 0, "message": "ok", "data": [_message_row(m) for m in rows], "trace_id": get_trace_id()}
|
||||
Reference in New Issue
Block a user