user3580316
user3580316

Reputation:

Python Request response time timeouts

I am trying to perform some benchmarking and having some issues with Request. The problem is that if the response time is high it throws some errors. How can I make it return the else if the request.get waits more than for instance 2 seconds.

time = requests.get('http://www.google.com').elapsed.total_seconds()

if time < 1:
    print "Low response time"
else:
    print "High reponse time"

Upvotes: 0

Views: 4041

Answers (2)

Dave
Dave

Reputation: 6554

I don't know what errors are called (do you mean exceptions here?). If it throws exceptions, then you could put it in a try / except:

try:
    time = requests.get('http://www.google.com').elapsed.total_seconds()
    if time < 1:
        print "Low response time"
    else:
        print "High response time"
except:
    # threw an exception
    print "High response time"

If you know the type of exception thrown, then I would set except to catch that exception and no others.

Upvotes: 0

Muhammad Tahir
Muhammad Tahir

Reputation: 5184

Use timeout parameter of requests.get. requests.get will raise requests.exceptions.Timeout exception if request took more time than timeout value.

try:
    resp = requests.get('http://www.google.com', timeout=1.0)
except requests.exceptions.Timeout as e:
    print "High reponse time"
else:
    print "Low response time"

Upvotes: 1

Related Questions