user3580316 user3580316 - 2 months ago 19
Python Question

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"

Answer

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"