0

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"
Delimitry
  • 2,987
  • 4
  • 30
  • 39

2 Answers2

1

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"
Muhammad Tahir
  • 5,006
  • 1
  • 19
  • 36
  • That works, but you have to change between high and low. –  Mar 10 '16 at 13:58
  • If exception is generated then it means response time was high (more than 1.0), so I think it is right? `else` part will be executed if request completed with in timeout time hence Low response time. – Muhammad Tahir Mar 10 '16 at 14:02
  • Becuase it is throwing "high respone time" when it takes less than 1 seconds and low response time when it takes more than 1 seconds. –  Mar 10 '16 at 14:06
  • @user3580316 are you sure you are using exact same code? For me here is the result of printing time taken by request and print output. `0.227112, Low response time` – Muhammad Tahir Mar 10 '16 at 14:24
  • You can test by replacing `resp = requests.get('http://www.google.com', timeout=1.0)` with `print requests.get('http://www.google.com', timeout=1.0).elapsed.total_seconds()` – Muhammad Tahir Mar 10 '16 at 14:25
0

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.

Delimitry
  • 2,987
  • 4
  • 30
  • 39
Dave
  • 6,184
  • 8
  • 26
  • 28
  • How can I make it go the `except` if the reponse takes longer than 2 seconds? Since I dont want to wait the uneccary 20 seconds (if the reponse time is 20 seconds). If it takes more than 2 seconds, I want it to stop immeditly and go the `except` –  Mar 10 '16 at 13:43