1

now it works once if connected successfully, but if exception is met, it doesn't retry as I wish, just throwing:

Will retry: [Errno 111] Connection refused

It should return False if all attempts weren't successful and True if at least one returned an answer

Seems there's something complicated with 'while' needed, like

for attempt in range(attempts) and while True

Here's my code:

attempts = 10
for attempt in range(attempts):
   try:
       conn = httplib.HTTPConnection("server:80", timeout=5)
       conn.request("GET","/url")
       r = conn.getresponse()
   except socket.error, serr:
       print("Will retry: %s" % serr)
       conn.close()
   else:
       print("OK")
   finally:
       return False

I tried also:

for attempt in range(attempts):
   while True:
       try:

The same result...

1 Answer 1

1

Try using a counter and a flag inside a while loop.

def funct():
    flag = False
    counter = 0
    while True:
        counter += 1
        try:
           conn = httplib.HTTPConnection("server:80", timeout=5)
           conn.request("GET","/url")
           r = conn.getresponse()
           flag = True
           break
        except socket.error, serr:
           print("Will retry: %s" % serr)
           conn.close() 
        if counter>9:
           break
    return flag
Sign up to request clarification or add additional context in comments.

1 Comment

hum... i am python newbie, not sure if there is a better way to "encapsulate" the whole "http.conn" steps, so we don't have to use the slightly cumbersome while loop in every func() that i have

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.