reflex.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332
  1. """Reflex CLI to create, run, and deploy apps."""
  2. import os
  3. import signal
  4. from pathlib import Path
  5. import httpx
  6. import typer
  7. from alembic.util.exc import CommandError
  8. from reflex import constants, model
  9. from reflex.config import get_config
  10. from reflex.utils import build, console, exec, prerequisites, processes, telemetry
  11. # Create the app.
  12. cli = typer.Typer(add_completion=False)
  13. def version(value: bool):
  14. """Get the Reflex version.
  15. Args:
  16. value: Whether the version flag was passed.
  17. Raises:
  18. typer.Exit: If the version flag was passed.
  19. """
  20. if value:
  21. console.print(constants.VERSION)
  22. raise typer.Exit()
  23. @cli.callback()
  24. def main(
  25. version: bool = typer.Option(
  26. None,
  27. "-v",
  28. "--version",
  29. callback=version,
  30. help="Get the Reflex version.",
  31. is_eager=True,
  32. ),
  33. ):
  34. """Reflex CLI to create, run, and deploy apps."""
  35. pass
  36. @cli.command()
  37. def init(
  38. name: str = typer.Option(
  39. None, metavar="APP_NAME", help="The name of the app to be initialized."
  40. ),
  41. template: constants.Template = typer.Option(
  42. constants.Template.DEFAULT, help="The template to initialize the app with."
  43. ),
  44. loglevel: constants.LogLevel = typer.Option(
  45. constants.LogLevel.INFO, help="The log level to use."
  46. ),
  47. ):
  48. """Initialize a new Reflex app in the current directory."""
  49. # Set the log level.
  50. console.set_log_level(loglevel)
  51. # Get the app name.
  52. app_name = prerequisites.get_default_app_name() if name is None else name
  53. console.rule(f"[bold]Initializing {app_name}")
  54. # Set up the web project.
  55. prerequisites.initialize_frontend_dependencies()
  56. # Migrate Pynecone projects to Reflex.
  57. prerequisites.migrate_to_reflex()
  58. # Set up the app directory, only if the config doesn't exist.
  59. config = get_config()
  60. if not os.path.exists(constants.CONFIG_FILE):
  61. prerequisites.create_config(app_name)
  62. prerequisites.initialize_app_directory(app_name, template)
  63. build.set_reflex_project_hash()
  64. telemetry.send("init", config.telemetry_enabled)
  65. else:
  66. telemetry.send("reinit", config.telemetry_enabled)
  67. # Initialize the .gitignore.
  68. prerequisites.initialize_gitignore()
  69. # Finish initializing the app.
  70. console.success(f"Initialized {app_name}")
  71. @cli.command()
  72. def run(
  73. env: constants.Env = typer.Option(
  74. get_config().env, help="The environment to run the app in."
  75. ),
  76. frontend: bool = typer.Option(
  77. False, "--frontend-only", help="Execute only frontend."
  78. ),
  79. backend: bool = typer.Option(False, "--backend-only", help="Execute only backend."),
  80. frontend_port: str = typer.Option(None, help="Specify a different frontend port."),
  81. backend_port: str = typer.Option(None, help="Specify a different backend port."),
  82. backend_host: str = typer.Option(None, help="Specify the backend host."),
  83. loglevel: constants.LogLevel = typer.Option(
  84. constants.LogLevel.INFO, help="The log level to use."
  85. ),
  86. ):
  87. """Run the app in the current directory."""
  88. # Set the log level.
  89. console.set_log_level(loglevel)
  90. # Set ports as os env variables to take precedence over config and
  91. # .env variables(if override_os_envs flag in config is set to False).
  92. build.set_os_env(
  93. frontend_port=frontend_port,
  94. backend_port=backend_port,
  95. backend_host=backend_host,
  96. )
  97. # Get the ports from the config.
  98. config = get_config()
  99. frontend_port = config.frontend_port if frontend_port is None else frontend_port
  100. backend_port = config.backend_port if backend_port is None else backend_port
  101. backend_host = config.backend_host if backend_host is None else backend_host
  102. # If no --frontend-only and no --backend-only, then turn on frontend and backend both
  103. if not frontend and not backend:
  104. frontend = True
  105. backend = True
  106. # Check that the app is initialized.
  107. prerequisites.check_initialized(frontend=frontend)
  108. # If something is running on the ports, ask the user if they want to kill or change it.
  109. if frontend and processes.is_process_on_port(frontend_port):
  110. frontend_port = processes.change_or_terminate_port(frontend_port, "frontend")
  111. if backend and processes.is_process_on_port(backend_port):
  112. backend_port = processes.change_or_terminate_port(backend_port, "backend")
  113. # Get the app module.
  114. console.rule("[bold]Starting Reflex App")
  115. app = prerequisites.get_app()
  116. # Check the admin dashboard settings.
  117. prerequisites.check_admin_settings()
  118. # Warn if schema is not up to date.
  119. prerequisites.check_schema_up_to_date()
  120. # Get the frontend and backend commands, based on the environment.
  121. setup_frontend = frontend_cmd = backend_cmd = None
  122. if env == constants.Env.DEV:
  123. setup_frontend, frontend_cmd, backend_cmd = (
  124. build.setup_frontend,
  125. exec.run_frontend,
  126. exec.run_backend,
  127. )
  128. if env == constants.Env.PROD:
  129. setup_frontend, frontend_cmd, backend_cmd = (
  130. build.setup_frontend_prod,
  131. exec.run_frontend_prod,
  132. exec.run_backend_prod,
  133. )
  134. assert setup_frontend and frontend_cmd and backend_cmd, "Invalid env"
  135. # Post a telemetry event.
  136. telemetry.send(f"run-{env.value}", config.telemetry_enabled)
  137. # Display custom message when there is a keyboard interrupt.
  138. signal.signal(signal.SIGINT, processes.catch_keyboard_interrupt)
  139. # Run the frontend and backend together.
  140. commands = []
  141. if frontend:
  142. setup_frontend(Path.cwd())
  143. commands.append((frontend_cmd, Path.cwd(), frontend_port))
  144. if backend:
  145. commands.append((backend_cmd, app.__name__, backend_host, backend_port))
  146. processes.run_concurrently(*commands)
  147. @cli.command()
  148. def deploy(dry_run: bool = typer.Option(False, help="Whether to run a dry run.")):
  149. """Deploy the app to the Reflex hosting service."""
  150. # Get the app config.
  151. config = get_config()
  152. # Check if the deploy url is set.
  153. if config.rxdeploy_url is None:
  154. typer.echo("This feature is coming soon!")
  155. return
  156. # Compile the app in production mode.
  157. typer.echo("Compiling production app")
  158. export()
  159. # Exit early if this is a dry run.
  160. if dry_run:
  161. return
  162. # Deploy the app.
  163. data = {"userId": config.username, "projectId": config.app_name}
  164. original_response = httpx.get(config.rxdeploy_url, params=data)
  165. response = original_response.json()
  166. frontend = response["frontend_resources_url"]
  167. backend = response["backend_resources_url"]
  168. # Upload the frontend and backend.
  169. with open(constants.FRONTEND_ZIP, "rb") as f:
  170. httpx.put(frontend, data=f) # type: ignore
  171. with open(constants.BACKEND_ZIP, "rb") as f:
  172. httpx.put(backend, data=f) # type: ignore
  173. @cli.command()
  174. def export(
  175. zipping: bool = typer.Option(
  176. True, "--no-zip", help="Disable zip for backend and frontend exports."
  177. ),
  178. frontend: bool = typer.Option(
  179. True, "--backend-only", help="Export only backend.", show_default=False
  180. ),
  181. backend: bool = typer.Option(
  182. True, "--frontend-only", help="Export only frontend.", show_default=False
  183. ),
  184. loglevel: constants.LogLevel = typer.Option(
  185. constants.LogLevel.INFO, help="The log level to use."
  186. ),
  187. ):
  188. """Export the app to a zip file."""
  189. # Set the log level.
  190. console.set_log_level(loglevel)
  191. # Check that the app is initialized.
  192. prerequisites.check_initialized(frontend=frontend)
  193. # Compile the app in production mode and export it.
  194. console.rule("[bold]Compiling production app and preparing for export.")
  195. if frontend:
  196. # Ensure module can be imported and app.compile() is called.
  197. prerequisites.get_app()
  198. # Set up .web directory and install frontend dependencies.
  199. build.setup_frontend(Path.cwd())
  200. # Export the app.
  201. config = get_config()
  202. build.export(
  203. backend=backend,
  204. frontend=frontend,
  205. zip=zipping,
  206. deploy_url=config.deploy_url,
  207. )
  208. # Post a telemetry event.
  209. telemetry.send("export", config.telemetry_enabled)
  210. if zipping:
  211. console.log(
  212. """Backend & Frontend compiled. See [green bold]backend.zip[/green bold]
  213. and [green bold]frontend.zip[/green bold]."""
  214. )
  215. else:
  216. console.log(
  217. """Backend & Frontend compiled. See [green bold]app[/green bold]
  218. and [green bold].web/_static[/green bold] directories."""
  219. )
  220. db_cli = typer.Typer()
  221. @db_cli.command(name="init")
  222. def db_init():
  223. """Create database schema and migration configuration."""
  224. # Check the database url.
  225. if get_config().db_url is None:
  226. console.error("db_url is not configured, cannot initialize.")
  227. return
  228. # Check the alembic config.
  229. if Path(constants.ALEMBIC_CONFIG).exists():
  230. console.error(
  231. "Database is already initialized. Use "
  232. "[bold]reflex db makemigrations[/bold] to create schema change "
  233. "scripts and [bold]reflex db migrate[/bold] to apply migrations "
  234. "to a new or existing database.",
  235. )
  236. return
  237. # Initialize the database.
  238. prerequisites.get_app()
  239. model.Model.alembic_init()
  240. model.Model.migrate(autogenerate=True)
  241. @db_cli.command()
  242. def migrate():
  243. """Create or update database schema from migration scripts."""
  244. prerequisites.get_app()
  245. if not prerequisites.check_db_initialized():
  246. return
  247. model.Model.migrate()
  248. prerequisites.check_schema_up_to_date()
  249. @db_cli.command()
  250. def makemigrations(
  251. message: str = typer.Option(
  252. None, help="Human readable identifier for the generated revision."
  253. ),
  254. ):
  255. """Create autogenerated alembic migration scripts."""
  256. prerequisites.get_app()
  257. if not prerequisites.check_db_initialized():
  258. return
  259. with model.Model.get_db_engine().connect() as connection:
  260. try:
  261. model.Model.alembic_autogenerate(connection=connection, message=message)
  262. except CommandError as command_error:
  263. if "Target database is not up to date." not in str(command_error):
  264. raise
  265. console.error(
  266. f"{command_error} Run [bold]reflex db migrate[/bold] to update database."
  267. )
  268. cli.add_typer(db_cli, name="db", help="Subcommands for managing the database schema.")
  269. if __name__ == "__main__":
  270. cli()