reflex.py 19 KB

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