host_url.py 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. from __future__ import annotations
  2. import re
  3. from typing_extensions import final, override
  4. from wandb import env, util
  5. from wandb.sdk.lib import urls
  6. @final
  7. class HostUrl:
  8. """A validated and normalized W&B server URL.
  9. For convenient formatting, the __str__ representation is the URL itself.
  10. """
  11. def __init__(self, url: str, *, app_url: str | None = None) -> None:
  12. """Validate a W&B server URL.
  13. Args:
  14. url: The "API" URL for programmatic access.
  15. app_url: The corresponding "app" URL for the W&B UI. If not
  16. provided, then either the WANDB_APP_URL variable is consulted
  17. or it is derived from the API URL. This is not used in
  18. comparisons.
  19. """
  20. urls.validate_url(url)
  21. # Checks for wandb.ai.
  22. if re.match(r".*wandb\.ai[^\.]*$", url):
  23. if "api." not in url:
  24. # A user might guess that app.wandb.ai is the default cloud server.
  25. raise ValueError(
  26. f"{url!r} is not a valid server address,"
  27. + " did you mean https://api.wandb.ai?"
  28. )
  29. elif not url.startswith("https"):
  30. raise ValueError("http is not secure, please use https://api.wandb.ai")
  31. self._url = url.rstrip("/")
  32. self._app_url = (
  33. app_url #
  34. or env.get_app_url()
  35. or util.api_to_app_url(self._url)
  36. ).rstrip("/")
  37. def is_same_url(self, value: str | HostUrl, /) -> bool:
  38. """Compare normalized URLs.
  39. Returns true if the value is an equivalent HostUrl or a string
  40. that normalizes to this URL.
  41. """
  42. if isinstance(value, HostUrl):
  43. return self._url == value._url
  44. else:
  45. return self._url == value.rstrip("/")
  46. @property
  47. def url(self) -> str:
  48. return self._url
  49. @property
  50. def app_url(self) -> str:
  51. return self._app_url
  52. @override
  53. def __str__(self) -> str:
  54. return self._url
  55. @override
  56. def __repr__(self) -> str:
  57. return f"HostUrl({self._url!r})"