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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With