reflex.py 18 KB

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