- Requests - Discussion
- Requests - Useful Resources
- Requests - Quick Guide
- Requests - Web Scraping using Requests
- Requests - Proxy
- Requests - Event Hooks
- Requests - Authentication
- Requests - SSL Certification
- Requests - Handling Sessions
- Requests - Handling History
- Requests - Handling Redirection
- Requests - Handling Timeouts
- Requests - Working with Errors
- Requests - Working with Cookies
- Requests - File Upload
- Handling POST, PUT, PATCH & DELETE Requests
- Requests - Handling GET Requests
- Requests - HTTP Requests Headers
- Handling Response for HTTP Requests
- Requests - Working with Requests
- Requests - How Http Requests Work?
- Requests - Environment Setup
- Requests - Overview
- Requests - Home
Selected Reading
- Who is Who
- Computer Glossary
- HR Interview Questions
- Effective Resume Writing
- Questions and Answers
- UPSC IAS Exams Notes
Requests - Handpng Timeouts
Timeouts can be easily added to the URL you are requesting. It so happens that, you are using a third-party URL and waiting for a response. It is always a good practice to give a timeout on the URL, as we might want the URL to respond within a timespan with a response or an error. Not doing so, can cause to wait on that request indefinitely.
We can give timeout to the URL by using the timeout param and value is passed in seconds as shown in the example below −
Example
import requests getdata = requests.get(,timeout=0.001) print(getdata.text)
Output
raise ConnectTimeout(e, request=request) requests.exceptions.ConnectTimeout: HTTPSConnectionPool(host= jsonplaceholder.typicode.com , port=443): Max retries exceeded with url: /users (Caused by Connect TimeoutError(<urlpb3.connection.VerifiedHTTPSConnection object at 0x000000B02AD E76A0>, Connection to jsonplaceholder.typicode.com timed out. (connect timeout = 0.001) ))
The timeout given is as follows −
getdata = requests.get(,timeout=0.001)
The execution throws connection timeout error as shown in the output. The timeout given is 0.001, which is not possible for the request to get back the response and throws an error. Now, we will increase the timeout and check.
Example
import requests getdata = requests.get(,timeout=1.000) print(getdata.text)
Output
E:prequests>python makeRequest.py [ { "id": 1, "name": "Leanne Graham", "username": "Bret", "email": "Sincere@april.biz", "address": { "street": "Kulas Light", "suite": "Apt. 556", "city": "Gwenborough", "zipcode": "92998-3874", "geo": { "lat": "-37.3159", "lng": "81.1496" } }, "phone": "1-770-736-8031 x56442", "website": "hildegard.org", "company": { "name": "Romaguera-Crona", "catchPhrase": "Multi-layered cpent-server neural-net", "bs": "harness real-time e-markets" } } ]
With a timeout of 1 second, we can get the response for the URL requested.
Advertisements