我目前正在使用python请求库与使用json的外部api进行交互。 每个端点都通过一个方法(api类)工作,并使用collect_data方法。
但是我希望刮刀在遇到http错误时继续运行(理想情况下将其输出到日志中)。
当我使用http.raise_for_status()
看起来我应该尝试使用try / except,但不确定如何在这里做到最好?
def scrape_full_address(self, house_no, postcode):
address_path = '/api/addresses'
address_url = self.api_source + address_path
payload = {
'houseNo': house_no,
'postcode': postcode,
}
return self.collect_data(url=address_url, method='get', payload=payload)
def collect_data(self, url, method, payload=None):
if method == 'get':
data = None
params = payload
elif method == 'post':
params = None
data = payload
response = getattr(requests, method)(url=url, params=params, json=data, headers=self.headers)
if response.status_code == 200:
return response.json()
else:
return response.raise_for_status()
答案 0 :(得分:2)
在try语句中的代码换行中调用scrape_full_address()时。
有关详细信息,请参阅:https://wiki.python.org/moin/HandlingExceptions
try:
scrape_full_address(659, 31052)
except HTTPError:
print "Oops! That caused an error. Try again..."