【发布时间】:2018-12-12 04:19:03
【问题描述】:
我正在努力处理 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'}}]
【问题讨论】:
-
在发送请求之前验证请求不是更聪明吗...?
-
脚本不仅要考虑每个国家,还要考虑每个城市和 DMA,这样编码起来很麻烦
-
我认为你想移动你的 else 语句或在你的迭代中添加一个辅助 else ,所以如果名称不匹配,它会返回一个错误,但你应该按照上面的说明来重构它。跨度>