w3resource

Python: Raise Timeout exception in the event of times out of request


6. Async Request Timeout

Write a Python program to send a request to a web page and stop waiting for a response after a given number of seconds. If a request times out, raise a Timeout exception.

Sample Solution:

Python Code:

import requests
print("timeout = 0.001")
try:
    r = requests.get('https://github.com/', timeout = 0.001)
    print(r.text)
except requests.exceptions.RequestException as e:
    print(e)    

print("\ntimeout = 1.0")    
try:
    r = requests.get('https://github.com/', timeout = 1.0)
    print("Connected....!")
except requests.exceptions.RequestException as e:
    print(e)

Sample Output:

timeout = 0.001
HTTPSConnectionPool(host='github.com', port=443): Max retries exceeded with url: / (Caused by ConnectTimeoutError(<urllib3.connection.VerifiedHTTPSConnection object at 0x0BD7B0D0>, 'Connection to github.com timed out. (connect timeout=0.001)'))

timeout = 1.0
Connected....!

For more Practice: Solve these Related Problems:

  • Write a Python program that sends a request to a URL with a specified timeout using requests.get(timeout=...), and prints a message if the request times out.
  • Write a Python function that attempts to fetch data from a slow server, catches the Timeout exception, and then logs an error message.
  • Write a Python script to simulate a timeout scenario by sending a request with a very short timeout period, then printing the exception details if a timeout occurs.
  • Write a Python program to prompt the user for a timeout duration, send a request with that timeout, and handle both successful and timeout responses appropriately.

Python Code Editor:


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python code to send a request to a web page, and print the JSON value of the response. Also print each key value of the response.
Next: Write a Python code to send some sort of data in the URL’s query string.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.