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