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

如何在Python中实现API批量调用并按批次入库?

实现方案

核心思路是分批次收集+批量入库,同时控制总数据量不超过目标值,具体修改如下:

修改后的完整代码

import requests
import json

# 替换为你的实际请求头
headers = {"Authorization": "Bearer YOUR_TOKEN", "Content-Type": "application/json"}

total_collected = 0  # 累计获取的总条数
batch_requests = 0   # 当前批次已发起的请求次数
batch_data = []      # 当前批次待入库的数据
target_total = 121000  # 目标总条数
per_batch_requests = 50  # 每批发起50次请求

# 先处理第一次请求(无cursor)
initial_url = "https://somecompany.gorgias.com/api/tickets?limit=100&order_by=updated_datetime%3Adesc"
try:
    response = requests.get(initial_url, headers=headers, timeout=15)
    response.raise_for_status()
    resp = json.loads(response.text)
except Exception as e:
    print(f"初始请求失败: {str(e)}")
    exit()

# 收集第一批数据
current_data = resp['data']  # 注意:根据API实际返回结构调整这个字段
batch_data.extend(current_data)
total_collected += len(current_data)
batch_requests += 1

while True:
    # 先检查是否已经拿到足够数据
    if total_collected >= target_total:
        # 入库剩余的批量数据
        if batch_data:
            # 这里替换成你的入库逻辑,比如写入MySQL/PostgreSQL等
            print(f"入库剩余数据:{len(batch_data)}条,累计总条数:{total_collected}")
            batch_data = []
        break

    # 检查是否还有下一页数据
    if not resp['meta']['next_cursor']:
        # 无更多数据,入库剩余内容
        if batch_data:
            print(f"无更多数据,入库剩余:{len(batch_data)}条,累计总条数:{total_collected}")
            batch_data = []
        break

    # 发起下一次请求
    try:
        url = f"https://somecompany.gorgias.com/api/tickets?limit=100&order_by=updated_datetime%3Adesc&cursor={resp['meta']['next_cursor']}"
        response = requests.get(url, headers=headers, timeout=15)
        response.raise_for_status()
        resp = json.loads(response.text)
    except Exception as e:
        print(f"请求失败: {str(e)}")
        # 可选:重试逻辑,比如最多重试3次
        continue

    # 收集当前请求的数据
    current_data = resp['data']
    batch_data.extend(current_data)
    total_collected += len(current_data)
    batch_requests += 1

    # 每50次请求完成后执行入库
    if batch_requests >= per_batch_requests:
        # 执行入库操作
        print(f"批量入库:{len(batch_data)}条,累计总条数:{total_collected}")
        # insert_into_database(batch_data)  # 替换为实际入库代码
        # 重置批次计数器和数据容器
        batch_data = []
        batch_requests = 0

关键细节说明

  1. 初始请求单独处理:第一次请求不需要传入next_cursor,单独发起避免循环里的逻辑混乱
  2. 批次控制:用batch_requests计数,每到50次就触发入库,然后清空数据和计数器
  3. 终止条件:优先判断总条数是否达标,再检查是否还有下一页,确保不会多拿数据,也不会遗漏剩余数据
  4. 异常处理:加入了请求超时和HTTP错误捕获,避免单次请求失败导致整个程序崩溃,你可以根据需求加重试逻辑
  5. 数据结构适配:API返回的数据大概率在resp['data']里,要是你的接口结构不一样,记得修改这个字段

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 18:47:10