w3resource

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

Python Requests: Exercise-6 with Solution

Write a Python code to send a request to a web page and stop waiting for a response after a given number of seconds. In the event of times out of request, raise 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 Python skills with w3resource's quiz



Python: Tips of the Day

Merging two dicts in Python 3.5+ with a single expression

Example:

# How to merge two dictionaries
# in Python 3.5+

x = {'p': 1, 'q': 3}
y = {'q': 5, 'r': 8}

z = {**x, **y}

z
{'r': 4, 'p': 1, 'q': 3}

z = dict(x, **y)
print(z)

Output:

{'p': 1, 'q': 5, 'r': 8}