redir.py 1.5 KB

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