reflex.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617
  1. """Reflex CLI to create, run, and deploy apps."""
  2. from __future__ import annotations
  3. import atexit
  4. import os
  5. from pathlib import Path
  6. from typing import List, Optional
  7. import typer
  8. import typer.core
  9. from reflex_cli.deployments import deployments_cli
  10. from reflex_cli.utils import dependency
  11. from reflex import constants
  12. from reflex.config import EnvironmentVariables, get_config
  13. from reflex.custom_components.custom_components import custom_components_cli
  14. from reflex.state import reset_disk_state_manager
  15. from reflex.utils import console, redir, telemetry
  16. # Disable typer+rich integration for help panels
  17. typer.core.rich = False # type: ignore
  18. # Create the app.
  19. try:
  20. cli = typer.Typer(add_completion=False, pretty_exceptions_enable=False)
  21. except TypeError:
  22. # Fallback for older typer versions.
  23. cli = typer.Typer(add_completion=False)
  24. # Get the config.
  25. config = get_config()
  26. def version(value: bool):
  27. """Get the Reflex version.
  28. Args:
  29. value: Whether the version flag was passed.
  30. Raises:
  31. typer.Exit: If the version flag was passed.
  32. """
  33. if value:
  34. console.print(constants.Reflex.VERSION)
  35. raise typer.Exit()
  36. @cli.callback()
  37. def main(
  38. version: bool = typer.Option(
  39. None,
  40. "-v",
  41. "--version",
  42. callback=version,
  43. help="Get the Reflex version.",
  44. is_eager=True,
  45. ),
  46. ):
  47. """Reflex CLI to create, run, and deploy apps."""
  48. pass
  49. def _init(
  50. name: str,
  51. template: str | None = None,
  52. loglevel: constants.LogLevel = config.loglevel,
  53. ai: bool = False,
  54. ):
  55. """Initialize a new Reflex app in the given directory."""
  56. from reflex.utils import exec, prerequisites
  57. # Set the log level.
  58. console.set_log_level(loglevel)
  59. # Show system info
  60. exec.output_system_info()
  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. # Integrate with reflex.build.
  71. generation_hash = None
  72. if ai:
  73. if template is None:
  74. # If AI is requested and no template specified, redirect the user to reflex.build.
  75. generation_hash = redir.reflex_build_redirect()
  76. elif prerequisites.is_generation_hash(template):
  77. # Otherwise treat the template as a generation hash.
  78. generation_hash = template
  79. else:
  80. console.error(
  81. "Cannot use `--template` option with `--ai` option. Please remove `--template` option."
  82. )
  83. raise typer.Exit(2)
  84. template = constants.Templates.DEFAULT
  85. # Initialize the app.
  86. prerequisites.initialize_app(app_name, template)
  87. # If a reflex.build generation hash is available, download the code and apply it to the main module.
  88. if generation_hash:
  89. prerequisites.initialize_main_module_index_from_generation(
  90. app_name, generation_hash=generation_hash
  91. )
  92. # Initialize the .gitignore.
  93. prerequisites.initialize_gitignore()
  94. # Initialize the requirements.txt.
  95. prerequisites.initialize_requirements_txt()
  96. # Finish initializing the app.
  97. console.success(f"Initialized {app_name}")
  98. @cli.command()
  99. def init(
  100. name: str = typer.Option(
  101. None, metavar="APP_NAME", help="The name of the app to initialize."
  102. ),
  103. template: str = typer.Option(
  104. None,
  105. help="The template to initialize the app with.",
  106. ),
  107. loglevel: constants.LogLevel = typer.Option(
  108. config.loglevel, help="The log level to use."
  109. ),
  110. ai: bool = typer.Option(
  111. False,
  112. help="Use AI to create the initial template. Cannot be used with existing app or `--template` option.",
  113. ),
  114. ):
  115. """Initialize a new Reflex app in the current directory."""
  116. _init(name, template, loglevel, ai)
  117. def _run(
  118. env: constants.Env = constants.Env.DEV,
  119. frontend: bool = True,
  120. backend: bool = True,
  121. frontend_port: str = str(config.frontend_port),
  122. backend_port: str = str(config.backend_port),
  123. backend_host: str = config.backend_host,
  124. loglevel: constants.LogLevel = config.loglevel,
  125. ):
  126. """Run the app in the given directory."""
  127. from reflex.utils import build, exec, prerequisites, processes
  128. # Set the log level.
  129. console.set_log_level(loglevel)
  130. # Set env mode in the environment
  131. EnvironmentVariables.REFLEX_ENV_MODE.set(env)
  132. # Show system info
  133. exec.output_system_info()
  134. # If no --frontend-only and no --backend-only, then turn on frontend and backend both
  135. if not frontend and not backend:
  136. frontend = True
  137. backend = True
  138. if not frontend and backend:
  139. _skip_compile()
  140. # Check that the app is initialized.
  141. if prerequisites.needs_reinit(frontend=frontend):
  142. _init(name=config.app_name, loglevel=loglevel)
  143. # Delete the states folder if it exists.
  144. reset_disk_state_manager()
  145. # Find the next available open port if applicable.
  146. if frontend:
  147. frontend_port = processes.handle_port(
  148. "frontend", frontend_port, str(constants.DefaultPorts.FRONTEND_PORT)
  149. )
  150. if backend:
  151. backend_port = processes.handle_port(
  152. "backend", backend_port, str(constants.DefaultPorts.BACKEND_PORT)
  153. )
  154. # Apply the new ports to the config.
  155. if frontend_port != str(config.frontend_port):
  156. config._set_persistent(frontend_port=frontend_port)
  157. if backend_port != str(config.backend_port):
  158. config._set_persistent(backend_port=backend_port)
  159. # Reload the config to make sure the env vars are persistent.
  160. get_config(reload=True)
  161. console.rule("[bold]Starting Reflex App")
  162. prerequisites.check_latest_package_version(constants.Reflex.MODULE_NAME)
  163. if frontend:
  164. # Get the app module.
  165. prerequisites.get_compiled_app()
  166. # Warn if schema is not up to date.
  167. prerequisites.check_schema_up_to_date()
  168. # Get the frontend and backend commands, based on the environment.
  169. setup_frontend = frontend_cmd = backend_cmd = None
  170. if env == constants.Env.DEV:
  171. setup_frontend, frontend_cmd, backend_cmd = (
  172. build.setup_frontend,
  173. exec.run_frontend,
  174. exec.run_backend,
  175. )
  176. if env == constants.Env.PROD:
  177. setup_frontend, frontend_cmd, backend_cmd = (
  178. build.setup_frontend_prod,
  179. exec.run_frontend_prod,
  180. exec.run_backend_prod,
  181. )
  182. if not setup_frontend or not frontend_cmd or not backend_cmd:
  183. raise ValueError("Invalid env")
  184. # Post a telemetry event.
  185. telemetry.send(f"run-{env.value}")
  186. # Display custom message when there is a keyboard interrupt.
  187. atexit.register(processes.atexit_handler)
  188. # Run the frontend and backend together.
  189. commands = []
  190. # Run the frontend on a separate thread.
  191. if frontend:
  192. setup_frontend(Path.cwd())
  193. commands.append((frontend_cmd, Path.cwd(), frontend_port, backend))
  194. # In prod mode, run the backend on a separate thread.
  195. if backend and env == constants.Env.PROD:
  196. commands.append(
  197. (
  198. backend_cmd,
  199. backend_host,
  200. backend_port,
  201. loglevel.subprocess_level(),
  202. frontend,
  203. )
  204. )
  205. # Start the frontend and backend.
  206. with processes.run_concurrently_context(*commands):
  207. # In dev mode, run the backend on the main thread.
  208. if backend and env == constants.Env.DEV:
  209. backend_cmd(
  210. backend_host, int(backend_port), loglevel.subprocess_level(), frontend
  211. )
  212. # The windows uvicorn bug workaround
  213. # https://github.com/reflex-dev/reflex/issues/2335
  214. if constants.IS_WINDOWS and exec.frontend_process:
  215. # Sends SIGTERM in windows
  216. exec.kill(exec.frontend_process.pid)
  217. @cli.command()
  218. def run(
  219. env: constants.Env = typer.Option(
  220. constants.Env.DEV, help="The environment to run the app in."
  221. ),
  222. frontend: bool = typer.Option(
  223. False,
  224. "--frontend-only",
  225. help="Execute only frontend.",
  226. envvar=EnvironmentVariables.REFLEX_FRONTEND_ONLY.name,
  227. ),
  228. backend: bool = typer.Option(
  229. False,
  230. "--backend-only",
  231. help="Execute only backend.",
  232. envvar=EnvironmentVariables.REFLEX_BACKEND_ONLY.name,
  233. ),
  234. frontend_port: str = typer.Option(
  235. config.frontend_port, help="Specify a different frontend port."
  236. ),
  237. backend_port: str = typer.Option(
  238. config.backend_port, help="Specify a different backend port."
  239. ),
  240. backend_host: str = typer.Option(
  241. config.backend_host, help="Specify the backend host."
  242. ),
  243. loglevel: constants.LogLevel = typer.Option(
  244. config.loglevel, help="The log level to use."
  245. ),
  246. ):
  247. """Run the app in the current directory."""
  248. if frontend and backend:
  249. console.error("Cannot use both --frontend-only and --backend-only options.")
  250. raise typer.Exit(1)
  251. EnvironmentVariables.REFLEX_BACKEND_ONLY.set(backend)
  252. EnvironmentVariables.REFLEX_FRONTEND_ONLY.set(frontend)
  253. EnvironmentVariables.REFLEX_ENV_MODE.set(env)
  254. _run(env, frontend, backend, frontend_port, backend_port, backend_host, loglevel)
  255. @cli.command()
  256. def export(
  257. zipping: bool = typer.Option(
  258. True, "--no-zip", help="Disable zip for backend and frontend exports."
  259. ),
  260. frontend: bool = typer.Option(
  261. True, "--backend-only", help="Export only backend.", show_default=False
  262. ),
  263. backend: bool = typer.Option(
  264. True, "--frontend-only", help="Export only frontend.", show_default=False
  265. ),
  266. zip_dest_dir: str = typer.Option(
  267. os.getcwd(),
  268. help="The directory to export the zip files to.",
  269. show_default=False,
  270. ),
  271. upload_db_file: bool = typer.Option(
  272. False,
  273. help="Whether to exclude sqlite db files when exporting backend.",
  274. hidden=True,
  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. if prerequisites.needs_reinit(frontend=True):
  284. _init(name=config.app_name, loglevel=loglevel)
  285. export_utils.export(
  286. zipping=zipping,
  287. frontend=frontend,
  288. backend=backend,
  289. zip_dest_dir=zip_dest_dir,
  290. upload_db_file=upload_db_file,
  291. loglevel=loglevel.subprocess_level(),
  292. )
  293. def _login() -> str:
  294. """Helper function to authenticate with Reflex hosting service."""
  295. from reflex_cli.utils import hosting
  296. access_token, invitation_code = hosting.authenticated_token()
  297. if access_token:
  298. console.print("You already logged in.")
  299. return access_token
  300. # If not already logged in, open a browser window/tab to the login page.
  301. access_token = hosting.authenticate_on_browser(invitation_code)
  302. if not access_token:
  303. console.error("Unable to authenticate. Please try again or contact support.")
  304. raise typer.Exit(1)
  305. console.print("Successfully logged in.")
  306. return access_token
  307. @cli.command()
  308. def login(
  309. loglevel: constants.LogLevel = typer.Option(
  310. config.loglevel, help="The log level to use."
  311. ),
  312. ):
  313. """Authenticate with Reflex hosting service."""
  314. # Set the log level.
  315. console.set_log_level(loglevel)
  316. _login()
  317. @cli.command()
  318. def logout(
  319. loglevel: constants.LogLevel = typer.Option(
  320. config.loglevel, help="The log level to use."
  321. ),
  322. ):
  323. """Log out of access to Reflex hosting service."""
  324. from reflex_cli.utils import hosting
  325. console.set_log_level(loglevel)
  326. hosting.log_out_on_browser()
  327. console.debug("Deleting access token from config locally")
  328. hosting.delete_token_from_config(include_invitation_code=True)
  329. db_cli = typer.Typer()
  330. script_cli = typer.Typer()
  331. def _skip_compile():
  332. """Skip the compile step."""
  333. EnvironmentVariables.REFLEX_SKIP_COMPILE.set(True)
  334. @db_cli.command(name="init")
  335. def db_init():
  336. """Create database schema and migration configuration."""
  337. from reflex import model
  338. from reflex.utils import prerequisites
  339. # Check the database url.
  340. if config.db_url is None:
  341. console.error("db_url is not configured, cannot initialize.")
  342. return
  343. # Check the alembic config.
  344. if EnvironmentVariables.ALEMBIC_CONFIG.get().exists():
  345. console.error(
  346. "Database is already initialized. Use "
  347. "[bold]reflex db makemigrations[/bold] to create schema change "
  348. "scripts and [bold]reflex db migrate[/bold] to apply migrations "
  349. "to a new or existing database.",
  350. )
  351. return
  352. # Initialize the database.
  353. _skip_compile()
  354. prerequisites.get_compiled_app()
  355. model.Model.alembic_init()
  356. model.Model.migrate(autogenerate=True)
  357. @db_cli.command()
  358. def migrate():
  359. """Create or update database schema from migration scripts."""
  360. from reflex import model
  361. from reflex.utils import prerequisites
  362. # TODO see if we can use `get_app()` instead (no compile). Would _skip_compile still be needed then?
  363. _skip_compile()
  364. prerequisites.get_compiled_app()
  365. if not prerequisites.check_db_initialized():
  366. return
  367. model.Model.migrate()
  368. prerequisites.check_schema_up_to_date()
  369. @db_cli.command()
  370. def makemigrations(
  371. message: str = typer.Option(
  372. None, help="Human readable identifier for the generated revision."
  373. ),
  374. ):
  375. """Create autogenerated alembic migration scripts."""
  376. from alembic.util.exc import CommandError
  377. from reflex import model
  378. from reflex.utils import prerequisites
  379. # TODO see if we can use `get_app()` instead (no compile). Would _skip_compile still be needed then?
  380. _skip_compile()
  381. prerequisites.get_compiled_app()
  382. if not prerequisites.check_db_initialized():
  383. return
  384. with model.Model.get_db_engine().connect() as connection:
  385. try:
  386. model.Model.alembic_autogenerate(connection=connection, message=message)
  387. except CommandError as command_error:
  388. if "Target database is not up to date." not in str(command_error):
  389. raise
  390. console.error(
  391. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  392. )
  393. @cli.command()
  394. def deploy(
  395. key: Optional[str] = typer.Option(
  396. None,
  397. "-k",
  398. "--deployment-key",
  399. help="The name of the deployment. Domain name safe characters only.",
  400. ),
  401. app_name: str = typer.Option(
  402. config.app_name,
  403. "--app-name",
  404. help="The name of the App to deploy under.",
  405. hidden=True,
  406. ),
  407. regions: List[str] = typer.Option(
  408. list(),
  409. "-r",
  410. "--region",
  411. help="The regions to deploy to.",
  412. ),
  413. envs: List[str] = typer.Option(
  414. list(),
  415. "--env",
  416. help="The environment variables to set: <key>=<value>. For multiple envs, repeat this option, e.g. --env k1=v2 --env k2=v2.",
  417. ),
  418. cpus: Optional[int] = typer.Option(
  419. None, help="The number of CPUs to allocate.", hidden=True
  420. ),
  421. memory_mb: Optional[int] = typer.Option(
  422. None, help="The amount of memory to allocate.", hidden=True
  423. ),
  424. auto_start: Optional[bool] = typer.Option(
  425. None,
  426. help="Whether to auto start the instance.",
  427. hidden=True,
  428. ),
  429. auto_stop: Optional[bool] = typer.Option(
  430. None,
  431. help="Whether to auto stop the instance.",
  432. hidden=True,
  433. ),
  434. frontend_hostname: Optional[str] = typer.Option(
  435. None,
  436. "--frontend-hostname",
  437. help="The hostname of the frontend.",
  438. hidden=True,
  439. ),
  440. interactive: bool = typer.Option(
  441. True,
  442. help="Whether to list configuration options and ask for confirmation.",
  443. ),
  444. with_metrics: Optional[str] = typer.Option(
  445. None,
  446. help="Setting for metrics scraping for the deployment. Setup required in user code.",
  447. hidden=True,
  448. ),
  449. with_tracing: Optional[str] = typer.Option(
  450. None,
  451. help="Setting to export tracing for the deployment. Setup required in user code.",
  452. hidden=True,
  453. ),
  454. upload_db_file: bool = typer.Option(
  455. False,
  456. help="Whether to include local sqlite db files when uploading to hosting service.",
  457. hidden=True,
  458. ),
  459. loglevel: constants.LogLevel = typer.Option(
  460. config.loglevel, help="The log level to use."
  461. ),
  462. ):
  463. """Deploy the app to the Reflex hosting service."""
  464. from reflex_cli import cli as hosting_cli
  465. from reflex.utils import export as export_utils
  466. from reflex.utils import prerequisites
  467. # Set the log level.
  468. console.set_log_level(loglevel)
  469. # Only check requirements if interactive. There is user interaction for requirements update.
  470. if interactive:
  471. dependency.check_requirements()
  472. # Check if we are set up.
  473. if prerequisites.needs_reinit(frontend=True):
  474. _init(name=config.app_name, loglevel=loglevel)
  475. prerequisites.check_latest_package_version(constants.ReflexHostingCLI.MODULE_NAME)
  476. hosting_cli.deploy(
  477. app_name=app_name,
  478. export_fn=lambda zip_dest_dir,
  479. api_url,
  480. deploy_url,
  481. frontend,
  482. backend,
  483. zipping: export_utils.export(
  484. zip_dest_dir=zip_dest_dir,
  485. api_url=api_url,
  486. deploy_url=deploy_url,
  487. frontend=frontend,
  488. backend=backend,
  489. zipping=zipping,
  490. loglevel=loglevel.subprocess_level(),
  491. upload_db_file=upload_db_file,
  492. ),
  493. key=key,
  494. regions=regions,
  495. envs=envs,
  496. cpus=cpus,
  497. memory_mb=memory_mb,
  498. auto_start=auto_start,
  499. auto_stop=auto_stop,
  500. frontend_hostname=frontend_hostname,
  501. interactive=interactive,
  502. with_metrics=with_metrics,
  503. with_tracing=with_tracing,
  504. loglevel=loglevel.subprocess_level(),
  505. )
  506. cli.add_typer(db_cli, name="db", help="Subcommands for managing the database schema.")
  507. cli.add_typer(script_cli, name="script", help="Subcommands running helper scripts.")
  508. cli.add_typer(
  509. deployments_cli,
  510. name="deployments",
  511. help="Subcommands for managing the Deployments.",
  512. )
  513. cli.add_typer(
  514. custom_components_cli,
  515. name="component",
  516. help="Subcommands for creating and publishing Custom Components.",
  517. )
  518. if __name__ == "__main__":
  519. cli()