redir.py 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """Utilities to handle redirection to browser UI."""
  2. import time
  3. import uuid
  4. import webbrowser
  5. import httpx
  6. from .. import constants
  7. from . import console
  8. def open_browser(target_url: str) -> None:
  9. """Open a browser window to target_url.
  10. Args:
  11. target_url: The URL to open in the browser.
  12. """
  13. if not webbrowser.open(target_url):
  14. console.warn(
  15. f"Unable to automatically open the browser. Please navigate to {target_url} in your browser."
  16. )
  17. def open_browser_and_wait(
  18. target_url: str, poll_url: str, interval: int = 2
  19. ) -> httpx.Response:
  20. """Open a browser window to target_url and request poll_url until it returns successfully.
  21. Args:
  22. target_url: The URL to open in the browser.
  23. poll_url: The URL to poll for success.
  24. interval: The interval in seconds to wait between polling.
  25. Returns:
  26. The response from the poll_url.
  27. """
  28. open_browser(target_url)
  29. console.info("[b]Complete the workflow in the browser to continue.[/b]")
  30. while True:
  31. try:
  32. response = httpx.get(poll_url, follow_redirects=True)
  33. if response.is_success:
  34. break
  35. except httpx.RequestError as err:
  36. console.info(f"Will retry after error occurred while polling: {err}.")
  37. time.sleep(interval)
  38. return response
  39. def reflex_build_redirect() -> str:
  40. """Open the browser window to reflex.build and wait for the user to select a generation.
  41. Returns:
  42. The selected generation hash.
  43. """
  44. token = str(uuid.uuid4())
  45. target_url = constants.Templates.REFLEX_BUILD_URL.format(reflex_init_token=token)
  46. poll_url = constants.Templates.REFLEX_BUILD_POLL_URL.format(reflex_init_token=token)
  47. response = open_browser_and_wait(target_url, poll_url)
  48. return response.json()["generation_hash"]