1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] How do I deploy a Heroku app with a Python script?

Discussão em 'Python' iniciado por Stack, Outubro 8, 2024.

  1. Stack

    Stack Membro Participativo

    def run_command(command: str) -> str:
    try:
    process = subprocess.run(
    command, capture_output=True, text=True, shell=True, check=True
    )
    return process.stdout.strip()
    except subprocess.CalledProcessError as e:
    logger.error(f"Command failed: {command}")
    logger.error(f"Error output: {e.stderr}")
    raise HerokuAppCreationError(f"Command failed: {e.stderr}")

    def create_heroku_app(bot_name: str, github_repo: str, branch: str, heroku_conn: heroku3.api.Heroku):
    logger.info(f"Starting Heroku app creation process for bot: {bot_name}")

    original_cwd = os.getcwd() # Save the original current working directory

    heroku_api_key = os.environ.get('HEROKU_API_KEY')
    if not heroku_api_key:
    logger.error("Heroku API key not found in environment variables")
    raise ValueError("Heroku API key not found in environment variables")

    logger.info("Heroku API Key is set")

    app_name = f"bot-{bot_name}-{str(uuid4())[:8]}"
    logger.info(f"Generated app name: {app_name}")

    temp_dir = 'temp'
    repo_name = github_repo.split('/')[-1]
    repo_path = os.path.join(temp_dir, repo_name)
    logger.info(f"Temporary directory path: {temp_dir}")
    logger.info(f"Repository path: {repo_path}")

    try:
    # Create Heroku app
    logger.info(f"Attempting to create Heroku app: {app_name}")
    app = heroku_conn.create_app(name=app_name, region_id_or_name='eu', stack_id_or_name="heroku-22")
    logger.info(f"Heroku app created successfully: {app.name}")

    # Clone GitHub repo
    logger.info(f"Preparing to clone GitHub repository: {github_repo}")
    os.makedirs(temp_dir, exist_ok=True)
    repo_url = f"git@github.com:{github_repo}.git"
    logger.info(f"Cloning repository from URL: {repo_url}")
    logger.info(f"Current working directory: {os.getcwd()}")
    logger.info(f"Contents of current directory: {os.listdir()}")

    clone_command = f"git clone {repo_url} {repo_path}"
    logger.info(f"Attempting to clone using subprocess: {clone_command}")
    clone_output = run_command(clone_command)
    logger.info(f"Git clone output: {clone_output}")

    logger.info(f"Contents of repo_path after cloning: {os.listdir(repo_path)}")

    # Change directory to repo_path
    os.chdir(repo_path)
    logger.info(f"Changed working directory to repo_path: {repo_path}")
    # Set up Git remote for Heroku using SSH URL
    logger.info("Setting up Git remote for Heroku")
    add_remote_command = f"heroku git:remote -a {app_name}"
    logger.info(f"Adding Heroku remote with command: {add_remote_command}")
    add_remote_output = run_command(add_remote_command)
    logger.info(f"Add remote output: {add_remote_output}")

    # Set the remote URL to use SSH
    set_ssh_remote_command = f"git remote set-url heroku git@heroku.com:{app_name}.git"
    logger.info(f"Setting SSH remote URL with command: {set_ssh_remote_command}")
    set_ssh_remote_output = run_command(set_ssh_remote_command)
    logger.info(f"Set SSH remote URL output: {set_ssh_remote_output}")

    # Push to Heroku
    logger.info(f"Preparing to push to Heroku. Branch: {branch}")
    push_command = f"git push heroku {branch}:main"
    try:
    push_output = run_command(push_command)
    logger.info(f"Git push output: {push_output}")
    logger.info("Deployed to Heroku successfully")
    except HerokuAppCreationError as e:
    logger.error(f"Failed to push to Heroku: {str(e)}")
    raise

    # Get app info
    app_url = app.web_url
    logger.info(f"Heroku app URL: {app_url}")

    return app_name, app_url

    except Exception as e:
    logger.exception(f"Unexpected error occurred while creating Heroku app: {str(e)}")
    if os.path.exists(temp_dir):
    os.chdir(original_cwd) # Ensure we're not in the temp directory before deleting
    logger.info(f"Cleaning up temporary directory: {temp_dir}")
    if os.name == 'nt': # Windows
    logger.info("Detected Windows OS, using appropriate cleanup command")
    subprocess.run(f"rmdir /s /q {temp_dir}", shell=True)
    else: # Unix-like
    logger.info("Detected Unix-like OS, using appropriate cleanup command")
    shutil.rmtree(temp_dir)
    logger.info("Cleaned up temporary directory")
    return None, None

    finally:
    os.chdir(original_cwd) # Restore the original working directory
    logger.info("Finished Heroku app creation process")


    2024-10-06T17:47:14.787486+00:00 app[worker.1]: INFO:service:Starting Heroku app creation process for bot: chapman
    2024-10-06T17:47:14.787537+00:00 app[worker.1]: INFO:service:Heroku API Key is set
    2024-10-06T17:47:14.787558+00:00 app[worker.1]: INFO:service:Generated app name: bot-chapman-941b996a
    2024-10-06T17:47:14.787582+00:00 app[worker.1]: INFO:service:Temporary directory path: temp
    2024-10-06T17:47:14.787600+00:00 app[worker.1]: INFO:service:Repository path: temp/og-ai-bots
    2024-10-06T17:47:14.787618+00:00 app[worker.1]: INFO:service:Attempting to create Heroku app: bot-chapman-941b996a
    2024-10-06T17:47:15.069882+00:00 app[worker.1]: INFO:service:Heroku app created successfully: bot-chapman-941b996a
    2024-10-06T17:47:15.069898+00:00 app[worker.1]: INFO:service:preparing to clone GitHub repository: riz3e/og-ai-bots
    2024-10-06T17:47:15.070096+00:00 app[worker.1]: INFO:service:Cloning repository from URL: git@github.com:riz3e/og-ai-bots.git
    2024-10-06T17:47:15.070120+00:00 app[worker.1]: INFO:service:Current working directory: /app/main/bots
    2024-10-06T17:47:15.070186+00:00 app[worker.1]: INFO:service:Contents of current directory: ['redis_conn.py', 'schemas.py', 'main_bots.py', 'telegram_bot.py', 'worker.py', '__init__.py', 'service.py', 'test.py', 'requirements.txt', 'chat_service.py', 'temp']
    2024-10-06T17:47:15.070209+00:00 app[worker.1]: INFO:service:Attempting to clone using subprocess: git clone git@github.com:riz3e/og-ai-bots.git temp/og-ai-bots
    2024-10-06T17:47:16.118541+00:00 app[worker.1]: INFO:service:Git clone output:
    2024-10-06T17:47:16.118681+00:00 app[worker.1]: INFO:service:Contents of repo_path after cloning: ['whatsapp_bot.py', '.git', 'main_bots.py', 'telegram_bot.py', 'Procfile', 'package-lock.json', '.gitignore', 'service.py', 'requirements.txt', 'chat_service.py', 'package.json']
    2024-10-06T17:47:16.118721+00:00 app[worker.1]: INFO:service:Changed working directory to repo_path: temp/og-ai-bots
    2024-10-06T17:47:16.118750+00:00 app[worker.1]: INFO:service:Setting up Git remote for Heroku
    2024-10-06T17:47:16.118779+00:00 app[worker.1]: INFO:service:Adding Heroku remote with command: heroku git:remote -a bot-chapman-941b996a
    2024-10-06T17:47:17.405989+00:00 app[worker.1]: INFO:service:Add remote output: set git remote heroku to https://git.heroku.com/bot-chapman-941b996a.git
    2024-10-06T17:47:17.406015+00:00 app[worker.1]: INFO:service:Setting SSH remote URL with command: git remote set-url heroku git@heroku.com:bot-chapman-941b996a.git
    2024-10-06T17:47:17.408566+00:00 app[worker.1]: INFO:service:Set SSH remote URL output:
    2024-10-06T17:47:17.408594+00:00 app[worker.1]: INFO:service:preparing to push to Heroku. Branch: main
    2024-10-06T17:56:01.100495+00:00 app[worker.1]: ERROR:service:Command failed: git push heroku main:main
    2024-10-06T17:56:01.100510+00:00 app[worker.1]: ERROR:service:Error output: ssh: connect to host heroku.com port 22: Network is unreachable
    2024-10-06T17:56:01.100511+00:00 app[worker.1]: fatal: Could not read from remote repository.
    2024-10-06T17:56:01.100513+00:00 app[worker.1]:
    2024-10-06T17:56:01.100513+00:00 app[worker.1]: Please make sure you have the correct access rights
    2024-10-06T17:56:01.100514+00:00 app[worker.1]: and the repository exists.
    2024-10-06T17:56:01.100514+00:00 app[worker.1]:
    2024-10-06T17:56:01.100543+00:00 app[worker.1]: ERROR:service:Failed to push to Heroku: Command failed: ssh: connect to host heroku.com port 22: Network is unreachable
    2024-10-06T17:56:01.100543+00:00 app[worker.1]: fatal: Could not read from remote repository.
    2024-10-06T17:56:01.100543+00:00 app[worker.1]:
    2024-10-06T17:56:01.100543+00:00 app[worker.1]: Please make sure you have the correct access rights
    2024-10-06T17:56:01.100544+00:00 app[worker.1]: and the repository exists.
    2024-10-06T17:56:01.100544+00:00 app[worker.1]:
    2024-10-06T17:56:01.101223+00:00 app[worker.1]: ERROR:service:Unexpected error occurred while creating Heroku app: Command failed: ssh: connect to host heroku.com port 22: Network is unreachable


    heroku API KEY is set in env, git SSH key set either

    Continue reading...

Compartilhe esta Página