reflex.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559
  1. """Reflex CLI to create, run, and deploy apps."""
  2. from __future__ import annotations
  3. import atexit
  4. import os
  5. import webbrowser
  6. from pathlib import Path
  7. from typing import List, Optional
  8. import typer
  9. import typer.core
  10. from reflex_cli.deployments import deployments_cli
  11. from reflex_cli.utils import dependency
  12. from reflex import constants
  13. from reflex.config import get_config
  14. from reflex.utils import console, telemetry
  15. # Disable typer+rich integration for help panels
  16. typer.core.rich = False # type: ignore
  17. # Create the app.
  18. try:
  19. cli = typer.Typer(add_completion=False, pretty_exceptions_enable=False)
  20. except TypeError:
  21. # Fallback for older typer versions.
  22. cli = typer.Typer(add_completion=False)
  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: constants.Templates.Kind | None = constants.Templates.Kind.BLANK,
  51. loglevel: constants.LogLevel = config.loglevel,
  52. ):
  53. """Initialize a new Reflex app in the given directory."""
  54. from reflex.utils import exec, prerequisites
  55. # Set the log level.
  56. console.set_log_level(loglevel)
  57. # Show system info
  58. exec.output_system_info()
  59. # Get the app name.
  60. app_name = prerequisites.get_default_app_name() if name is None else name
  61. console.rule(f"[bold]Initializing {app_name}")
  62. prerequisites.check_latest_package_version(constants.Reflex.MODULE_NAME)
  63. # Set up the web project.
  64. prerequisites.initialize_frontend_dependencies()
  65. # Migrate Pynecone projects to Reflex.
  66. prerequisites.migrate_to_reflex()
  67. # Set up the app directory, only if the config doesn't exist.
  68. if not os.path.exists(constants.Config.FILE):
  69. if template is None:
  70. template = prerequisites.prompt_for_template()
  71. prerequisites.create_config(app_name)
  72. prerequisites.initialize_app_directory(app_name, template)
  73. telemetry.send("init")
  74. else:
  75. telemetry.send("reinit")
  76. # Initialize the .gitignore.
  77. prerequisites.initialize_gitignore()
  78. # Initialize the requirements.txt.
  79. prerequisites.initialize_requirements_txt()
  80. # Finish initializing the app.
  81. console.success(f"Initialized {app_name}")
  82. @cli.command()
  83. def init(
  84. name: str = typer.Option(
  85. None, metavar="APP_NAME", help="The name of the app to initialize."
  86. ),
  87. template: constants.Templates.Kind = typer.Option(
  88. None,
  89. help="The template to initialize the app with.",
  90. ),
  91. loglevel: constants.LogLevel = typer.Option(
  92. config.loglevel, help="The log level to use."
  93. ),
  94. ):
  95. """Initialize a new Reflex app in the current directory."""
  96. _init(name, template, loglevel)
  97. def _run(
  98. env: constants.Env = constants.Env.DEV,
  99. frontend: bool = True,
  100. backend: bool = True,
  101. frontend_port: str = str(config.frontend_port),
  102. backend_port: str = str(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. os.environ["REFLEX_ENV_MODE"] = env.value
  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. prerequisites.check_initialized(frontend=frontend)
  122. # If something is running on the ports, ask the user if they want to kill or change it.
  123. if frontend and processes.is_process_on_port(frontend_port):
  124. frontend_port = processes.change_or_terminate_port(frontend_port, "frontend")
  125. if backend and processes.is_process_on_port(backend_port):
  126. backend_port = processes.change_or_terminate_port(backend_port, "backend")
  127. # Apply the new ports to the config.
  128. if frontend_port != str(config.frontend_port):
  129. config._set_persistent(frontend_port=frontend_port)
  130. if backend_port != str(config.backend_port):
  131. config._set_persistent(backend_port=backend_port)
  132. # Reload the config to make sure the env vars are persistent.
  133. get_config(reload=True)
  134. console.rule("[bold]Starting Reflex App")
  135. prerequisites.check_latest_package_version(constants.Reflex.MODULE_NAME)
  136. if frontend:
  137. prerequisites.update_next_config()
  138. # Get the app module.
  139. prerequisites.get_app()
  140. # Warn if schema is not up to date.
  141. prerequisites.check_schema_up_to_date()
  142. # Get the frontend and backend commands, based on the environment.
  143. setup_frontend = frontend_cmd = backend_cmd = None
  144. if env == constants.Env.DEV:
  145. setup_frontend, frontend_cmd, backend_cmd = (
  146. build.setup_frontend,
  147. exec.run_frontend,
  148. exec.run_backend,
  149. )
  150. if env == constants.Env.PROD:
  151. setup_frontend, frontend_cmd, backend_cmd = (
  152. build.setup_frontend_prod,
  153. exec.run_frontend_prod,
  154. exec.run_backend_prod,
  155. )
  156. assert setup_frontend and frontend_cmd and backend_cmd, "Invalid env"
  157. # Post a telemetry event.
  158. telemetry.send(f"run-{env.value}")
  159. # Display custom message when there is a keyboard interrupt.
  160. atexit.register(processes.atexit_handler)
  161. # Run the frontend and backend together.
  162. commands = []
  163. # Run the frontend on a separate thread.
  164. if frontend:
  165. setup_frontend(Path.cwd())
  166. commands.append((frontend_cmd, Path.cwd(), frontend_port))
  167. # In prod mode, run the backend on a separate thread.
  168. if backend and env == constants.Env.PROD:
  169. commands.append((backend_cmd, backend_host, backend_port))
  170. # Start the frontend and backend.
  171. with processes.run_concurrently_context(*commands):
  172. # In dev mode, run the backend on the main thread.
  173. if backend and env == constants.Env.DEV:
  174. backend_cmd(backend_host, int(backend_port))
  175. @cli.command()
  176. def run(
  177. env: constants.Env = typer.Option(
  178. constants.Env.DEV, help="The environment to run the app in."
  179. ),
  180. frontend: bool = typer.Option(
  181. False, "--frontend-only", help="Execute only frontend."
  182. ),
  183. backend: bool = typer.Option(False, "--backend-only", help="Execute only backend."),
  184. frontend_port: str = typer.Option(
  185. config.frontend_port, help="Specify a different frontend port."
  186. ),
  187. backend_port: str = typer.Option(
  188. config.backend_port, help="Specify a different backend port."
  189. ),
  190. backend_host: str = typer.Option(
  191. config.backend_host, help="Specify the backend host."
  192. ),
  193. loglevel: constants.LogLevel = typer.Option(
  194. config.loglevel, help="The log level to use."
  195. ),
  196. ):
  197. """Run the app in the current directory."""
  198. _run(env, frontend, backend, frontend_port, backend_port, backend_host, loglevel)
  199. @cli.command()
  200. def export(
  201. zipping: bool = typer.Option(
  202. True, "--no-zip", help="Disable zip for backend and frontend exports."
  203. ),
  204. frontend: bool = typer.Option(
  205. True, "--backend-only", help="Export only backend.", show_default=False
  206. ),
  207. backend: bool = typer.Option(
  208. True, "--frontend-only", help="Export only frontend.", show_default=False
  209. ),
  210. zip_dest_dir: str = typer.Option(
  211. os.getcwd(),
  212. help="The directory to export the zip files to.",
  213. show_default=False,
  214. ),
  215. upload_db_file: bool = typer.Option(
  216. False,
  217. help="Whether to exclude sqlite db files when exporting backend.",
  218. hidden=True,
  219. ),
  220. loglevel: constants.LogLevel = typer.Option(
  221. config.loglevel, help="The log level to use."
  222. ),
  223. ):
  224. """Export the app to a zip file."""
  225. from reflex.utils import export as export_utils
  226. export_utils.export(
  227. zipping=zipping,
  228. frontend=frontend,
  229. backend=backend,
  230. zip_dest_dir=zip_dest_dir,
  231. upload_db_file=upload_db_file,
  232. loglevel=loglevel,
  233. )
  234. @cli.command()
  235. def login(
  236. loglevel: constants.LogLevel = typer.Option(
  237. config.loglevel, help="The log level to use."
  238. ),
  239. ):
  240. """Authenticate with Reflex hosting service."""
  241. from reflex_cli.utils import hosting
  242. # Set the log level.
  243. console.set_log_level(loglevel)
  244. access_token, invitation_code = hosting.authenticated_token()
  245. if access_token:
  246. console.print("You already logged in.")
  247. return
  248. # If not already logged in, open a browser window/tab to the login page.
  249. access_token = hosting.authenticate_on_browser(invitation_code)
  250. if not access_token:
  251. console.error(f"Unable to authenticate. Please try again or contact support.")
  252. raise typer.Exit(1)
  253. console.print("Successfully logged in.")
  254. @cli.command()
  255. def logout(
  256. loglevel: constants.LogLevel = typer.Option(
  257. config.loglevel, help="The log level to use."
  258. ),
  259. ):
  260. """Log out of access to Reflex hosting service."""
  261. from reflex_cli.utils import hosting
  262. console.set_log_level(loglevel)
  263. hosting.log_out_on_browser()
  264. console.debug("Deleting access token from config locally")
  265. hosting.delete_token_from_config(include_invitation_code=True)
  266. db_cli = typer.Typer()
  267. def _skip_compile():
  268. """Skip the compile step."""
  269. os.environ[constants.SKIP_COMPILE_ENV_VAR] = "yes"
  270. @db_cli.command(name="init")
  271. def db_init():
  272. """Create database schema and migration configuration."""
  273. from reflex import model
  274. from reflex.utils import prerequisites
  275. # Check the database url.
  276. if config.db_url is None:
  277. console.error("db_url is not configured, cannot initialize.")
  278. return
  279. # Check the alembic config.
  280. if Path(constants.ALEMBIC_CONFIG).exists():
  281. console.error(
  282. "Database is already initialized. Use "
  283. "[bold]reflex db makemigrations[/bold] to create schema change "
  284. "scripts and [bold]reflex db migrate[/bold] to apply migrations "
  285. "to a new or existing database.",
  286. )
  287. return
  288. # Initialize the database.
  289. _skip_compile()
  290. prerequisites.get_app()
  291. model.Model.alembic_init()
  292. model.Model.migrate(autogenerate=True)
  293. @db_cli.command()
  294. def migrate():
  295. """Create or update database schema from migration scripts."""
  296. from reflex import model
  297. from reflex.utils import prerequisites
  298. _skip_compile()
  299. prerequisites.get_app()
  300. if not prerequisites.check_db_initialized():
  301. return
  302. model.Model.migrate()
  303. prerequisites.check_schema_up_to_date()
  304. @db_cli.command()
  305. def makemigrations(
  306. message: str = typer.Option(
  307. None, help="Human readable identifier for the generated revision."
  308. ),
  309. ):
  310. """Create autogenerated alembic migration scripts."""
  311. from alembic.util.exc import CommandError
  312. from reflex import model
  313. from reflex.utils import prerequisites
  314. _skip_compile()
  315. prerequisites.get_app()
  316. if not prerequisites.check_db_initialized():
  317. return
  318. with model.Model.get_db_engine().connect() as connection:
  319. try:
  320. model.Model.alembic_autogenerate(connection=connection, message=message)
  321. except CommandError as command_error:
  322. if "Target database is not up to date." not in str(command_error):
  323. raise
  324. console.error(
  325. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  326. )
  327. @cli.command()
  328. def deploy(
  329. key: Optional[str] = typer.Option(
  330. None,
  331. "-k",
  332. "--deployment-key",
  333. help="The name of the deployment. Domain name safe characters only.",
  334. ),
  335. app_name: str = typer.Option(
  336. config.app_name,
  337. "--app-name",
  338. help="The name of the App to deploy under.",
  339. hidden=True,
  340. ),
  341. regions: List[str] = typer.Option(
  342. list(),
  343. "-r",
  344. "--region",
  345. help="The regions to deploy to.",
  346. ),
  347. envs: List[str] = typer.Option(
  348. list(),
  349. "--env",
  350. help="The environment variables to set: <key>=<value>. For multiple envs, repeat this option, e.g. --env k1=v2 --env k2=v2.",
  351. ),
  352. cpus: Optional[int] = typer.Option(
  353. None, help="The number of CPUs to allocate.", hidden=True
  354. ),
  355. memory_mb: Optional[int] = typer.Option(
  356. None, help="The amount of memory to allocate.", hidden=True
  357. ),
  358. auto_start: Optional[bool] = typer.Option(
  359. None,
  360. help="Whether to auto start the instance.",
  361. hidden=True,
  362. ),
  363. auto_stop: Optional[bool] = typer.Option(
  364. None,
  365. help="Whether to auto stop the instance.",
  366. hidden=True,
  367. ),
  368. frontend_hostname: Optional[str] = typer.Option(
  369. None,
  370. "--frontend-hostname",
  371. help="The hostname of the frontend.",
  372. hidden=True,
  373. ),
  374. interactive: bool = typer.Option(
  375. True,
  376. help="Whether to list configuration options and ask for confirmation.",
  377. ),
  378. with_metrics: Optional[str] = typer.Option(
  379. None,
  380. help="Setting for metrics scraping for the deployment. Setup required in user code.",
  381. hidden=True,
  382. ),
  383. with_tracing: Optional[str] = typer.Option(
  384. None,
  385. help="Setting to export tracing for the deployment. Setup required in user code.",
  386. hidden=True,
  387. ),
  388. upload_db_file: bool = typer.Option(
  389. False,
  390. help="Whether to include local sqlite db files when uploading to hosting service.",
  391. hidden=True,
  392. ),
  393. loglevel: constants.LogLevel = typer.Option(
  394. config.loglevel, help="The log level to use."
  395. ),
  396. ):
  397. """Deploy the app to the Reflex hosting service."""
  398. from reflex_cli import cli as hosting_cli
  399. from reflex.utils import export as export_utils
  400. from reflex.utils import prerequisites
  401. # Set the log level.
  402. console.set_log_level(loglevel)
  403. # Only check requirements if interactive. There is user interaction for requirements update.
  404. if interactive:
  405. dependency.check_requirements()
  406. # Check if we are set up.
  407. prerequisites.check_initialized(frontend=True)
  408. prerequisites.check_latest_package_version(constants.ReflexHostingCLI.MODULE_NAME)
  409. hosting_cli.deploy(
  410. app_name=app_name,
  411. export_fn=lambda zip_dest_dir, api_url, deploy_url, frontend, backend, zipping: export_utils.export(
  412. zip_dest_dir=zip_dest_dir,
  413. api_url=api_url,
  414. deploy_url=deploy_url,
  415. frontend=frontend,
  416. backend=backend,
  417. zipping=zipping,
  418. loglevel=loglevel,
  419. upload_db_file=upload_db_file,
  420. ),
  421. key=key,
  422. regions=regions,
  423. envs=envs,
  424. cpus=cpus,
  425. memory_mb=memory_mb,
  426. auto_start=auto_start,
  427. auto_stop=auto_stop,
  428. frontend_hostname=frontend_hostname,
  429. interactive=interactive,
  430. with_metrics=with_metrics,
  431. with_tracing=with_tracing,
  432. loglevel=loglevel.value,
  433. )
  434. @cli.command()
  435. def demo(
  436. frontend_port: str = typer.Option(
  437. "3001", help="Specify a different frontend port."
  438. ),
  439. backend_port: str = typer.Option("8001", help="Specify a different backend port."),
  440. ):
  441. """Run the demo app."""
  442. # Open the demo app in a terminal.
  443. webbrowser.open("https://demo.reflex.run")
  444. # Later: open the demo app locally.
  445. # with tempfile.TemporaryDirectory() as tmp_dir:
  446. # os.chdir(tmp_dir)
  447. # _init(
  448. # name="reflex_demo",
  449. # template=constants.Templates.Kind.DEMO,
  450. # loglevel=constants.LogLevel.DEBUG,
  451. # )
  452. # _run(
  453. # frontend_port=frontend_port,
  454. # backend_port=backend_port,
  455. # loglevel=constants.LogLevel.DEBUG,
  456. # )
  457. cli.add_typer(db_cli, name="db", help="Subcommands for managing the database schema.")
  458. cli.add_typer(
  459. deployments_cli,
  460. name="deployments",
  461. help="Subcommands for managing the Deployments.",
  462. )
  463. if __name__ == "__main__":
  464. cli()