pc.py 7.9 KB

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