How to Handle Timeout in Python Requests: Simple Fix
To handle timeout in
python requests, use the timeout parameter in your request call to limit waiting time. Wrap the request in a try-except block to catch requests.exceptions.Timeout and handle it gracefully.Why This Happens
When you make a web request using requests.get() without a timeout, the program waits indefinitely if the server is slow or unresponsive. This can freeze your program or cause it to hang.
python
import requests response = requests.get('https://httpbin.org/delay/10') print(response.status_code)
Output
The program hangs and does not return for a long time (about 10 seconds delay). No error is raised.
The Fix
Add the timeout parameter to your request to limit how long it waits. Use try-except to catch the timeout error and handle it, like retrying or showing a message.
python
import requests try: response = requests.get('https://httpbin.org/delay/10', timeout=3) print(response.status_code) except requests.exceptions.Timeout: print('The request timed out. Please try again later.')
Output
The request timed out. Please try again later.
Prevention
Always set a reasonable timeout value for your requests to avoid hanging programs. Use exception handling to manage timeouts gracefully. This keeps your app responsive and user-friendly.
- Use small timeout values for quick feedback.
- Catch
requests.exceptions.Timeoutto handle delays. - Consider retrying requests with backoff if needed.
Related Errors
Other common errors when making requests include:
- ConnectionError: Happens if the server is unreachable.
- HTTPError: Raised for bad HTTP responses like 404 or 500.
- TooManyRedirects: Occurs if the request exceeds redirect limits.
Handle these with try-except blocks similar to timeout handling.
Key Takeaways
Always use the timeout parameter in requests to avoid waiting forever.
Wrap requests in try-except blocks to catch and handle timeout exceptions.
Choose timeout values based on your app's responsiveness needs.
Handle other request exceptions like ConnectionError and HTTPError similarly.
Consider retry logic with delays for better user experience on timeouts.