Python / API:处理服务器不返回的错误

时间:2018-12-12 04:19:04

标签: python api

我正在努力处理Outbrain API服务器未返回的错误。我要做的是使用国家名称向服务器发送GET请求,它返回包含所需ID值的JSON响应,但是当我输入带有错字的国家名称时,JSON响应为空而不是带有错误的JSON讯息(如果我没记错的话)。因此,我正在尝试自行处理错误,但无法正常工作。这是我的代码(其中csv [row] [2] = United Kinjdom ):

r = requests.get('https://api.outbrain.com/amplify/v0.1/locations/search?term=' + csv[row][2] + '&limit=7', headers=headers)
try:
    print(r.json())
    data = r.json()
    error()
except:
    print(r.text)
    data = r.text
    error()

for results in data:
    if results['geoType']:
        if results['geoType'] == 'Country' and results['name'] == csv[row][2]:
            print(results['id'])
            countryId = results['id']
    else:
        logText = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + ": Country name error"
        c.execute("INSERT INTO log VALUES (?)", [logText])
        conn.commit()
        os._exit(1)

第一次打印返回“ []”,并且代码似乎未到达“ else”语句,因此我可以将错误添加到日志数据库。

这是正确拼写国家/地区时服务器的响应:

[{'id': 'c20768bb56a25c22299c38801e935c3a', 'geoType': 'Country', 'name': 'United Kingdom', 'canonicalName': 'United Kingdom', 'code': 'GB'},
{'id': '7477c333ed4e1895b040efe45c30c816', 'geoType': 'Region', 'name': 'Darlington', 'canonicalName': 'Darlington, United Kingdom', 'code': 'D1', 'parent': {'id': 'c20768bb56a25c22299c38801e935c3a', 'geoType': 'Country', 'name': 'United Kingdom', 'canonicalName': 'United Kingdom', 'code': 'GB'}},
{'id': 'd9a9732283ec131e7fa422843449baa4', 'geoType': 'Region', 'name': 'Bath and North East Somerset', 'canonicalName': 'Bath and North East Somerset, United Kingdom', 'code': 'A4', 'parent': {'id': 'c20768bb56a25c22299c38801e935c3a', 'geoType': 'Country', 'name': 'United Kingdom', 'canonicalName': 'United Kingdom', 'code': 'GB'}}, 
{'id': '92b5f5ef7a5a25e60263e365982be9ad', 'geoType': 'Region', 'name': 'Northumberland', 'canonicalName': 'Northumberland, United Kingdom', 'code': 'J6', 'parent': {'id': 'c20768bb56a25c22299c38801e935c3a', 'geoType': 'Country', 'name': 'United Kingdom', 'canonicalName': 'United Kingdom', 'code': 'GB'}},
{'id': '3a83dddcd55e92aaab4b142c7858892d', 'geoType': 'Region', 'name': 'Vale of Glamorgan', 'canonicalName': 'Vale of Glamorgan, United Kingdom', 'code': 'Z3', 'parent': {'id': 'c20768bb56a25c22299c38801e935c3a', 'geoType': 'Country', 'name': 'United Kingdom', 'canonicalName': 'United Kingdom', 'code': 'GB'}},
{'id': '915c6d5814a9826e34e1a5c0a423797a', 'geoType': 'Region', 'name': 'Walsall', 'canonicalName': 'Walsall, United Kingdom', 'code': 'O8', 'parent':                     {'id': 'c20768bb56a25c22299c38801e935c3a', 'geoType': 'Country', 'name': 'United Kingdom', 'canonicalName': 'United Kingdom', 'code': 'GB'}},
{'id': 'e96bcc2de342e74e491d3b6ab95cfedc', 'geoType': 'Region', 'name': 'Tameside', 'canonicalName': 'Tameside, United Kingdom', 'code': 'O1', 'parent': {'id': 'c20768bb56a25c22299c38801e935c3a', 'geoType': 'Country', 'name': 'United Kingdom', 'canonicalName': 'United Kingdom', 'code': 'GB'}}]

2 个答案:

答案 0 :(得分:2)

根据您的问题,也许您的代码仅执行tryexcept部分。由于您的第一个print提供了输出[],因此服务器可能什么也不返回,甚至没有警告消息。由于您的数据为空列表,因此不会执行for循环。我担心的是,除了这里,您要尝试的Exception是什么。如果您需要处理服务器输入的错误(如果您输入错误),这意味着您收到一个空列表,那么我建议:

data = r.json()    
if not data: raise Exception

然后将此代码块放入except处理部分,而不是将它们放入其他部分(如果这是Exception发生时要发生的情况)。

logText = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + ": Country name error"
c.execute("INSERT INTO log VALUES (?)", [logText])
conn.commit()
os._exit(1)

此外,您使用的if results['geoType']等于if True,仅当'geoType'键的值不是None时,else部分才应仅当该值为None时才执行。这很危险,因为如果键不在结果中,它将立即引发一个Exception。我可能建议您在这里稍微具体一点,因为这可能会让您头疼。

答案 1 :(得分:1)

您应该先检查结果列表(data)是否为空,在这种情况下,您可以对其进行迭代,否则就不能进行迭代,这就是为什么从不输入else子句的原因。

r = requests.get('https://api.outbrain.com/amplify/v0.1/locations/search?term=' + csv[row][2] + '&limit=7', headers=headers)
try:
    print(r.json())
    data = r.json()
    error()
except:
    print(r.text)
    data = r.text
    error()

if data:    
    for result in data:
        if result.get('geoType') == 'Country' and result['name'] == csv[row][2]:
            print(result['id'])
            countryId = result['id']
else:
    logText = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()) + ": Country name error"
    c.execute("INSERT INTO log VALUES (?)", [logText])
    conn.commit()
    os._exit(1)