我有try / except块处理对某个客户端的API请求。
while attempts < 10:
try:
r = requests.post(server, data=contents,
auth=HTTPBasicAuth(service_userid, service_pswd))
r.raise_for_status()
except requests.exceptions.HTTPError as errh:
print ('Http Error:',errh)
attempts += 1
if attempts == 10:
body = 'Http Error: ' + str(errh)
subject = 'Failure'
sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)
except requests.exceptions.ConnectionError as errc:
print ('Error Connecting:',errc)
attempts += 1
if attempts == 10:
body = 'Error Connecting: ' + str(errh)
subject = 'Failure'
sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)
except requests.exceptions.Timeout as errt:
print ('Timeout Error:',errt)
attempts += 1
if attempts == 10:
body = 'Timeout Error: ' + str(errh)
subject = 'Failure'
sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)
except requests.exceptions.RequestException as err:
print ('Unidentified error: ',err)
attempts += 1
if attempts == 10:
body = 'Unidentified error: ' + str(errh)
subject = 'Failure'
sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)
如何简化上述代码? 一般来说,我想处理HTTP响应错误代码。我想发送一封包含特定错误信息的电子邮件,以防我在同一个电话上收到至少10个错误代码。
答案 0 :(得分:4)
由于要执行的操作在每种情况下都相同,只需将异常分组到一个,然后根据错误类/类名自定义消息:
except (requests.exceptions.HTTPError,requests.exceptions.ConnectionError,requests.exceptions.RequestException,requests.exceptions.Timeout) as err:
error_message = "{}: ".format(err.__class__.__name__,err)
print (error_message)
attempts += 1
if attempts == 10:
body = error_message
subject = 'Failure'
sendEmailMessage(SMPTHOST, fromEmailAddr, toEmailAddr, subject, body)
如果您需要间接,只需创建字典类名称=&gt;字符串/动作执行/无论如何。