utils.py 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. from __future__ import annotations
  2. import json
  3. from typing import Any, Tuple
  4. def url_from_host_port(host: str, port: int) -> str:
  5. host = (host or "").strip()
  6. if not host:
  7. host = "127.0.0.1"
  8. if host.startswith("http://") or host.startswith("https://"):
  9. return f"{host}:{port}"
  10. return f"http://{host}:{port}"
  11. def parse_host_port(base_url: str) -> Tuple[str, int]:
  12. s = (base_url or "").strip()
  13. s = s.replace("http://", "").replace("https://", "")
  14. if ":" not in s:
  15. return (s or "127.0.0.1"), 8000
  16. host, port_s = s.split(":", 1)
  17. try:
  18. port = int(port_s)
  19. except Exception:
  20. port = 8000
  21. return (host or "127.0.0.1"), port
  22. def short_json(x: Any, max_len: int = 500) -> str:
  23. try:
  24. s = json.dumps(x, ensure_ascii=False)
  25. except Exception:
  26. s = str(x)
  27. if len(s) > max_len:
  28. return s[:max_len] + "..."
  29. return s
  30. def short_path(p: str, max_len: int = 160) -> str:
  31. p = p or ""
  32. if len(p) > max_len:
  33. return "..." + p[-(max_len - 3):]
  34. return p