API 对接看似只是发送请求交付时却要面对分页中断、限流、超时和重复写入。可靠同步的关键不是无限重试而是保存游标、识别可重试错误并让同一页重复执行不会产生重复结果。一、把传输层与业务层分开importjsonimporttimefromurllib.errorimportHTTPErrorfromurllib.requestimportRequest,urlopendefget_json(url,attempts3):forattemptinrange(attempts):try:reqRequest(url,headers{User-Agent:sync-client/1.0})withurlopen(req,timeout15)asresponse:returnjson.load(response)exceptHTTPErrorasexc:ifexc.code!429orattemptattempts-1:raisetime.sleep(2**attempt)raiseRuntimeError(unreachable)只有明确的 429 才按上限退避。认证失败、参数错误等 4xx 应立即停止让调用方看到真实原因。二、用业务键实现幂等写入importsqlite3 dbsqlite3.connect(sync.db)db.execute(create table if not exists items(id text primary key, payload text))defsave(items):withdb:db.executemany(insert into items values(?, ?) on conflict(id) do update set payloadexcluded.payload,[(str(x[id]),json.dumps(x,ensure_asciiFalse))forxinitems],)输出示例page4 received100 upserted100 nextcursor_5游标应在该页事务提交后再保存。进程在两者之间退出时最多重复处理同一页但主键写入不会制造重复数据。三、第一轮与第二轮之间留下可恢复点本篇是系列第一轮的收束。验收时主动让请求在中间页失败再从记录的游标恢复比较恢复前后的唯一 ID 数量。成功标准是无遗漏、无重复且失败原因可见而不是脚本最终打印“完成”。 本文用有限重试、游标后移和主键写入搭建了可恢复的 API 同步骨架也完成了系列第一轮的基础能力闭环。 你对接 API 时最棘手的是分页协议、限流、签名认证还是重复数据 关注《Python 自动化接单实战》第二轮下一篇进入需要登录态与动态页面的浏览器流程。参考来源Dev.toThe Optimistic UI Race ConditionHacker NewsModern email can be built from borrowed parts