32

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?

1
  • Wrap it in a try/catch block?
    – royhowie
    Feb 7, 2015 at 1:16

3 Answers 3

59

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"

)

6
  • 1
    hi tk u for quick reply. this is a better answer because Catching this error will catch both ConnectTimeout and ReadTimeout errors. Feb 7, 2015 at 1:21
  • @nuttynibbles You said in your question how to catch ReadTimeout exception?. Otherwise just only use try/except and catch all of them.
    – GLHF
    Feb 7, 2015 at 1:22
  • sorry i am not sure why it is showing 0 vote here even though i upvote your ans Feb 7, 2015 at 1:22
  • hi @howaboutNO, initially i thought by putting the timeout argument, it will auto stop the requests process if it takes longer than that Feb 7, 2015 at 1:23
  • Using this answer, I wrote a function to deal with it: hastebin.com/izaponomer.py
    – xendi
    Sep 22, 2018 at 19:27
9
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
1
  • 2
    hi tk you for quick reply. i shall do that Feb 7, 2015 at 1:20
2

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.

1
  • 2
    It is not a good idea to use time.sleep() for something like this as suspends the thread that it is invoked from. Increasing the timeout is more viable in this case.
    – Eren Atas
    Sep 1, 2022 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.