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

如何用Python Requests模块构建批量HTTP请求(GCP DNS场景)

使用Python Requests实现GCP DNS批量请求

可以用Python Requests模块构建批量请求,把多个DNS记录创建请求打包成一个multipart/mixed的POST请求发送给GCP API,这样就能避免频繁触发速率限制。

下面是一个简单的示例代码,实现批量创建DNS记录:

import requests
import uuid

# 配置参数
AUTH_TOKEN = "your_gcp_auth_token"
PROJECT_ID = "your-project-id"
ZONE_NAME = "your-dns-zone"
BATCH_URL = "https://www.googleapis.com/batch/dns/v1"

# 生成唯一的边界字符串
boundary = f"batch_{uuid.uuid4().hex}"

# 构造批量请求的各个子请求
sub_requests = []

# 第一个DNS记录创建请求(A记录)
record1 = {
    "name": "test1.example.com.",
    "type": "A",
    "ttl": 300,
    "rrdatas": ["192.168.1.1"]
}
sub_request1 = (
    f"POST /dns/v1/projects/{PROJECT_ID}/managedZones/{ZONE_NAME}/changes HTTP/1.1\r\n"
    "Content-Type: application/json\r\n\r\n"
    f'{{"additions": [{str(record1).replace("\'", "\"")}]}}'
)
sub_requests.append(sub_request1)

# 第二个DNS记录创建请求(CNAME记录)
record2 = {
    "name": "test2.example.com.",
    "type": "CNAME",
    "ttl": 300,
    "rrdatas": ["test1.example.com."]
}
sub_request2 = (
    f"POST /dns/v1/projects/{PROJECT_ID}/managedZones/{ZONE_NAME}/changes HTTP/1.1\r\n"
    "Content-Type: application/json\r\n\r\n"
    f'{{"additions": [{str(record2).replace("\'", "\"")}]}}'
)
sub_requests.append(sub_request2)

# 构造multipart/mixed的请求体
body_parts = []
for idx, req in enumerate(sub_requests):
    body_parts.append(f"--{boundary}")
    body_parts.append("Content-Type: application/http")
    body_parts.append(f"Content-ID: <item{idx+1}:{uuid.uuid4().hex}@example.com>")
    body_parts.append("")
    body_parts.append(req)
body_parts.append(f"--{boundary}--")

# 拼接成完整的请求体
body = "\r\n".join(body_parts)

# 发送请求
headers = {
    "Authorization": f"Bearer {AUTH_TOKEN}",
    "Content-Type": f"multipart/mixed; boundary={boundary}"
}

response = requests.post(BATCH_URL, headers=headers, data=body)

# 处理响应
print(f"响应状态码: {response.status_code}")
print("响应内容:")
print(response.text)

关键说明

  • 边界字符串:用uuid生成唯一值,确保批量请求中子请求的分隔不会冲突
  • 子请求格式:每个子请求都是标准的HTTP请求,对应GCP DNS的记录变更接口,通过additions字段指定要添加的记录
  • 请求体拼接:严格按照multipart/mixed格式组织内容,每个子请求前加上边界标识和必要的头信息
  • 请求发送:设置正确的Authorization和Content-Type头,用Requests发送POST请求

注意事项

  • 替换代码中的AUTH_TOKEN、PROJECT_ID、ZONE_NAME为你的实际GCP资源信息
  • GCP批量请求单次最多支持100个子请求,超过需要拆分批次
  • 可以修改子请求的内容,实现DNS记录的删除(通过deletions字段)或其他操作

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.19 23:25:23