如何正确处理来自json响应的错误

时间:2019-04-27 16:44:32

标签: python json api python-requests

首先,在编写python时,我是个菜鸟,所以到目前为止,我所做的很多事情都是学到的,

我在这里有这段代码

if buycott_token != '':
    print("Looking up in Buycott")
    url = "https://www.buycott.com/api/v4/products/lookup"
    headers = {
    'Content-Type': 'application/json'
    }
    data={'barcode':upc,
          'access_token':buycott_token
         }
    try:
        r = requests.get(url=url, json=data, headers=headers)
        j = r.json()
        if r.status_code == 200:
        print("Buycott found it so now we're going to gather some info here and then add it to the system")
        name = j['products'][0]['product_name']
        description = j['products'][0]['product_description']
        #We now have what we need to add it to grocy so lets do that
        #Sometimes buycott returns a success but it never actually does anything so lets just make sure that we have something
        if name != '':
            add_to_system(upc, name, description)
    except requests.exceptions.Timeout:
        print("The connection timed out")
    except requests.exceptions.TooManyRedirects:
        print ("Too many redirects")
    except requests.exceptions.RequestException as e:
        print e  

98%的时间都可以正常工作,没有任何问题。然后,我将使用条形码扫描仪进行扫描,然后得到

Traceback (most recent call last):
  File "./barcode_reader.py", line 231, in <module>
    increase_inventory(upc)
  File "./barcode_reader.py", line 34, in increase_inventory
    product_id_lookup(upc)
  File "./barcode_reader.py", line 79, in product_id_lookup
    upc_lookup(upc)
  File "./barcode_reader.py", line 128, in upc_lookup
    name = aj['products'][0]['product_name']
KeyError: 'products'

我确信这与json的返回方式有关。问题是,抛出该错误会杀死该脚本,就是这样。谢谢您的帮助。

2 个答案:

答案 0 :(得分:1)

问题是您的响应JSON中没有'products'键。如果不存在'products'键,则解决方法可能是提供默认值:

default_value = [{'product_name': '', 'product_description': ''}]
j.get('products', default_value)[0]['product_name']

或者您可以简单地检查您的回复是否具有产品密钥:

if 'products' not in j:
    return 'Product not found'

答案 1 :(得分:0)

我认为此错误是由于API无法为您提供正确的json作为响应。因此,我认为您可以从侧面检查密钥是否在API响应中。

if 'products' in j:
   name = j['products'][0]['product_name']
   description = j['products'][0]['product_description']
else:
   #Whatever you want when 'product' is not in API response