redir.py 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. """Utilities to handle redirection to browser UI."""
  2. import time
  3. import webbrowser
  4. import httpx
  5. from reflex.utils import net
  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. else:
  18. console.info(f"Opening browser to {target_url}.")
  19. def open_browser_and_wait(
  20. target_url: str, poll_url: str, interval: int = 2
  21. ) -> httpx.Response:
  22. """Open a browser window to target_url and request poll_url until it returns successfully.
  23. Args:
  24. target_url: The URL to open in the browser.
  25. poll_url: The URL to poll for success.
  26. interval: The interval in seconds to wait between polling.
  27. Returns:
  28. The response from the poll_url.
  29. """
  30. open_browser(target_url)
  31. console.info("[b]Complete the workflow in the browser to continue.[/b]")
  32. while True:
  33. try:
  34. response = net.get(poll_url, follow_redirects=True)
  35. if response.is_success:
  36. break
  37. except httpx.RequestError as err:
  38. console.info(f"Will retry after error occurred while polling: {err}.")
  39. time.sleep(interval)
  40. return response
  41. def reflex_build_redirect() -> None:
  42. """Open the browser window to reflex.build."""
  43. open_browser(constants.Templates.REFLEX_BUILD_FRONTEND)
  44. def reflex_templates():
  45. """Open the browser window to reflex.build/templates."""
  46. open_browser(constants.Templates.REFLEX_TEMPLATES_URL)