You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过Python脚本调用Heroku CLI执行addons类相关命令?

方案1:直接通过Python调用系统已安装的Heroku CLI

这是实现需求最直接的方式,你可以用Python内置的subprocess模块执行外部CLI命令,无需额外适配Heroku3.py未封装的功能。

基础用法(已提前完成Heroku登录的场景)

import subprocess

# 替换为你自己的Heroku应用名称
app_name = "your-heroku-app-name"
cmd_result = subprocess.run(
    ["heroku", "pg:backups:capture", "--app", app_name],
    capture_output=True,
    text=True
)

if cmd_result.returncode == 0:
    print("备份捕获成功,输出信息:", cmd_result.stdout)
else:
    print("备份捕获失败,错误信息:", cmd_result.stderr)

无交互场景用法(无需提前登录)

如果是在服务器、CI/CD等无交互环境运行,你可以直接把Heroku API密钥注入环境变量,无需提前执行heroku login:

import subprocess
import os

# 替换为你自己的配置
os.environ["HEROKU_API_KEY"] = "your-heroku-api-key"
app_name = "your-heroku-app-name"

cmd_result = subprocess.run(
    ["heroku", "pg:backups:capture", "--app", app_name],
    capture_output=True,
    text=True
)
  • 注意:使用该方案前需要确保运行脚本的环境已经正确安装Heroku CLI,否则会出现命令找不到的错误。

方案2:直接调用Heroku API实现(无需安装CLI)

如果你不想依赖本地安装的Heroku CLI,也可以直接调用Heroku官方API完成备份捕获操作,无需通过Heroku3.py封装的接口:

import requests

# 替换为你自己的配置
HEROKU_API_KEY = "your-heroku-api-key"
APP_NAME = "your-heroku-app-name"

# 请求头通用配置
headers = {
    "Authorization": f"Bearer {HEROKU_API_KEY}",
    "Accept": "application/vnd.heroku+json; version=3"
}

# 第一步:获取应用下的PostgreSQL数据库addon ID
addons_resp = requests.get(
    f"https://api.heroku.com/apps/{APP_NAME}/addons",
    headers=headers
)
addons_resp.raise_for_status()
pg_addon = [addon for addon in addons_resp.json() if "heroku-postgresql" in addon["plan"]["name"]][0]

# 第二步:触发备份捕获任务
capture_resp = requests.post(
    f"https://api.heroku.com/client/v11/apps/{APP_NAME}/addons/{pg_addon['id']}/actions/backups/capture",
    headers=headers
)

if capture_resp.status_code == 201:
    print("备份任务触发成功")
else:
    print(f"备份触发失败,状态码:{capture_resp.status_code},错误信息:{capture_resp.text}")
  • 注意:使用该方案需要先安装requests库,执行pip install requests即可。

内容的提问来源于stack exchange,提问作者JayBee

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.27 04:24:07