models.py 1.6 KB

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