reflex.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  1. """Reflex CLI to create, run, and deploy apps."""
  2. from __future__ import annotations
  3. import atexit
  4. from pathlib import Path
  5. import typer
  6. import typer.core
  7. from reflex_cli.v2.deployments import hosting_cli
  8. from reflex import constants
  9. from reflex.config import environment, get_config
  10. from reflex.custom_components.custom_components import custom_components_cli
  11. from reflex.state import reset_disk_state_manager
  12. from reflex.utils import console, redir, telemetry
  13. from reflex.utils.exec import should_use_granian
  14. from reflex.utils.terminal import colored
  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"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("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(loglevel) # pyright: ignore [reportArgumentType]
  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. + colored("reflex db makemigrations", attrs=("bold",))
  372. + " to create schema change scripts and "
  373. + colored("reflex db migrate", attrs=("bold",))
  374. + " to apply migrations to a new or existing database.",
  375. )
  376. return
  377. # Initialize the database.
  378. _skip_compile()
  379. prerequisites.get_compiled_app()
  380. model.Model.alembic_init()
  381. model.Model.migrate(autogenerate=True)
  382. @db_cli.command()
  383. def migrate():
  384. """Create or update database schema from migration scripts."""
  385. from reflex import model
  386. from reflex.utils import prerequisites
  387. # TODO see if we can use `get_app()` instead (no compile). Would _skip_compile still be needed then?
  388. _skip_compile()
  389. prerequisites.get_compiled_app()
  390. if not prerequisites.check_db_initialized():
  391. return
  392. model.Model.migrate()
  393. prerequisites.check_schema_up_to_date()
  394. @db_cli.command()
  395. def makemigrations(
  396. message: str = typer.Option(
  397. None, help="Human readable identifier for the generated revision."
  398. ),
  399. ):
  400. """Create autogenerated alembic migration scripts."""
  401. from alembic.util.exc import CommandError
  402. from reflex import model
  403. from reflex.utils import prerequisites
  404. # TODO see if we can use `get_app()` instead (no compile). Would _skip_compile still be needed then?
  405. _skip_compile()
  406. prerequisites.get_compiled_app()
  407. if not prerequisites.check_db_initialized():
  408. return
  409. with model.Model.get_db_engine().connect() as connection:
  410. try:
  411. model.Model.alembic_autogenerate(connection=connection, message=message)
  412. except CommandError as command_error:
  413. if "Target database is not up to date." not in str(command_error):
  414. raise
  415. console.error(
  416. f"{command_error} Run "
  417. + colored("reflex db migrate", attrs=("bold",))
  418. + " to update database."
  419. )
  420. @cli.command()
  421. def deploy(
  422. app_name: str | None = typer.Option(
  423. None,
  424. "--app-name",
  425. help="The name of the App to deploy under.",
  426. ),
  427. app_id: str = typer.Option(
  428. None,
  429. "--app-id",
  430. help="The ID of the App to deploy over.",
  431. ),
  432. regions: list[str] = typer.Option(
  433. [],
  434. "-r",
  435. "--region",
  436. help="The regions to deploy to. `reflex cloud regions` For multiple envs, repeat this option, e.g. --region sjc --region iad",
  437. ),
  438. envs: list[str] = typer.Option(
  439. [],
  440. "--env",
  441. help="The environment variables to set: <key>=<value>. For multiple envs, repeat this option, e.g. --env k1=v2 --env k2=v2.",
  442. ),
  443. vmtype: str | None = typer.Option(
  444. None,
  445. "--vmtype",
  446. help="Vm type id. Run `reflex cloud vmtypes` to get options.",
  447. ),
  448. hostname: str | None = typer.Option(
  449. None,
  450. "--hostname",
  451. help="The hostname of the frontend.",
  452. ),
  453. interactive: bool = typer.Option(
  454. True,
  455. help="Whether to list configuration options and ask for confirmation.",
  456. ),
  457. envfile: str | None = typer.Option(
  458. None,
  459. "--envfile",
  460. help="The path to an env file to use. Will override any envs set manually.",
  461. ),
  462. loglevel: constants.LogLevel | None = typer.Option(
  463. None, help="The log level to use."
  464. ),
  465. project: str | None = typer.Option(
  466. None,
  467. "--project",
  468. help="project id to deploy to",
  469. ),
  470. project_name: str | None = typer.Option(
  471. None,
  472. "--project-name",
  473. help="The name of the project to deploy to.",
  474. ),
  475. token: str | None = typer.Option(
  476. None,
  477. "--token",
  478. help="token to use for auth",
  479. ),
  480. config_path: str | None = typer.Option(
  481. None,
  482. "--config",
  483. help="path to the config file",
  484. ),
  485. ):
  486. """Deploy the app to the Reflex hosting service."""
  487. from reflex_cli.constants.base import LogLevel as HostingLogLevel
  488. from reflex_cli.utils import dependency
  489. from reflex_cli.v2 import cli as hosting_cli
  490. from reflex_cli.v2.deployments import check_version
  491. from reflex.utils import export as export_utils
  492. from reflex.utils import prerequisites
  493. if loglevel is not None:
  494. console.set_log_level(loglevel)
  495. config = get_config()
  496. loglevel = loglevel or config.loglevel
  497. app_name = app_name or config.app_name
  498. check_version()
  499. environment.REFLEX_COMPILE_CONTEXT.set(constants.CompileContext.DEPLOY)
  500. # Set the log level.
  501. console.set_log_level(loglevel)
  502. def convert_reflex_loglevel_to_reflex_cli_loglevel(
  503. loglevel: constants.LogLevel,
  504. ) -> HostingLogLevel:
  505. if loglevel == constants.LogLevel.DEBUG:
  506. return HostingLogLevel.DEBUG
  507. if loglevel == constants.LogLevel.INFO:
  508. return HostingLogLevel.INFO
  509. if loglevel == constants.LogLevel.WARNING:
  510. return HostingLogLevel.WARNING
  511. if loglevel == constants.LogLevel.ERROR:
  512. return HostingLogLevel.ERROR
  513. if loglevel == constants.LogLevel.CRITICAL:
  514. return HostingLogLevel.CRITICAL
  515. return HostingLogLevel.INFO
  516. # Only check requirements if interactive.
  517. # There is user interaction for requirements update.
  518. if interactive:
  519. dependency.check_requirements()
  520. # Check if we are set up.
  521. if prerequisites.needs_reinit(frontend=True):
  522. _init(name=config.app_name, loglevel=loglevel)
  523. prerequisites.check_latest_package_version(constants.ReflexHostingCLI.MODULE_NAME)
  524. hosting_cli.deploy(
  525. app_name=app_name,
  526. app_id=app_id,
  527. export_fn=lambda zip_dest_dir,
  528. api_url,
  529. deploy_url,
  530. frontend,
  531. backend,
  532. zipping: export_utils.export(
  533. zip_dest_dir=zip_dest_dir,
  534. api_url=api_url,
  535. deploy_url=deploy_url,
  536. frontend=frontend,
  537. backend=backend,
  538. zipping=zipping,
  539. loglevel=loglevel.subprocess_level(),
  540. ),
  541. regions=regions,
  542. envs=envs,
  543. vmtype=vmtype,
  544. envfile=envfile,
  545. hostname=hostname,
  546. interactive=interactive,
  547. loglevel=convert_reflex_loglevel_to_reflex_cli_loglevel(loglevel),
  548. token=token,
  549. project=project,
  550. project_name=project_name,
  551. **({"config_path": config_path} if config_path is not None else {}),
  552. )
  553. @cli.command()
  554. def rename(
  555. new_name: str = typer.Argument(..., help="The new name for the app."),
  556. loglevel: constants.LogLevel | None = typer.Option(
  557. None, help="The log level to use."
  558. ),
  559. ):
  560. """Rename the app in the current directory."""
  561. from reflex.utils import prerequisites
  562. loglevel = loglevel or get_config().loglevel
  563. prerequisites.validate_app_name(new_name)
  564. prerequisites.rename_app(new_name, loglevel)
  565. cli.add_typer(db_cli, name="db", help="Subcommands for managing the database schema.")
  566. cli.add_typer(script_cli, name="script", help="Subcommands running helper scripts.")
  567. cli.add_typer(
  568. hosting_cli,
  569. name="cloud",
  570. help="Subcommands for managing the reflex cloud.",
  571. )
  572. cli.add_typer(
  573. custom_components_cli,
  574. name="component",
  575. help="Subcommands for creating and publishing Custom Components.",
  576. )
  577. if __name__ == "__main__":
  578. cli()