Why do I receive a timeout error from Pythons requests module?

Question:

I use requests.post(url, headers, timeout=10) and sometimes I received a ReadTimeout exception HTTPSConnectionPool(host='domain.com', port=443): Read timed out. (read timeout=10)

Since I already set timeout as 10 seconds, why am I still receiving a ReadTimeout exception?

Asked By: chrizonline

||

Answers:

Per https://requests.readthedocs.io/en/latest/user/quickstart/#timeouts, that is the expected behavior. As royhowie mentioned, wrap it in a try/except block
(e.g.:

try:
  requests.post(url, headers, timeout=10)
except requests.exceptions.Timeout:
  print "Timeout occurred"

)

Answered By: Foon
try:
    #defined request goes here
except requests.exceptions.ReadTimeout:
    # Set up for a retry, or continue in a retry loop

You can wrap it like an exception block like this. Since you asked for this only ReadTimeout. Otherwise catch all of them;

try:
    #defined request goes here
except:
    # Set up for a retry, or continue in a retry loop
Answered By: GLHF

Another thing you can try is at the end of your code block, include the following:

time.sleep(2)

This worked for me. The delay is longer (in seconds) but might help overcome the issue you’re having.

Answered By: Attrey
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.