models.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. from __future__ import annotations
  2. from datetime import datetime
  3. from typing import List
  4. from fastapi import APIRouter, HTTPException
  5. from pydantic import BaseModel
  6. from app.db import get_pool
  7. router = APIRouter(tags=["models"])
  8. class ModelIn(BaseModel):
  9. name: str
  10. url: str
  11. class ModelOut(BaseModel):
  12. id: int
  13. name: str
  14. url: str
  15. created_at: datetime
  16. @router.get("/models", response_model=List[ModelOut])
  17. async def list_models() -> List[ModelOut]:
  18. pool = get_pool()
  19. async with pool.acquire() as conn:
  20. rows = await conn.fetch("SELECT id, name, url, created_at FROM models ORDER BY created_at DESC")
  21. return [ModelOut(**dict(r)) for r in rows]
  22. @router.post("/models", response_model=ModelOut, status_code=201)
  23. async def create_model(body: ModelIn) -> ModelOut:
  24. pool = get_pool()
  25. async with pool.acquire() as conn:
  26. try:
  27. row = await conn.fetchrow(
  28. "INSERT INTO models (name, url) VALUES ($1, $2) RETURNING id, name, url, created_at",
  29. body.name, body.url,
  30. )
  31. except Exception:
  32. raise HTTPException(status_code=409, detail="该 URL 已存在")
  33. return ModelOut(**dict(row))
  34. @router.delete("/models/{model_id}", status_code=204)
  35. async def delete_model(model_id: int) -> None:
  36. pool = get_pool()
  37. async with pool.acquire() as conn:
  38. result = await conn.execute("DELETE FROM models WHERE id = $1", model_id)
  39. if result == "DELETE 0":
  40. raise HTTPException(status_code=404, detail="模型不存在")