public.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. from __future__ import annotations
  2. from datetime import datetime
  3. from typing import List, Optional
  4. import json
  5. from fastapi import APIRouter, HTTPException
  6. from pydantic import BaseModel
  7. from app.db import get_pool
  8. router = APIRouter()
  9. class PublicPriceOut(BaseModel):
  10. url: str
  11. model_name: str
  12. prices: dict
  13. scraped_at: datetime
  14. @router.get("/prices", response_model=List[PublicPriceOut])
  15. async def get_public_prices(url: Optional[str] = None) -> List[PublicPriceOut]:
  16. pool = get_pool()
  17. if url is None:
  18. rows = await pool.fetch(
  19. "SELECT DISTINCT ON (url) url, model_name, prices, scraped_at "
  20. "FROM scrape_results ORDER BY url, scraped_at DESC"
  21. )
  22. else:
  23. rows = await pool.fetch(
  24. "SELECT url, model_name, prices, scraped_at "
  25. "FROM scrape_results WHERE url = $1 ORDER BY scraped_at DESC LIMIT 1",
  26. url,
  27. )
  28. if not rows:
  29. raise HTTPException(status_code=404, detail="No scrape results found for the given URL")
  30. return [PublicPriceOut(
  31. url=r["url"],
  32. model_name=r["model_name"],
  33. prices=r["prices"] if isinstance(r["prices"], dict) else json.loads(r["prices"]),
  34. scraped_at=r["scraped_at"],
  35. ) for r in rows]