reflex.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708
  1. """Reflex CLI to create, run, and deploy apps."""
  2. from __future__ import annotations
  3. import atexit
  4. from pathlib import Path
  5. from typing import TYPE_CHECKING
  6. import typer
  7. import typer.core
  8. from reflex_cli.v2.deployments import hosting_cli
  9. from reflex import constants
  10. from reflex.config import environment, get_config
  11. from reflex.custom_components.custom_components import custom_components_cli
  12. from reflex.state import reset_disk_state_manager
  13. from reflex.utils import console, redir, telemetry
  14. from reflex.utils.exec import should_use_granian
  15. # Disable typer+rich integration for help panels
  16. typer.core.rich = None # pyright: ignore [reportPrivateImportUsage]
  17. # Create the app.
  18. cli = typer.Typer(add_completion=False, pretty_exceptions_enable=False)
  19. def version(value: bool):
  20. """Get the Reflex version.
  21. Args:
  22. value: Whether the version flag was passed.
  23. Raises:
  24. typer.Exit: If the version flag was passed.
  25. """
  26. if value:
  27. console.print(constants.Reflex.VERSION)
  28. raise typer.Exit()
  29. @cli.callback()
  30. def main(
  31. version: bool = typer.Option(
  32. None,
  33. "-v",
  34. "--version",
  35. callback=version,
  36. help="Get the Reflex version.",
  37. is_eager=True,
  38. ),
  39. ):
  40. """Reflex CLI to create, run, and deploy apps."""
  41. pass
  42. def _init(
  43. name: str,
  44. template: str | None = None,
  45. loglevel: constants.LogLevel | None = None,
  46. ai: bool = False,
  47. ):
  48. """Initialize a new Reflex app in the given directory."""
  49. from reflex.utils import exec, prerequisites
  50. if loglevel is not None:
  51. console.set_log_level(loglevel)
  52. config = get_config()
  53. # Set the log level.
  54. loglevel = loglevel or config.loglevel
  55. console.set_log_level(loglevel)
  56. # Show system info
  57. exec.output_system_info()
  58. if ai:
  59. redir.reflex_build_redirect()
  60. return
  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. # Set up the web project.
  69. prerequisites.initialize_frontend_dependencies()
  70. # Initialize the app.
  71. template = prerequisites.initialize_app(app_name, template)
  72. # Initialize the .gitignore.
  73. prerequisites.initialize_gitignore()
  74. # Initialize the requirements.txt.
  75. prerequisites.initialize_requirements_txt()
  76. template_msg = f" using the {template} template" if template else ""
  77. # Finish initializing the app.
  78. console.success(f"Initialized {app_name}{template_msg}")
  79. @cli.command()
  80. def init(
  81. name: str = typer.Option(
  82. None, metavar="APP_NAME", help="The name of the app to initialize."
  83. ),
  84. template: str = typer.Option(
  85. None,
  86. help="The template to initialize the app with.",
  87. ),
  88. loglevel: constants.LogLevel | None = typer.Option(
  89. None, help="The log level to use."
  90. ),
  91. ai: bool = typer.Option(
  92. False,
  93. help="Use AI to create the initial template. Cannot be used with existing app or `--template` option.",
  94. ),
  95. ):
  96. """Initialize a new Reflex app in the current directory."""
  97. _init(name, template, loglevel, ai)
  98. def _run(
  99. env: constants.Env = constants.Env.DEV,
  100. frontend: bool = True,
  101. backend: bool = True,
  102. frontend_port: int | None = None,
  103. backend_port: int | None = None,
  104. backend_host: str | None = None,
  105. loglevel: constants.LogLevel | None = None,
  106. ):
  107. """Run the app in the given directory."""
  108. from reflex.utils import build, exec, prerequisites, processes
  109. if loglevel is not None:
  110. console.set_log_level(loglevel)
  111. config = get_config()
  112. loglevel = loglevel or config.loglevel
  113. backend_host = backend_host or config.backend_host
  114. # Set the log level.
  115. console.set_log_level(loglevel)
  116. # Set env mode in the environment
  117. environment.REFLEX_ENV_MODE.set(env)
  118. # Show system info
  119. exec.output_system_info()
  120. # If no --frontend-only and no --backend-only, then turn on frontend and backend both
  121. frontend, backend = prerequisites.check_running_mode(frontend, backend)
  122. if not frontend and backend:
  123. _skip_compile()
  124. # Check that the app is initialized.
  125. if prerequisites.needs_reinit(frontend=frontend):
  126. _init(name=config.app_name, loglevel=loglevel)
  127. # Delete the states folder if it exists.
  128. reset_disk_state_manager()
  129. # Find the next available open port if applicable.
  130. if frontend:
  131. auto_increment_frontend = not bool(frontend_port or config.frontend_port)
  132. frontend_port = processes.handle_port(
  133. "frontend",
  134. (
  135. frontend_port
  136. or config.frontend_port
  137. or constants.DefaultPorts.FRONTEND_PORT
  138. ),
  139. auto_increment=auto_increment_frontend,
  140. )
  141. if backend:
  142. auto_increment_backend = not bool(backend_port or config.backend_port)
  143. backend_port = processes.handle_port(
  144. "backend",
  145. (
  146. backend_port
  147. or config.backend_port
  148. or constants.DefaultPorts.BACKEND_PORT
  149. ),
  150. auto_increment=auto_increment_backend,
  151. )
  152. # Apply the new ports to the config.
  153. if frontend_port != config.frontend_port:
  154. config._set_persistent(frontend_port=frontend_port)
  155. if backend_port != config.backend_port:
  156. config._set_persistent(backend_port=backend_port)
  157. # Reload the config to make sure the env vars are persistent.
  158. get_config(reload=True)
  159. console.rule("[bold]Starting Reflex App")
  160. prerequisites.check_latest_package_version(constants.Reflex.MODULE_NAME)
  161. # Get the app module.
  162. app_task = prerequisites.compile_or_validate_app
  163. args = (frontend,)
  164. # Granian fails if the app is already imported.
  165. if should_use_granian():
  166. import concurrent.futures
  167. compile_future = concurrent.futures.ProcessPoolExecutor(max_workers=1).submit(
  168. app_task,
  169. *args,
  170. )
  171. validation_result = compile_future.result()
  172. else:
  173. validation_result = app_task(*args)
  174. if not validation_result:
  175. raise typer.Exit(1)
  176. # Warn if schema is not up to date.
  177. prerequisites.check_schema_up_to_date()
  178. # Get the frontend and backend commands, based on the environment.
  179. setup_frontend = frontend_cmd = backend_cmd = None
  180. if env == constants.Env.DEV:
  181. setup_frontend, frontend_cmd, backend_cmd = (
  182. build.setup_frontend,
  183. exec.run_frontend,
  184. exec.run_backend,
  185. )
  186. if env == constants.Env.PROD:
  187. setup_frontend, frontend_cmd, backend_cmd = (
  188. build.setup_frontend_prod,
  189. exec.run_frontend_prod,
  190. exec.run_backend_prod,
  191. )
  192. if not setup_frontend or not frontend_cmd or not backend_cmd:
  193. raise ValueError("Invalid env")
  194. # Post a telemetry event.
  195. telemetry.send(f"run-{env.value}")
  196. # Display custom message when there is a keyboard interrupt.
  197. atexit.register(processes.atexit_handler)
  198. # Run the frontend and backend together.
  199. commands = []
  200. # Run the frontend on a separate thread.
  201. if frontend:
  202. setup_frontend(Path.cwd())
  203. commands.append((frontend_cmd, Path.cwd(), frontend_port, backend))
  204. # In prod mode, run the backend on a separate thread.
  205. if backend and env == constants.Env.PROD:
  206. commands.append(
  207. (
  208. backend_cmd,
  209. backend_host,
  210. backend_port,
  211. loglevel.subprocess_level(),
  212. frontend,
  213. )
  214. )
  215. # Start the frontend and backend.
  216. with processes.run_concurrently_context(*commands):
  217. # In dev mode, run the backend on the main thread.
  218. if backend and backend_port and env == constants.Env.DEV:
  219. backend_cmd(
  220. backend_host, int(backend_port), loglevel.subprocess_level(), frontend
  221. )
  222. # The windows uvicorn bug workaround
  223. # https://github.com/reflex-dev/reflex/issues/2335
  224. if constants.IS_WINDOWS and exec.frontend_process:
  225. # Sends SIGTERM in windows
  226. exec.kill(exec.frontend_process.pid)
  227. @cli.command()
  228. def run(
  229. env: constants.Env = typer.Option(
  230. constants.Env.DEV, help="The environment to run the app in."
  231. ),
  232. frontend: bool = typer.Option(
  233. False,
  234. "--frontend-only",
  235. help="Execute only frontend.",
  236. envvar=environment.REFLEX_FRONTEND_ONLY.name,
  237. ),
  238. backend: bool = typer.Option(
  239. False,
  240. "--backend-only",
  241. help="Execute only backend.",
  242. envvar=environment.REFLEX_BACKEND_ONLY.name,
  243. ),
  244. frontend_port: int | None = typer.Option(
  245. None,
  246. help="Specify a different frontend port.",
  247. envvar=environment.REFLEX_FRONTEND_PORT.name,
  248. ),
  249. backend_port: int | None = typer.Option(
  250. None,
  251. help="Specify a different backend port.",
  252. envvar=environment.REFLEX_BACKEND_PORT.name,
  253. ),
  254. backend_host: str | None = typer.Option(None, help="Specify the backend host."),
  255. loglevel: constants.LogLevel | None = typer.Option(
  256. None, help="The log level to use."
  257. ),
  258. ):
  259. """Run the app in the current directory."""
  260. if frontend and backend:
  261. console.error("Cannot use both --frontend-only and --backend-only options.")
  262. raise typer.Exit(1)
  263. if loglevel is not None:
  264. console.set_log_level(loglevel)
  265. config = get_config()
  266. frontend_port = frontend_port or config.frontend_port
  267. backend_port = backend_port or config.backend_port
  268. backend_host = backend_host or config.backend_host
  269. loglevel = loglevel or config.loglevel
  270. environment.REFLEX_COMPILE_CONTEXT.set(constants.CompileContext.RUN)
  271. environment.REFLEX_BACKEND_ONLY.set(backend)
  272. environment.REFLEX_FRONTEND_ONLY.set(frontend)
  273. _run(env, frontend, backend, frontend_port, backend_port, backend_host, loglevel)
  274. @cli.command()
  275. def export(
  276. zipping: bool = typer.Option(
  277. True, "--no-zip", help="Disable zip for backend and frontend exports."
  278. ),
  279. frontend: bool = typer.Option(
  280. False,
  281. "--frontend-only",
  282. help="Export only frontend.",
  283. show_default=False,
  284. envvar=environment.REFLEX_FRONTEND_ONLY.name,
  285. ),
  286. backend: bool = typer.Option(
  287. False,
  288. "--backend-only",
  289. help="Export only backend.",
  290. show_default=False,
  291. envvar=environment.REFLEX_BACKEND_ONLY.name,
  292. ),
  293. zip_dest_dir: str = typer.Option(
  294. str(Path.cwd()),
  295. help="The directory to export the zip files to.",
  296. show_default=False,
  297. ),
  298. upload_db_file: bool = typer.Option(
  299. False,
  300. help="Whether to exclude sqlite db files when exporting backend.",
  301. hidden=True,
  302. ),
  303. env: constants.Env = typer.Option(
  304. constants.Env.PROD, help="The environment to export the app in."
  305. ),
  306. loglevel: constants.LogLevel | None = typer.Option(
  307. None, help="The log level to use."
  308. ),
  309. ):
  310. """Export the app to a zip file."""
  311. from reflex.utils import export as export_utils
  312. from reflex.utils import prerequisites
  313. environment.REFLEX_COMPILE_CONTEXT.set(constants.CompileContext.EXPORT)
  314. frontend, backend = prerequisites.check_running_mode(frontend, backend)
  315. loglevel = loglevel or get_config().loglevel
  316. console.set_log_level(loglevel)
  317. if prerequisites.needs_reinit(frontend=frontend or not backend):
  318. _init(name=get_config().app_name, loglevel=loglevel)
  319. export_utils.export(
  320. zipping=zipping,
  321. frontend=frontend,
  322. backend=backend,
  323. zip_dest_dir=zip_dest_dir,
  324. upload_db_file=upload_db_file,
  325. env=env,
  326. loglevel=loglevel.subprocess_level(),
  327. )
  328. @cli.command()
  329. def login(loglevel: constants.LogLevel | None = typer.Option(None)):
  330. """Authenticate with experimental Reflex hosting service."""
  331. from reflex_cli.v2 import cli as hosting_cli
  332. from reflex_cli.v2.deployments import check_version
  333. loglevel = loglevel or get_config().loglevel
  334. console.set_log_level(loglevel)
  335. check_version()
  336. validated_info = hosting_cli.login()
  337. if validated_info is not None:
  338. _skip_compile() # Allow running outside of an app dir
  339. telemetry.send("login", user_uuid=validated_info.get("user_id"))
  340. @cli.command()
  341. def logout(
  342. loglevel: constants.LogLevel | None = typer.Option(
  343. None, help="The log level to use."
  344. ),
  345. ):
  346. """Log out of access to Reflex hosting service."""
  347. from reflex_cli.v2.cli import logout
  348. from reflex_cli.v2.deployments import check_version
  349. check_version()
  350. loglevel = loglevel or get_config().loglevel
  351. logout(_convert_reflex_loglevel_to_reflex_cli_loglevel(loglevel))
  352. db_cli = typer.Typer()
  353. script_cli = typer.Typer()
  354. def _skip_compile():
  355. """Skip the compile step."""
  356. environment.REFLEX_SKIP_COMPILE.set(True)
  357. @db_cli.command(name="init")
  358. def db_init():
  359. """Create database schema and migration configuration."""
  360. from reflex import model
  361. from reflex.utils import prerequisites
  362. config = get_config()
  363. # Check the database url.
  364. if config.db_url is None:
  365. console.error("db_url is not configured, cannot initialize.")
  366. return
  367. # Check the alembic config.
  368. if environment.ALEMBIC_CONFIG.get().exists():
  369. console.error(
  370. "Database is already initialized. Use "
  371. "[bold]reflex db makemigrations[/bold] to create schema change "
  372. "scripts and [bold]reflex db migrate[/bold] to apply migrations "
  373. "to a new or existing database.",
  374. )
  375. return
  376. # Initialize the database.
  377. _skip_compile()
  378. prerequisites.get_compiled_app()
  379. model.Model.alembic_init()
  380. model.Model.migrate(autogenerate=True)
  381. @db_cli.command()
  382. def migrate():
  383. """Create or update database schema from migration scripts."""
  384. from reflex import model
  385. from reflex.utils import prerequisites
  386. # TODO see if we can use `get_app()` instead (no compile). Would _skip_compile still be needed then?
  387. _skip_compile()
  388. prerequisites.get_compiled_app()
  389. if not prerequisites.check_db_initialized():
  390. return
  391. model.Model.migrate()
  392. prerequisites.check_schema_up_to_date()
  393. @db_cli.command()
  394. def makemigrations(
  395. message: str = typer.Option(
  396. None, help="Human readable identifier for the generated revision."
  397. ),
  398. ):
  399. """Create autogenerated alembic migration scripts."""
  400. from alembic.util.exc import CommandError
  401. from reflex import model
  402. from reflex.utils import prerequisites
  403. # TODO see if we can use `get_app()` instead (no compile). Would _skip_compile still be needed then?
  404. _skip_compile()
  405. prerequisites.get_compiled_app()
  406. if not prerequisites.check_db_initialized():
  407. return
  408. with model.Model.get_db_engine().connect() as connection:
  409. try:
  410. model.Model.alembic_autogenerate(connection=connection, message=message)
  411. except CommandError as command_error:
  412. if "Target database is not up to date." not in str(command_error):
  413. raise
  414. console.error(
  415. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  416. )
  417. @cli.command()
  418. def deploy(
  419. app_name: str | None = typer.Option(
  420. None,
  421. "--app-name",
  422. help="The name of the App to deploy under.",
  423. ),
  424. app_id: str = typer.Option(
  425. None,
  426. "--app-id",
  427. help="The ID of the App to deploy over.",
  428. ),
  429. regions: list[str] = typer.Option(
  430. [],
  431. "-r",
  432. "--region",
  433. help="The regions to deploy to. `reflex cloud regions` For multiple envs, repeat this option, e.g. --region sjc --region iad",
  434. ),
  435. envs: list[str] = typer.Option(
  436. [],
  437. "--env",
  438. help="The environment variables to set: <key>=<value>. For multiple envs, repeat this option, e.g. --env k1=v2 --env k2=v2.",
  439. ),
  440. vmtype: str | None = typer.Option(
  441. None,
  442. "--vmtype",
  443. help="Vm type id. Run `reflex cloud vmtypes` to get options.",
  444. ),
  445. hostname: str | None = typer.Option(
  446. None,
  447. "--hostname",
  448. help="The hostname of the frontend.",
  449. ),
  450. interactive: bool = typer.Option(
  451. True,
  452. help="Whether to list configuration options and ask for confirmation.",
  453. ),
  454. envfile: str | None = typer.Option(
  455. None,
  456. "--envfile",
  457. help="The path to an env file to use. Will override any envs set manually.",
  458. ),
  459. loglevel: constants.LogLevel | None = typer.Option(
  460. None, help="The log level to use."
  461. ),
  462. project: str | None = typer.Option(
  463. None,
  464. "--project",
  465. help="project id to deploy to",
  466. ),
  467. project_name: str | None = typer.Option(
  468. None,
  469. "--project-name",
  470. help="The name of the project to deploy to.",
  471. ),
  472. token: str | None = typer.Option(
  473. None,
  474. "--token",
  475. help="token to use for auth",
  476. ),
  477. config_path: str | None = typer.Option(
  478. None,
  479. "--config",
  480. help="path to the config file",
  481. ),
  482. ):
  483. """Deploy the app to the Reflex hosting service."""
  484. from reflex_cli.utils import dependency
  485. from reflex_cli.v2 import cli as hosting_cli
  486. from reflex_cli.v2.deployments import check_version
  487. from reflex.utils import export as export_utils
  488. from reflex.utils import prerequisites
  489. if loglevel is not None:
  490. console.set_log_level(loglevel)
  491. config = get_config()
  492. loglevel = loglevel or config.loglevel
  493. app_name = app_name or config.app_name
  494. check_version()
  495. environment.REFLEX_COMPILE_CONTEXT.set(constants.CompileContext.DEPLOY)
  496. # Set the log level.
  497. console.set_log_level(loglevel)
  498. # Only check requirements if interactive.
  499. # There is user interaction for requirements update.
  500. if interactive:
  501. dependency.check_requirements()
  502. # Check if we are set up.
  503. if prerequisites.needs_reinit(frontend=True):
  504. _init(name=config.app_name, loglevel=loglevel)
  505. prerequisites.check_latest_package_version(constants.ReflexHostingCLI.MODULE_NAME)
  506. hosting_cli.deploy(
  507. app_name=app_name,
  508. app_id=app_id,
  509. export_fn=lambda zip_dest_dir,
  510. api_url,
  511. deploy_url,
  512. frontend,
  513. backend,
  514. zipping: export_utils.export(
  515. zip_dest_dir=zip_dest_dir,
  516. api_url=api_url,
  517. deploy_url=deploy_url,
  518. frontend=frontend,
  519. backend=backend,
  520. zipping=zipping,
  521. loglevel=loglevel.subprocess_level(),
  522. ),
  523. regions=regions,
  524. envs=envs,
  525. vmtype=vmtype,
  526. envfile=envfile,
  527. hostname=hostname,
  528. interactive=interactive,
  529. loglevel=_convert_reflex_loglevel_to_reflex_cli_loglevel(loglevel),
  530. token=token,
  531. project=project,
  532. project_name=project_name,
  533. **({"config_path": config_path} if config_path is not None else {}),
  534. )
  535. @cli.command()
  536. def rename(
  537. new_name: str = typer.Argument(..., help="The new name for the app."),
  538. loglevel: constants.LogLevel | None = typer.Option(
  539. None, help="The log level to use."
  540. ),
  541. ):
  542. """Rename the app in the current directory."""
  543. from reflex.utils import prerequisites
  544. loglevel = loglevel or get_config().loglevel
  545. prerequisites.validate_app_name(new_name)
  546. prerequisites.rename_app(new_name, loglevel)
  547. if TYPE_CHECKING:
  548. from reflex_cli.constants.base import LogLevel as HostingLogLevel
  549. def _convert_reflex_loglevel_to_reflex_cli_loglevel(
  550. loglevel: constants.LogLevel,
  551. ) -> HostingLogLevel:
  552. """Convert a Reflex log level to a Reflex CLI log level.
  553. Args:
  554. loglevel: The Reflex log level to convert.
  555. Returns:
  556. The converted Reflex CLI log level.
  557. """
  558. from reflex_cli.constants.base import LogLevel as HostingLogLevel
  559. if loglevel == constants.LogLevel.DEBUG:
  560. return HostingLogLevel.DEBUG
  561. if loglevel == constants.LogLevel.INFO:
  562. return HostingLogLevel.INFO
  563. if loglevel == constants.LogLevel.WARNING:
  564. return HostingLogLevel.WARNING
  565. if loglevel == constants.LogLevel.ERROR:
  566. return HostingLogLevel.ERROR
  567. if loglevel == constants.LogLevel.CRITICAL:
  568. return HostingLogLevel.CRITICAL
  569. return HostingLogLevel.INFO
  570. cli.add_typer(db_cli, name="db", help="Subcommands for managing the database schema.")
  571. cli.add_typer(script_cli, name="script", help="Subcommands running helper scripts.")
  572. cli.add_typer(
  573. hosting_cli,
  574. name="cloud",
  575. help="Subcommands for managing the reflex cloud.",
  576. )
  577. cli.add_typer(
  578. custom_components_cli,
  579. name="component",
  580. help="Subcommands for creating and publishing Custom Components.",
  581. )
  582. if __name__ == "__main__":
  583. cli()