Search code examples
pythonexceptionpython-requeststimeoutconnection-timeout

define timeout in web request with python


This is my scenario. I am making requests to a web page that takes too long in some occasions. I would like that when it takes more than 10 seconds without issuing a response from the server, the request is canceled but without receiving any error. This is my current code and the error that appears to me. when this error appears, my code ends. In summary I want to make a web request and limit that if there is no answer in 10 seconds, I finish the request and continue with my code.

requests.post("www.webpage.com", headers = {'Content-type': 'application/x-www-form-urlencoded'}, data = {"conid":1,"event":5},timeout=10)
.
.
.

when 10 seconds pass I get this error

ReadTimeout: HTTPConnectionPool(host='www.webpage.com', port=80): Read timed out. (read timeout=10)

I do not put the real url for confidentiality reasons, but normally without setting a timeout, it works


Solution

  • Use an exception to handle the timeout

    try:
        requests.post("www.webpage.com", headers = {'Content-type': 'application/x-www-form-urlencoded'}, data = {"conid":1,"event":5},timeout=10)
    
    except requests.exceptions.ReadTimeout:
        print("Server didn't respond within 10 seconds")