Python: Raise Timeout exception in the event of times out of request
Python Requests: Exercise-6 with Solution
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....!
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.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://w3resource.com/python-exercises/requests/python-request-exercise-6.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics