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

如何使用Python向Google Cloud Run服务发送POST请求?

Python实现Google身份令牌认证的POST请求

方法1:直接调用gcloud获取令牌(与你的curl命令逻辑一致)

如果你的环境已经配置好gcloud并能正常输出身份令牌,直接用Python调用gcloud命令获取令牌,再携带到请求头里即可:

import subprocess
import requests

# 调用gcloud命令获取身份令牌
token = subprocess.check_output(
    ["gcloud", "auth", "print-identity-token"],
    text=True
).strip()

# 发送POST请求
url = "你的目标API地址"
headers = {
    "Authorization": f"Bearer {token}",
    # 根据API需求添加其他头,比如Content-Type
    "Content-Type": "application/json"
}
# 如果有请求体,添加data或json参数
response = requests.post(url, headers=headers)

# 打印响应结果
print(response.status_code)
print(response.text)

方法2:用Google官方认证库(推荐,适合服务账号场景)

既然你已经用服务账号完成过其他Google服务的认证,推荐使用google-auth库直接生成令牌,不需要依赖gcloud命令,更适合脚本化部署:

首先安装依赖:

pip install google-auth requests

然后使用服务账号密钥文件(或默认应用凭据)获取令牌:

import requests
from google.oauth2 import service_account
from google.auth.transport.requests import Request

# 替换为你的服务账号密钥文件路径,或者留空使用默认凭据(如GCE/GKE环境)
SERVICE_ACCOUNT_FILE = "/path/to/your/service-account-key.json"
# 替换为目标API的受众(audience),如果不确定可以用gcloud命令里的目标API域名
AUDIENCE = "https://your-target-api.example.com"

# 加载服务账号凭据
credentials = service_account.IDTokenCredentials.from_service_account_file(
    SERVICE_ACCOUNT_FILE,
    target_audience=AUDIENCE
)

# 获取身份令牌
credentials.refresh(Request())
token = credentials.token

# 发送POST请求
url = "你的目标API地址"
headers = {
    "Authorization": f"Bearer {token}",
    "Content-Type": "application/json"
}
# 示例请求体(如果需要)
payload = {"key": "value"}
response = requests.post(url, headers=headers, json=payload)

# 验证响应
print(response.status_code)
print(response.json() if response.ok else response.text)

注意事项

  • 如果是在Google云环境(如GCE、GKE、Cloud Functions)中运行,不需要指定服务账号密钥文件,库会自动获取默认应用凭据
  • 目标API的AUDIENCE参数需要和API要求一致,部分Google服务的受众可以参考官方文档,自定义API的话通常是API的根域名
  • 确保服务账号拥有访问目标API的权限,否则会返回403错误

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.01 07:07:08