reflex.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591
  1. """Reflex CLI to create, run, and deploy apps."""
  2. from __future__ import annotations
  3. import atexit
  4. import os
  5. import webbrowser
  6. from pathlib import Path
  7. from typing import List, Optional
  8. import typer
  9. import typer.core
  10. from reflex_cli.deployments import deployments_cli
  11. from reflex_cli.utils import dependency
  12. from reflex import constants
  13. from reflex.config import get_config
  14. from reflex.custom_components.custom_components import custom_components_cli
  15. from reflex.utils import console, telemetry
  16. # Disable typer+rich integration for help panels
  17. typer.core.rich = False # type: ignore
  18. # Create the app.
  19. try:
  20. cli = typer.Typer(add_completion=False, pretty_exceptions_enable=False)
  21. except TypeError:
  22. # Fallback for older typer versions.
  23. cli = typer.Typer(add_completion=False)
  24. # Get the config.
  25. config = get_config()
  26. def version(value: bool):
  27. """Get the Reflex version.
  28. Args:
  29. value: Whether the version flag was passed.
  30. Raises:
  31. typer.Exit: If the version flag was passed.
  32. """
  33. if value:
  34. console.print(constants.Reflex.VERSION)
  35. raise typer.Exit()
  36. @cli.callback()
  37. def main(
  38. version: bool = typer.Option(
  39. None,
  40. "-v",
  41. "--version",
  42. callback=version,
  43. help="Get the Reflex version.",
  44. is_eager=True,
  45. ),
  46. ):
  47. """Reflex CLI to create, run, and deploy apps."""
  48. pass
  49. def _init(
  50. name: str,
  51. template: str | None = None,
  52. loglevel: constants.LogLevel = config.loglevel,
  53. ):
  54. """Initialize a new Reflex app in the given directory."""
  55. from reflex.utils import exec, prerequisites
  56. # Set the log level.
  57. console.set_log_level(loglevel)
  58. # Show system info
  59. exec.output_system_info()
  60. # Validate the app name.
  61. app_name = prerequisites.validate_app_name(name)
  62. console.rule(f"[bold]Initializing {app_name}")
  63. # Check prerequisites.
  64. prerequisites.check_latest_package_version(constants.Reflex.MODULE_NAME)
  65. prerequisites.initialize_reflex_user_directory()
  66. prerequisites.ensure_reflex_installation_id()
  67. # When upgrading to 0.4, show migration instructions.
  68. if prerequisites.should_show_rx_chakra_migration_instructions():
  69. prerequisites.show_rx_chakra_migration_instructions()
  70. # Set up the web project.
  71. prerequisites.initialize_frontend_dependencies()
  72. # Initialize the app.
  73. prerequisites.initialize_app(app_name, template)
  74. # Migrate Pynecone projects to Reflex.
  75. prerequisites.migrate_to_reflex()
  76. # Initialize the .gitignore.
  77. prerequisites.initialize_gitignore()
  78. # Initialize the requirements.txt.
  79. prerequisites.initialize_requirements_txt()
  80. # Finish initializing the app.
  81. console.success(f"Initialized {app_name}")
  82. @cli.command()
  83. def init(
  84. name: str = typer.Option(
  85. None, metavar="APP_NAME", help="The name of the app to initialize."
  86. ),
  87. template: str = typer.Option(
  88. None,
  89. help="The template to initialize the app with.",
  90. ),
  91. loglevel: constants.LogLevel = typer.Option(
  92. config.loglevel, help="The log level to use."
  93. ),
  94. ):
  95. """Initialize a new Reflex app in the current directory."""
  96. _init(name, template, loglevel)
  97. def _run(
  98. env: constants.Env = constants.Env.DEV,
  99. frontend: bool = True,
  100. backend: bool = True,
  101. frontend_port: str = str(config.frontend_port),
  102. backend_port: str = str(config.backend_port),
  103. backend_host: str = config.backend_host,
  104. loglevel: constants.LogLevel = config.loglevel,
  105. ):
  106. """Run the app in the given directory."""
  107. from reflex.utils import build, exec, prerequisites, processes
  108. # Set the log level.
  109. console.set_log_level(loglevel)
  110. # Set env mode in the environment
  111. os.environ[constants.ENV_MODE_ENV_VAR] = env.value
  112. # Show system info
  113. exec.output_system_info()
  114. # If no --frontend-only and no --backend-only, then turn on frontend and backend both
  115. if not frontend and not backend:
  116. frontend = True
  117. backend = True
  118. if not frontend and backend:
  119. _skip_compile()
  120. # Check that the app is initialized.
  121. if prerequisites.needs_reinit(frontend=frontend):
  122. _init(name=config.app_name, loglevel=loglevel)
  123. # Find the next available open port if applicable.
  124. if frontend:
  125. frontend_port = processes.handle_port(
  126. "frontend", frontend_port, str(constants.DefaultPorts.FRONTEND_PORT)
  127. )
  128. if backend:
  129. backend_port = processes.handle_port(
  130. "backend", backend_port, str(constants.DefaultPorts.BACKEND_PORT)
  131. )
  132. # Apply the new ports to the config.
  133. if frontend_port != str(config.frontend_port):
  134. config._set_persistent(frontend_port=frontend_port)
  135. if backend_port != str(config.backend_port):
  136. config._set_persistent(backend_port=backend_port)
  137. # Reload the config to make sure the env vars are persistent.
  138. get_config(reload=True)
  139. console.rule("[bold]Starting Reflex App")
  140. prerequisites.check_latest_package_version(constants.Reflex.MODULE_NAME)
  141. if frontend:
  142. # Get the app module.
  143. prerequisites.get_compiled_app()
  144. # Warn if schema is not up to date.
  145. prerequisites.check_schema_up_to_date()
  146. # Get the frontend and backend commands, based on the environment.
  147. setup_frontend = frontend_cmd = backend_cmd = None
  148. if env == constants.Env.DEV:
  149. setup_frontend, frontend_cmd, backend_cmd = (
  150. build.setup_frontend,
  151. exec.run_frontend,
  152. exec.run_backend,
  153. )
  154. if env == constants.Env.PROD:
  155. setup_frontend, frontend_cmd, backend_cmd = (
  156. build.setup_frontend_prod,
  157. exec.run_frontend_prod,
  158. exec.run_backend_prod,
  159. )
  160. assert setup_frontend and frontend_cmd and backend_cmd, "Invalid env"
  161. # Post a telemetry event.
  162. telemetry.send(f"run-{env.value}")
  163. # Display custom message when there is a keyboard interrupt.
  164. atexit.register(processes.atexit_handler)
  165. # Run the frontend and backend together.
  166. commands = []
  167. # Run the frontend on a separate thread.
  168. if frontend:
  169. setup_frontend(Path.cwd())
  170. commands.append((frontend_cmd, Path.cwd(), frontend_port, backend))
  171. # In prod mode, run the backend on a separate thread.
  172. if backend and env == constants.Env.PROD:
  173. commands.append((backend_cmd, backend_host, backend_port))
  174. # Start the frontend and backend.
  175. with processes.run_concurrently_context(*commands):
  176. # In dev mode, run the backend on the main thread.
  177. if backend and env == constants.Env.DEV:
  178. backend_cmd(backend_host, int(backend_port))
  179. # The windows uvicorn bug workaround
  180. # https://github.com/reflex-dev/reflex/issues/2335
  181. if constants.IS_WINDOWS and exec.frontend_process:
  182. # Sends SIGTERM in windows
  183. exec.kill(exec.frontend_process.pid)
  184. @cli.command()
  185. def run(
  186. env: constants.Env = typer.Option(
  187. constants.Env.DEV, help="The environment to run the app in."
  188. ),
  189. frontend: bool = typer.Option(
  190. False, "--frontend-only", help="Execute only frontend."
  191. ),
  192. backend: bool = typer.Option(False, "--backend-only", help="Execute only backend."),
  193. frontend_port: str = typer.Option(
  194. config.frontend_port, help="Specify a different frontend port."
  195. ),
  196. backend_port: str = typer.Option(
  197. config.backend_port, help="Specify a different backend port."
  198. ),
  199. backend_host: str = typer.Option(
  200. config.backend_host, help="Specify the backend host."
  201. ),
  202. loglevel: constants.LogLevel = typer.Option(
  203. config.loglevel, help="The log level to use."
  204. ),
  205. ):
  206. """Run the app in the current directory."""
  207. _run(env, frontend, backend, frontend_port, backend_port, backend_host, loglevel)
  208. @cli.command()
  209. def export(
  210. zipping: bool = typer.Option(
  211. True, "--no-zip", help="Disable zip for backend and frontend exports."
  212. ),
  213. frontend: bool = typer.Option(
  214. True, "--backend-only", help="Export only backend.", show_default=False
  215. ),
  216. backend: bool = typer.Option(
  217. True, "--frontend-only", help="Export only frontend.", show_default=False
  218. ),
  219. zip_dest_dir: str = typer.Option(
  220. os.getcwd(),
  221. help="The directory to export the zip files to.",
  222. show_default=False,
  223. ),
  224. upload_db_file: bool = typer.Option(
  225. False,
  226. help="Whether to exclude sqlite db files when exporting backend.",
  227. hidden=True,
  228. ),
  229. loglevel: constants.LogLevel = typer.Option(
  230. config.loglevel, help="The log level to use."
  231. ),
  232. ):
  233. """Export the app to a zip file."""
  234. from reflex.utils import export as export_utils
  235. from reflex.utils import prerequisites
  236. if prerequisites.needs_reinit(frontend=True):
  237. _init(name=config.app_name, loglevel=loglevel)
  238. export_utils.export(
  239. zipping=zipping,
  240. frontend=frontend,
  241. backend=backend,
  242. zip_dest_dir=zip_dest_dir,
  243. upload_db_file=upload_db_file,
  244. loglevel=loglevel,
  245. )
  246. def _login() -> str:
  247. """Helper function to authenticate with Reflex hosting service."""
  248. from reflex_cli.utils import hosting
  249. access_token, invitation_code = hosting.authenticated_token()
  250. if access_token:
  251. console.print("You already logged in.")
  252. return access_token
  253. # If not already logged in, open a browser window/tab to the login page.
  254. access_token = hosting.authenticate_on_browser(invitation_code)
  255. if not access_token:
  256. console.error(f"Unable to authenticate. Please try again or contact support.")
  257. raise typer.Exit(1)
  258. console.print("Successfully logged in.")
  259. return access_token
  260. @cli.command()
  261. def login(
  262. loglevel: constants.LogLevel = typer.Option(
  263. config.loglevel, help="The log level to use."
  264. ),
  265. ):
  266. """Authenticate with Reflex hosting service."""
  267. # Set the log level.
  268. console.set_log_level(loglevel)
  269. _login()
  270. @cli.command()
  271. def logout(
  272. loglevel: constants.LogLevel = typer.Option(
  273. config.loglevel, help="The log level to use."
  274. ),
  275. ):
  276. """Log out of access to Reflex hosting service."""
  277. from reflex_cli.utils import hosting
  278. console.set_log_level(loglevel)
  279. hosting.log_out_on_browser()
  280. console.debug("Deleting access token from config locally")
  281. hosting.delete_token_from_config(include_invitation_code=True)
  282. db_cli = typer.Typer()
  283. script_cli = typer.Typer()
  284. def _skip_compile():
  285. """Skip the compile step."""
  286. os.environ[constants.SKIP_COMPILE_ENV_VAR] = "yes"
  287. @db_cli.command(name="init")
  288. def db_init():
  289. """Create database schema and migration configuration."""
  290. from reflex import model
  291. from reflex.utils import prerequisites
  292. # Check the database url.
  293. if config.db_url is None:
  294. console.error("db_url is not configured, cannot initialize.")
  295. return
  296. # Check the alembic config.
  297. if Path(constants.ALEMBIC_CONFIG).exists():
  298. console.error(
  299. "Database is already initialized. Use "
  300. "[bold]reflex db makemigrations[/bold] to create schema change "
  301. "scripts and [bold]reflex db migrate[/bold] to apply migrations "
  302. "to a new or existing database.",
  303. )
  304. return
  305. # Initialize the database.
  306. _skip_compile()
  307. prerequisites.get_compiled_app()
  308. model.Model.alembic_init()
  309. model.Model.migrate(autogenerate=True)
  310. @db_cli.command()
  311. def migrate():
  312. """Create or update database schema from migration scripts."""
  313. from reflex import model
  314. from reflex.utils import prerequisites
  315. # TODO see if we can use `get_app()` instead (no compile). Would _skip_compile still be needed then?
  316. _skip_compile()
  317. prerequisites.get_compiled_app()
  318. if not prerequisites.check_db_initialized():
  319. return
  320. model.Model.migrate()
  321. prerequisites.check_schema_up_to_date()
  322. @db_cli.command()
  323. def makemigrations(
  324. message: str = typer.Option(
  325. None, help="Human readable identifier for the generated revision."
  326. ),
  327. ):
  328. """Create autogenerated alembic migration scripts."""
  329. from alembic.util.exc import CommandError
  330. from reflex import model
  331. from reflex.utils import prerequisites
  332. # TODO see if we can use `get_app()` instead (no compile). Would _skip_compile still be needed then?
  333. _skip_compile()
  334. prerequisites.get_compiled_app()
  335. if not prerequisites.check_db_initialized():
  336. return
  337. with model.Model.get_db_engine().connect() as connection:
  338. try:
  339. model.Model.alembic_autogenerate(connection=connection, message=message)
  340. except CommandError as command_error:
  341. if "Target database is not up to date." not in str(command_error):
  342. raise
  343. console.error(
  344. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  345. )
  346. @script_cli.command(
  347. name="keep-chakra",
  348. help="Change all rx.<component> references to rx.chakra.<component>, to preserve Chakra UI usage.",
  349. )
  350. def keep_chakra():
  351. """Change all rx.<component> references to rx.chakra.<component>, to preserve Chakra UI usage."""
  352. from reflex.utils import prerequisites
  353. prerequisites.migrate_to_rx_chakra()
  354. @cli.command()
  355. def deploy(
  356. key: Optional[str] = typer.Option(
  357. None,
  358. "-k",
  359. "--deployment-key",
  360. help="The name of the deployment. Domain name safe characters only.",
  361. ),
  362. app_name: str = typer.Option(
  363. config.app_name,
  364. "--app-name",
  365. help="The name of the App to deploy under.",
  366. hidden=True,
  367. ),
  368. regions: List[str] = typer.Option(
  369. list(),
  370. "-r",
  371. "--region",
  372. help="The regions to deploy to.",
  373. ),
  374. envs: List[str] = typer.Option(
  375. list(),
  376. "--env",
  377. help="The environment variables to set: <key>=<value>. For multiple envs, repeat this option, e.g. --env k1=v2 --env k2=v2.",
  378. ),
  379. cpus: Optional[int] = typer.Option(
  380. None, help="The number of CPUs to allocate.", hidden=True
  381. ),
  382. memory_mb: Optional[int] = typer.Option(
  383. None, help="The amount of memory to allocate.", hidden=True
  384. ),
  385. auto_start: Optional[bool] = typer.Option(
  386. None,
  387. help="Whether to auto start the instance.",
  388. hidden=True,
  389. ),
  390. auto_stop: Optional[bool] = typer.Option(
  391. None,
  392. help="Whether to auto stop the instance.",
  393. hidden=True,
  394. ),
  395. frontend_hostname: Optional[str] = typer.Option(
  396. None,
  397. "--frontend-hostname",
  398. help="The hostname of the frontend.",
  399. hidden=True,
  400. ),
  401. interactive: bool = typer.Option(
  402. True,
  403. help="Whether to list configuration options and ask for confirmation.",
  404. ),
  405. with_metrics: Optional[str] = typer.Option(
  406. None,
  407. help="Setting for metrics scraping for the deployment. Setup required in user code.",
  408. hidden=True,
  409. ),
  410. with_tracing: Optional[str] = typer.Option(
  411. None,
  412. help="Setting to export tracing for the deployment. Setup required in user code.",
  413. hidden=True,
  414. ),
  415. upload_db_file: bool = typer.Option(
  416. False,
  417. help="Whether to include local sqlite db files when uploading to hosting service.",
  418. hidden=True,
  419. ),
  420. loglevel: constants.LogLevel = typer.Option(
  421. config.loglevel, help="The log level to use."
  422. ),
  423. ):
  424. """Deploy the app to the Reflex hosting service."""
  425. from reflex_cli import cli as hosting_cli
  426. from reflex.utils import export as export_utils
  427. from reflex.utils import prerequisites
  428. # Set the log level.
  429. console.set_log_level(loglevel)
  430. # Only check requirements if interactive. There is user interaction for requirements update.
  431. if interactive:
  432. dependency.check_requirements()
  433. # Check if we are set up.
  434. if prerequisites.needs_reinit(frontend=True):
  435. _init(name=config.app_name, loglevel=loglevel)
  436. prerequisites.check_latest_package_version(constants.ReflexHostingCLI.MODULE_NAME)
  437. hosting_cli.deploy(
  438. app_name=app_name,
  439. export_fn=lambda zip_dest_dir,
  440. api_url,
  441. deploy_url,
  442. frontend,
  443. backend,
  444. zipping: export_utils.export(
  445. zip_dest_dir=zip_dest_dir,
  446. api_url=api_url,
  447. deploy_url=deploy_url,
  448. frontend=frontend,
  449. backend=backend,
  450. zipping=zipping,
  451. loglevel=loglevel,
  452. upload_db_file=upload_db_file,
  453. ),
  454. key=key,
  455. regions=regions,
  456. envs=envs,
  457. cpus=cpus,
  458. memory_mb=memory_mb,
  459. auto_start=auto_start,
  460. auto_stop=auto_stop,
  461. frontend_hostname=frontend_hostname,
  462. interactive=interactive,
  463. with_metrics=with_metrics,
  464. with_tracing=with_tracing,
  465. loglevel=loglevel.value,
  466. )
  467. @cli.command()
  468. def demo(
  469. frontend_port: str = typer.Option(
  470. "3001", help="Specify a different frontend port."
  471. ),
  472. backend_port: str = typer.Option("8001", help="Specify a different backend port."),
  473. ):
  474. """Run the demo app."""
  475. # Open the demo app in a terminal.
  476. webbrowser.open("https://demo.reflex.run")
  477. cli.add_typer(db_cli, name="db", help="Subcommands for managing the database schema.")
  478. cli.add_typer(script_cli, name="script", help="Subcommands running helper scripts.")
  479. cli.add_typer(
  480. deployments_cli,
  481. name="deployments",
  482. help="Subcommands for managing the Deployments.",
  483. )
  484. cli.add_typer(
  485. custom_components_cli,
  486. name="component",
  487. help="Subcommands for creating and publishing Custom Components.",
  488. )
  489. if __name__ == "__main__":
  490. cli()