reflex.py 20 KB

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