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

Creates a dictionary with the same keys as the provided dictionary and values generated by running the provided function for each value:

Example:

def tips_map_values(obj, fn):
  ret = {}
  for key in obj.keys():
    ret[key] = fn(obj[key])
  return ret
users = {
  'Owen': { 'user': 'Owen', 'age': 29 },
  'Eddie': { 'user': 'Eddie', 'age': 15 }
}

print(tips_map_values(users, lambda u : u['age'])) # {'Owen': 29, 'Eddie': 15}

Output:

{'Owen': 29, 'Eddie': 15}