pc.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229
  1. """Pynecone CLI to create, run, and deploy apps."""
  2. import os
  3. import platform
  4. from pathlib import Path
  5. import httpx
  6. import typer
  7. from pynecone import constants
  8. from pynecone.config import get_config
  9. from pynecone.utils import build, console, exec, prerequisites, processes, telemetry
  10. # Create the app.
  11. cli = typer.Typer()
  12. @cli.command()
  13. def version():
  14. """Get the Pynecone version."""
  15. console.print(constants.VERSION)
  16. @cli.command()
  17. def init(
  18. name: str = typer.Option(None, help="Name of the app to be initialized."),
  19. template: constants.Template = typer.Option(
  20. constants.Template.DEFAULT, help="Template to use for the app."
  21. ),
  22. ):
  23. """Initialize a new Pynecone app in the current directory."""
  24. app_name = prerequisites.get_default_app_name() if name is None else name
  25. # Make sure they don't name the app "pynecone".
  26. if app_name == constants.MODULE_NAME:
  27. console.print(
  28. f"[red]The app directory cannot be named [bold]{constants.MODULE_NAME}."
  29. )
  30. raise typer.Exit()
  31. console.rule(f"[bold]Initializing {app_name}")
  32. # Set up the web directory.
  33. prerequisites.validate_and_install_bun()
  34. prerequisites.initialize_web_directory()
  35. # Set up the app directory, only if the config doesn't exist.
  36. if not os.path.exists(constants.CONFIG_FILE):
  37. prerequisites.create_config(app_name)
  38. prerequisites.initialize_app_directory(app_name, template)
  39. build.set_pynecone_project_hash()
  40. telemetry.send("init", get_config().telemetry_enabled)
  41. else:
  42. build.set_pynecone_project_hash()
  43. telemetry.send("reinit", get_config().telemetry_enabled)
  44. # Initialize the .gitignore.
  45. prerequisites.initialize_gitignore()
  46. # Finish initializing the app.
  47. console.log(f"[bold green]Finished Initializing: {app_name}")
  48. @cli.command()
  49. def run(
  50. env: constants.Env = typer.Option(
  51. constants.Env.DEV, help="The environment to run the app in."
  52. ),
  53. frontend: bool = typer.Option(
  54. False, "--frontend-only", help="Execute only frontend."
  55. ),
  56. backend: bool = typer.Option(False, "--backend-only", help="Execute only backend."),
  57. loglevel: constants.LogLevel = typer.Option(
  58. constants.LogLevel.ERROR, help="The log level to use."
  59. ),
  60. port: str = typer.Option(None, help="Specify a different frontend port."),
  61. backend_port: str = typer.Option(None, help="Specify a different backend port."),
  62. ):
  63. """Run the app in the current directory."""
  64. if platform.system() == "Windows":
  65. console.print(
  66. "[yellow][WARNING] We strongly advise you to use Windows Subsystem for Linux (WSL) for optimal performance when using Pynecone. Due to compatibility issues with one of our dependencies, Bun, you may experience slower performance on Windows. By using WSL, you can expect to see a significant speed increase."
  67. )
  68. frontend_port = get_config().port if port is None else port
  69. backend_port = get_config().backend_port if backend_port is None else backend_port
  70. # If --no-frontend-only and no --backend-only, then turn on frontend and backend both
  71. if not frontend and not backend:
  72. frontend = True
  73. backend = True
  74. # If something is running on the ports, ask the user if they want to kill or change it.
  75. if frontend and processes.is_process_on_port(frontend_port):
  76. frontend_port = processes.change_or_terminate_port(frontend_port, "frontend")
  77. if backend and processes.is_process_on_port(backend_port):
  78. backend_port = processes.change_or_terminate_port(backend_port, "backend")
  79. # Check that the app is initialized.
  80. if frontend and not prerequisites.is_initialized():
  81. console.print(
  82. "[red]The app is not initialized. Run [bold]pc init[/bold] first."
  83. )
  84. raise typer.Exit()
  85. # Check that the template is up to date.
  86. if frontend and not prerequisites.is_latest_template():
  87. console.print(
  88. "[red]The base app template has updated. Run [bold]pc init[/bold] again."
  89. )
  90. raise typer.Exit()
  91. # Get the app module.
  92. console.rule("[bold]Starting Pynecone App")
  93. app = prerequisites.get_app()
  94. # Get the frontend and backend commands, based on the environment.
  95. frontend_cmd = backend_cmd = None
  96. if env == constants.Env.DEV:
  97. frontend_cmd, backend_cmd = exec.run_frontend, exec.run_backend
  98. if env == constants.Env.PROD:
  99. frontend_cmd, backend_cmd = exec.run_frontend_prod, exec.run_backend_prod
  100. assert frontend_cmd and backend_cmd, "Invalid env"
  101. # Post a telemetry event.
  102. telemetry.send(f"run-{env.value}", get_config().telemetry_enabled)
  103. # Run the frontend and backend.
  104. try:
  105. if frontend:
  106. frontend_cmd(app.app, Path.cwd(), frontend_port)
  107. if backend:
  108. backend_cmd(app.__name__, port=int(backend_port), loglevel=loglevel)
  109. finally:
  110. if frontend:
  111. processes.kill_process_on_port(frontend_port)
  112. if backend:
  113. processes.kill_process_on_port(backend_port)
  114. @cli.command()
  115. def deploy(dry_run: bool = typer.Option(False, help="Whether to run a dry run.")):
  116. """Deploy the app to the Pynecone hosting service."""
  117. # Get the app config.
  118. config = get_config()
  119. config.api_url = prerequisites.get_production_backend_url()
  120. # Check if the deploy url is set.
  121. if config.pcdeploy_url is None:
  122. typer.echo("This feature is coming soon!")
  123. return
  124. # Compile the app in production mode.
  125. typer.echo("Compiling production app")
  126. app = prerequisites.get_app().app
  127. build.export_app(app, zip=True, deploy_url=config.deploy_url)
  128. # Exit early if this is a dry run.
  129. if dry_run:
  130. return
  131. # Deploy the app.
  132. data = {"userId": config.username, "projectId": config.app_name}
  133. original_response = httpx.get(config.pcdeploy_url, params=data)
  134. response = original_response.json()
  135. frontend = response["frontend_resources_url"]
  136. backend = response["backend_resources_url"]
  137. # Upload the frontend and backend.
  138. with open(constants.FRONTEND_ZIP, "rb") as f:
  139. httpx.put(frontend, data=f) # type: ignore
  140. with open(constants.BACKEND_ZIP, "rb") as f:
  141. httpx.put(backend, data=f) # type: ignore
  142. @cli.command()
  143. def export(
  144. zipping: bool = typer.Option(
  145. True, "--no-zip", help="Disable zip for backend and frontend exports."
  146. ),
  147. frontend: bool = typer.Option(
  148. True, "--backend-only", help="Export only backend.", show_default=False
  149. ),
  150. backend: bool = typer.Option(
  151. True, "--frontend-only", help="Export only frontend.", show_default=False
  152. ),
  153. for_pc_deploy: bool = typer.Option(
  154. False,
  155. "--for-pc-deploy",
  156. help="Whether export the app for Pynecone Deploy Service.",
  157. ),
  158. ):
  159. """Export the app to a zip file."""
  160. config = get_config()
  161. if for_pc_deploy:
  162. # Get the app config and modify the api_url base on username and app_name.
  163. config.api_url = prerequisites.get_production_backend_url()
  164. # Compile the app in production mode and export it.
  165. console.rule("[bold]Compiling production app and preparing for export.")
  166. app = prerequisites.get_app().app
  167. build.export_app(
  168. app,
  169. backend=backend,
  170. frontend=frontend,
  171. zip=zipping,
  172. deploy_url=config.deploy_url,
  173. )
  174. # Post a telemetry event.
  175. telemetry.send("export", get_config().telemetry_enabled)
  176. if zipping:
  177. console.rule(
  178. """Backend & Frontend compiled. See [green bold]backend.zip[/green bold]
  179. and [green bold]frontend.zip[/green bold]."""
  180. )
  181. else:
  182. console.rule(
  183. """Backend & Frontend compiled. See [green bold]app[/green bold]
  184. and [green bold].web/_static[/green bold] directories."""
  185. )
  186. main = cli
  187. if __name__ == "__main__":
  188. main()