1
0

reflex.py 19 KB

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