I'm trying to use urllib2 inside a loop with a try/except but when one iterate enter in the except, all the next iterations enter in the except too:
for machine_id in machines:
machine = Machine.objects.get(id=machine_id)
r2 = urllib2.Request('http://localhost:9191/run')
r2.add_header('Accept', 'application/json')
r2.add_header('Content-Type', 'application/json')
data = json.dumps({"client":"ssh", "tgt":machine.name, "fun": "state.sls", "arg":["update2", "nacl"]})
r2.add_data(data)
try:
resp2 = urllib2.urlopen(r2)
json_response = json.load(resp2)['return'][0]
json_response_m7 = json_response[machine.name]
try:
json_response_m7 = json_response_m7['return']
for key, value in json_response_m7.items():
if(value['result'] == False):
print(key)
print("\n")
print(value['changes']['stderr'])
data_return['key'].append(key)
data_return['error'].append(value['changes']['stderr'])
data_return['machine'].append(machine.name)
#data_return = {"key":key, "error": value['changes']['stderr']}
except:
print("except!!!!!!")
print(json_response_m7['stderr'])
data_return['key'].append('stderr:')
data_return['error'].append(json_response_m7['stderr'])
data_return['machine'].append(machine.name)
except (IOError, httplib.HTTPException):
print("Errooor")
data_return['key'].append('stderr: ')
data_return['error'].append('This machine is not added to the roster file')
data_return['machine'].append(machine.name)
the problem is with the first try/except. Can anyone help me please? Thanks!