Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if a request is taking too long in requests?

If I make a blocking request using requests to a remote api it takes too long then my site will return an error too. I don't want that to happen.

This is the blocking code I have:

@app.route('/api')
def returnapi():
    r = requests.get("http://dndchecker.railsroot.com/api?mobile_number=9876543210")
    return r.text

I want to set the r value to False if the request object.

like image 901
Wally Avatar asked Oct 28 '25 16:10

Wally


1 Answers

So you could do this:

@app.route('/api')
def returnapi():
    try:
        r = requests.get("http://dndchecker.railsroot.com/api?mobile_number=9876543210", timeout=my_timeout)
    except (requests.exceptions.Timeout, requests.exceptions.ConnectionError) as err:
        return 'Server taking too long. Try again later'
    else:
        return r.text

That should help you prevent the server from taking too long. You of course have to define my_timeout to be the maximum you'd like to wait. I would caution you that you shouldn't set it too low though otherwise you'll always see the "Server taking too long. Try again later." The right amount of time is totally up to you as a service author and how long you feel is reasonable to wait.

like image 86
Ian Stapleton Cordasco Avatar answered Oct 31 '25 07:10

Ian Stapleton Cordasco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!