pc.py 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  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 rich.prompt import Prompt
  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. # Finish initializing the app.
  35. utils.console.log(f"[bold green]Finished Initializing: {app_name}")
  36. @cli.command()
  37. def run(
  38. env: constants.Env = typer.Option(
  39. constants.Env.DEV, help="The environment to run the app in."
  40. ),
  41. frontend: bool = typer.Option(
  42. True, "--no-frontend", help="Disable frontend execution."
  43. ),
  44. backend: bool = typer.Option(
  45. True, "--no-backend", help="Disable backend execution."
  46. ),
  47. loglevel: constants.LogLevel = typer.Option(
  48. constants.LogLevel.ERROR, help="The log level to use."
  49. ),
  50. port: str = typer.Option(None, help="Specify a different port."),
  51. ):
  52. """Run the app in the current directory."""
  53. frontend_port = utils.get_config().port if port is None else port
  54. backend_port = utils.get_api_port()
  55. # If something is running on the ports, ask the user if they want to kill or change it.
  56. if utils.is_process_on_port(frontend_port):
  57. frontend_port = utils.change_or_terminate_port(frontend_port, "frontend")
  58. if utils.is_process_on_port(backend_port):
  59. backend_port = utils.change_or_terminate_port(backend_port, "backend")
  60. # Check that the app is initialized.
  61. if frontend and not utils.is_initialized():
  62. utils.console.print(
  63. "[red]The app is not initialized. Run [bold]pc init[/bold] first."
  64. )
  65. raise typer.Exit()
  66. # Check that the template is up to date.
  67. if frontend and not utils.is_latest_template():
  68. utils.console.print(
  69. "[red]The base app template has updated. Run [bold]pc init[/bold] again."
  70. )
  71. raise typer.Exit()
  72. # Get the app module.
  73. utils.console.rule("[bold]Starting Pynecone App")
  74. app = utils.get_app()
  75. # Get the frontend and backend commands, based on the environment.
  76. frontend_cmd = backend_cmd = None
  77. if env == constants.Env.DEV:
  78. frontend_cmd, backend_cmd = utils.run_frontend, utils.run_backend
  79. if env == constants.Env.PROD:
  80. frontend_cmd, backend_cmd = utils.run_frontend_prod, utils.run_backend_prod
  81. assert frontend_cmd and backend_cmd, "Invalid env"
  82. # Run the frontend and backend.
  83. try:
  84. if frontend:
  85. frontend_cmd(app.app, Path.cwd(), frontend_port)
  86. if backend:
  87. backend_cmd(app.__name__, port=int(backend_port), loglevel=loglevel)
  88. finally:
  89. utils.kill_process_on_port(frontend_port)
  90. utils.kill_process_on_port(backend_port)
  91. @cli.command()
  92. def deploy(dry_run: bool = typer.Option(False, help="Whether to run a dry run.")):
  93. """Deploy the app to the Pynecone hosting service."""
  94. # Get the app config.
  95. config = utils.get_config()
  96. config.api_url = utils.get_production_backend_url()
  97. # Check if the deploy url is set.
  98. if config.deploy_url is None:
  99. typer.echo("This feature is coming soon!")
  100. return
  101. # Compile the app in production mode.
  102. typer.echo("Compiling production app")
  103. app = utils.get_app().app
  104. utils.export_app(app, zip=True)
  105. # Exit early if this is a dry run.
  106. if dry_run:
  107. return
  108. # Deploy the app.
  109. data = {"userId": config.username, "projectId": config.app_name}
  110. original_response = httpx.get(config.deploy_url, params=data)
  111. response = original_response.json()
  112. frontend = response["frontend_resources_url"]
  113. backend = response["backend_resources_url"]
  114. # Upload the frontend and backend.
  115. with open(constants.FRONTEND_ZIP, "rb") as f:
  116. response = httpx.put(frontend, data=f) # type: ignore
  117. with open(constants.BACKEND_ZIP, "rb") as f:
  118. response = httpx.put(backend, data=f) # type: ignore
  119. @cli.command()
  120. def export(
  121. zipping: bool = typer.Option(
  122. True, "--no-zip", help="Disable zip for backend and frontend exports."
  123. )
  124. ):
  125. """Export the app to a zip file."""
  126. # Get the app config.
  127. config = utils.get_config()
  128. config.api_url = utils.get_production_backend_url()
  129. # Compile the app in production mode and export it.
  130. utils.console.rule("[bold]Compiling production app and preparing for export.")
  131. app = utils.get_app().app
  132. utils.export_app(app, zip=zipping)
  133. if zipping:
  134. utils.console.rule(
  135. """Backend & Frontend compiled. See [green bold]backend.zip[/green bold]
  136. and [green bold]frontend.zip[/green bold]."""
  137. )
  138. else:
  139. utils.console.rule(
  140. """Backend & Frontend compiled. See [green bold]app[/green bold]
  141. and [green bold].web/_static[/green bold] directories."""
  142. )
  143. main = cli
  144. if __name__ == "__main__":
  145. main()