跳到主要内容

处理游标与偏移量分页

列表接口使用两类分页协议。调用前以当前 API 页面的参数和响应字段为准,不要假设所有列表接口采用相同方式。

游标分页​

游标由服务端生成。首次请求使用空游标或不传 cursor,后续请求始终使用上一次响应的 nextCursor。

def collect_by_cursor(fetch_page):
records = []
cursor = ""
while True:
page = fetch_page(cursor=cursor, size=100)
records.extend(page["items"])
if not page.get("hasMore"):
return records
cursor = page["nextCursor"]

不要自行计算游标,也不要在请求失败后直接跳到下一个游标。只有当前页处理成功后才保存 nextCursor。

偏移量分页​

偏移量表示当前页起点,limit 表示单页数量。每次根据实际返回数量推进 offset,直到已读取数量达到 total 或当前页为空。

def collect_by_offset(fetch_page):
records = []
offset = 0
while True:
page = fetch_page(offset=offset, limit=100)
items = page["items"]
records.extend(items)
offset += len(items)
if offset >= page["total"] or not items:
return records

生产检查​

  • 为每页请求设置超时、有限重试和速率限制。
  • 使用资源 ID 去重,处理分页期间的数据新增或删除。
  • 长任务保存已完成页和分页标记,支持失败后继续。
  • 不把 size 或 limit 设置为超过接口允许的最大值。

参考:原始示例。