user4647247
user4647247

Reputation:

While loop with else

I am working with a while loop which I am trying to run for 5 minutes and check if it gets the http response code 200. The problem is if it doesn't get 200 it will be keep running, but it doesn't go to the else when the site should be up and running.

r = requests.head("http://www.testing.co.uk")
while r.status_code != 200:
    print "Response not == to 200."
    time.sleep(30)
else:
    print "Response is 200 - OK"

Upvotes: 0

Views: 1984

Answers (3)

mhawke
mhawke

Reputation: 87074

Try this which includes timeout checking up to approximately 5 minutes:

import time
from datetime import datetime, timedelta
import requests

FIVE_MINUTES = timedelta(minutes=1) * 5
RETRY_DELAY = 30

end_time = datetime.now() + FIVE_MINUTES

while datetime.now() < end_time:
    r = requests.head("http://www.testing.co.uk")
    if r.status_code == 200:
        print "Response is 200 - OK"
        break
    else:
        print "Response not == to 200."
        time.sleep(RETRY_DELAY)
else:
    print 'Timed out'

N.B approximately because each request will take an unpredictable period of time, e.g. a request might hang for 2 minutes, while other requests might fail immediately. Also, you should add exception handling because requests raise exceptions for failures such as "Connection refused".

Upvotes: 0

avim
avim

Reputation: 1019

the request should be looped:

numOfRequests = 1000
for i in range(numOfRequests):
    r = requests.head("http://www.testing.co.uk")
    if r.status_code == 200:
        print "Response is 200 - OK"
        break
    print "Response not == to 200."
    time.sleep(30)

Upvotes: 0

Malik Brahimi
Malik Brahimi

Reputation: 16711

Repeat the request.

r = requests.head("http://www.testing.co.uk")

while r.status_code != 200:
    print "Response not == to 200."
    time.sleep(30)
    r = requests.head("http://www.testing.co.uk")

else:
    print "Response is 200 - OK"

Upvotes: 4

Related Questions