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

Python发起API请求后出现KeyError: 'data'报错的原因是什么?

问题原因分析
  • 最常见的原因是触发了Nanopool API的请求频率限制:多次固定间隔请求后接口触发限流规则,返回的响应结构不再包含data字段,而是会返回带有错误提示的结构体。
  • 网络波动或接口临时故障:请求出现超时、响应状态码非200的情况时,返回的内容并非预期的接口正常响应结构,自然不存在data字段。
  • 原代码未做任何容错处理:直接对请求结果调用.json()后就强制取data键,只要返回结构和预期不一致就会直接抛出KeyError。
修复方案
  1. 先校验请求状态码,确认接口正常响应后再解析内容
  2. 不要直接强制取data字段,改用字典get方法取值,同时新增异常捕获逻辑
  3. 出现异常时增加重试等待逻辑,避免直接崩溃
优化后代码示例
import requests
import time
import os

def programm():
    while True:
        url = "https://api.nanopool.org/v1/eth/network/timetonextepoch"
        puffer = 420
        try:
            resp = requests.get(url, timeout=10)
            # 先校验状态码
            if resp.status_code != 200:
                print(f"请求异常,状态码:{resp.status_code},120秒后重试")
                time.sleep(120)
                continue
            webseite = resp.json()
            # 安全取值
            zeit = webseite.get('data')
            if zeit is None:
                print(f"接口返回结构异常,完整返回内容:{webseite},120秒后重试")
                time.sleep(120)
                continue
            zeit = int(zeit)
        except Exception as e:
            print(f"请求或解析出错:{str(e)},120秒后重试")
            time.sleep(120)
            continue

        while zeit > puffer:
            try:
                resp = requests.get(url, timeout=10)
                if resp.status_code != 200:
                    print(f"请求异常,状态码:{resp.status_code},60秒后重试")
                    time.sleep(60)
                    continue
                webseite = resp.json()
                zeit = webseite.get('data')
                if zeit is None:
                    print(f"接口返回结构异常,完整返回内容:{webseite},60秒后重试")
                    time.sleep(60)
                    continue
                zeit = int(zeit)
            except Exception as e:
                print(f"请求或解析出错:{str(e)},60秒后重试")
                time.sleep(60)
                continue

            print("Zeit zum DAG-Wechsel in Sekunden:", zeit)
            time.sleep(60)
            
            if zeit < puffer:
                print("Neustart in", int(zeit))
                os.startfile("C:/Users/xxxx/Desktop/restart1.bat")
                print("restart")
                time.sleep(5000)
                break
        break

if __name__ == "__main__":
    programm()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 16:36:02