调用Trumail邮件验证API时出现KeyError: 'username'错误是什么原因?
问题修复方案
KeyError: 'username'报错原因
该报错是因为你直接通过下标访问接口返回的字典字段,但当触发速率限制、输入邮箱格式完全非法时,trumail接口返回的JSON结构不会包含username这类常规业务字段,甚至会直接返回错误结构,访问不存在的键就会触发KeyError。
修复方法
- 优先使用字典的
get()方法读取字段,第二个参数传入默认值,避免访问不存在的键时报错 - 增加接口返回校验逻辑,先判断返回内容是否是正常的业务结构,再做后续字段读取
速率限制问题解决
- 测试阶段可以把正常的接口返回结果存为本地JSON文件,后续测试直接读取本地文件,无需反复请求线上接口
- 增加请求间隔控制,每次请求后休眠10秒以上,降低触发限流的概率
- 增加限流自动重试逻辑,识别到限流返回后自动等待一段时间再重新发起请求
修改后的代码示例
import json import requests import sys import time emailInput = "" def printHelp(): print("正确用法: python test.py [邮箱地址]") if len(sys.argv) < 2: printHelp() sys.exit() elif len(sys.argv) == 2 and sys.argv[1] == "--help": printHelp() sys.exit() elif len(sys.argv) == 2 and sys.argv[1] != "--help": emailInput = str(sys.argv[1]) url = 'https://api.trumail.io/v2/lookups/json?email=' + str(emailInput) # 增加重试逻辑 retry_count = 0 max_retry = 3 emailInfo = {} while retry_count < max_retry: try: res = requests.get(url, timeout=10) res.raise_for_status() emailInfo = res.json() # 检测是否触发限流 if "error" in emailInfo and "rate limit" in emailInfo["error"].lower(): print(f"触发速率限制,等待15秒后重试,剩余重试次数:{max_retry - retry_count -1}") time.sleep(15) retry_count +=1 continue break except Exception as e: print(f"请求异常:{str(e)},等待5秒后重试") time.sleep(5) retry_count +=1 if not emailInfo: print("请求失败,未获取到有效返回数据") sys.exit() print("\n邮箱分析工具 1.0\n\n当前查询邮箱: " + sys.argv[1]) print("=====================================================") # 改用get方法读取字段,设置默认值 print("用户名: " + str(emailInfo.get("username", "无数据"))) print("域名: " + str(emailInfo.get("domain", "无数据"))) print("格式是否合法: " + str(emailInfo.get("validFormat", "无数据"))) print("是否可送达: " + str(emailInfo.get("deliverable", "无数据"))) print("收件箱是否已满: " + str(emailInfo.get("fullInbox", "无数据"))) print("主机是否存在: " + str(emailInfo.get("hostExists", "无数据"))) print("是否为 Catch All 域名: " + str(emailInfo.get("catchAll", "无数据"))) print("是否为临时邮箱: " + str(emailInfo.get("disposable", "无数据"))) print("是否为免费邮箱: " + str(emailInfo.get("free", "无数据")))
内容的提问来源于stack exchange,提问作者identity7
相关产品推荐
相关产品推荐

