pc.py 6.6 KB

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