reflex.py 17 KB

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