0

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!

David Lopez
  • 73
  • 1
  • 7
  • I'm not quite sure I understand your question, but your try/except is *outside* your loop so once you've got an exception the loop is done and there won't be any further iterations. – Gareth McCaughan May 10 '16 at 16:40
  • 1
    Incidentally, it's usually a bad idea to say just `except:` because it may catch errors you didn't actually want it to catch... – Gareth McCaughan May 10 '16 at 16:41
  • Sorry @GarethMcCaughan I didn't put the loop but is outside at the first line of the code. – David Lopez May 10 '16 at 16:44
  • Why didn't you include the loop? – Gareth McCaughan May 10 '16 at 16:45
  • I think it would be extremely helpful to have more information about your problem. What actual exception are you hitting? Why do you expect not to get the same exception the next time around the loop? Is it the same exception you're getting in later iterations, or a different one? Etc. – Gareth McCaughan May 10 '16 at 16:46
  • @GarethMcCaughan, I'm trying to connect to an api via urllib2 with diferent machines, this machines are in a list. I iterate over this list and when a urllib.open throws an exception httplib.HTTPException, the next iterate with another machine enter to the httplib.HTTPException too. – David Lopez May 10 '16 at 17:03
  • Can you show us the actual traceback? It may have more information about the exception you're getting. Generally an HTTPException is meant to indicate that something pretty bad happened (connection timed out, URL is invalid, etc.) and just eyeballing your code it seems like it wouldn't be very surprising if that tended to be true for all attempts or none. – Gareth McCaughan May 10 '16 at 17:10
  • @GarethMcCaughan If I take away the first try/except appears a BadStatusLine error: Exception Type: BadStatusLine – David Lopez May 10 '16 at 17:15
  • @DavidLopez httplib.BadStatusLine can be raised when server goes down and doesn't send any response. have you checked what's going on localhost:9191 ? – Andriy Ivaneyko May 10 '16 at 17:39
  • BadStatusLine might also indicate that the server you're talking to is actually trying to speak some other protocol that isn't HTTP. You might find this http://stackoverflow.com/questions/10708828/how-to-fix-httplib-badstatusline-exception a useful first step towards diagnosis. – Gareth McCaughan May 11 '16 at 10:41
  • Yes @AndriyIvaneyko this is the problem, If I try with curl I recieve this message: curl: (52) Empty reply from server – David Lopez May 11 '16 at 12:55
  • @DavidLopez So you have to trace what's going on server ... python script is fine ... – Andriy Ivaneyko May 11 '16 at 13:17

0 Answers0