redir.py 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  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_and_wait(
  9. target_url: str, poll_url: str, interval: int = 1
  10. ) -> httpx.Response:
  11. """Open a browser window to target_url and request poll_url until it returns successfully.
  12. Args:
  13. target_url: The URL to open in the browser.
  14. poll_url: The URL to poll for success.
  15. interval: The interval in seconds to wait between polling.
  16. Returns:
  17. The response from the poll_url.
  18. """
  19. if not webbrowser.open(target_url):
  20. console.warn(
  21. f"Unable to automatically open the browser. Please navigate to {target_url} in your browser."
  22. )
  23. console.info("Complete the workflow in the browser to continue.")
  24. while response := httpx.get(poll_url, follow_redirects=True):
  25. if response.is_success:
  26. break
  27. time.sleep(interval)
  28. return response
  29. def reflex_build_redirect() -> str:
  30. """Open the browser window to reflex.build and wait for the user to select a generation.
  31. Returns:
  32. The selected generation hash.
  33. """
  34. token = str(uuid.uuid4())
  35. target_url = constants.Templates.REFLEX_BUILD_URL.format(reflex_init_token=token)
  36. poll_url = constants.Templates.REFLEX_BUILD_POLL_URL.format(reflex_init_token=token)
  37. response = open_browser_and_wait(target_url, poll_url)
  38. return response.json()["generation_hash"]