如何在Python requests中跳过值为None的uid嵌套请求?
解决嵌套API请求中uid为null时的报错问题
直接通过判断uid是否为None(JSON返回的null对应Python的None)来跳过无效的嵌套请求,以下是完整的实现示例:
import requests # 替换为你的首次请求API地址 first_request_url = "https://your-first-api-endpoint.com" try: first_response = requests.get(first_request_url) first_response.raise_for_status() # 捕获请求失败的情况 results = first_response.json() except requests.exceptions.RequestException as e: print(f"首次请求失败: {e}") exit() for result in results: # 用get方法避免键不存在时抛出KeyError uid = result.get("uid") # 仅当uid不为None时发起嵌套请求 if uid is not None: second_request_url = f"https://registry.nbnatlas.org/ws/dataResource/{uid}" try: second_response = requests.get(second_request_url) second_response.raise_for_status() # 处理第二个请求的响应数据,这里按需修改逻辑 second_data = second_response.json() print(f"成功获取uid={uid}的资源数据") except requests.exceptions.RequestException as e: print(f"获取uid={uid}的资源失败: {e}") else: print("uid为null,跳过嵌套请求")
关键注意点:
- 使用
result.get("uid")而非直接result["uid"]:如果部分响应没有uid字段,前者会返回None,避免抛出KeyError - 核心判断
if uid is not None:精准匹配JSON返回的null值,确保只有有效uid才触发嵌套请求 - 加入异常捕获:用
try-except包裹请求,避免单个请求失败导致整个程序崩溃 - 可选扩展:如果uid可能出现空字符串的情况,可以把判断条件改为
if uid is not None and uid.strip(),过滤空值
内容的提问来源于stack exchange,提问作者h1m aga1n
相关产品推荐
相关产品推荐

