python - python请求模块无法使用错误信息
问题描述
我不知道如何在标题中用词,但基本上我有一个 IP 地址 API,如果 API 有效,它会提供数据,如果不是,它会提供错误消息(https://ipapi.co/ {args[0]}/json/)。这个 API 的问题是成功时没有错误名称。所以我做了一个 if 语句来检查 API 是否返回错误:
API = f'https://ipapi.co/{args[0]}/json/'
json_data = requests.get(api).json()
if json_data['error'] == True:
print(f'There was an error with the API') # something like this.
else:
countryname = json_data['country_name']
countrycode = json_data['country_code']
region = json_data['region']
这样做的问题是,如果返回错误,那么它会这样说,但如果没有,我只会收到一个控制台错误,因为它是一个有效的 IP,因此没有返回错误名称。无论如何我可以检查是否有一个名为错误的名称?如果我的措辞不对,我很抱歉,英语不是我的第一语言。
解决方案
您可以get()
使用dict
. None
如果未找到密钥,它将返回,而不是引发异常:
if json_data.get('error'):
print(f'There was an error with the API') # something like this.
else:
countryname = json_data['country_name']
countrycode = json_data['country_code']
region = json_data['region']
推荐阅读
- go - 为什么,当我在 main 中打印一个指向函数中声明的变量的取消引用指针时,它不会打印垃圾内存吗?
- kubernetes - Kubernetes Jobs 是否有助于在后台执行耗时的微服务?
- git - 在 Visual Studio 2015 “从 git 提取数据时”出现错误
- math - 我们如何解决moodle filter wiris错误?
- css - 在每个断点上处理同一组 CSS 选择器。如何保持 CSS DRY?
- git - git中的全局配置和本地配置有什么区别?
- xml - 基于 XSLT 中的分组的计算问题
- macos - Apple SpeechRecognition 和听写占用超过 50% 的 CPU
- azure - 如何使用 terraform 资源提供者创建 azure 机器学习资源?
- c# - Handlebars C# if equals 比较