from __future__ import annotations from datetime import datetime from typing import List from fastapi import APIRouter, HTTPException from pydantic import BaseModel from app.db import get_pool router = APIRouter(tags=["models"]) class ModelIn(BaseModel): name: str url: str class ModelOut(BaseModel): id: int name: str url: str created_at: datetime @router.get("/models", response_model=List[ModelOut]) async def list_models() -> List[ModelOut]: pool = get_pool() async with pool.acquire() as conn: rows = await conn.fetch("SELECT id, name, url, created_at FROM models ORDER BY created_at DESC") return [ModelOut(**dict(r)) for r in rows] @router.post("/models", response_model=ModelOut, status_code=201) async def create_model(body: ModelIn) -> ModelOut: pool = get_pool() async with pool.acquire() as conn: try: row = await conn.fetchrow( "INSERT INTO models (name, url) VALUES ($1, $2) RETURNING id, name, url, created_at", body.name, body.url, ) except Exception: raise HTTPException(status_code=409, detail="该 URL 已存在") return ModelOut(**dict(row)) @router.delete("/models/{model_id}", status_code=204) async def delete_model(model_id: int) -> None: pool = get_pool() async with pool.acquire() as conn: result = await conn.execute("DELETE FROM models WHERE id = $1", model_id) if result == "DELETE 0": raise HTTPException(status_code=404, detail="模型不存在")