Created
January 20, 2026 22:17
-
-
Save Harsha-PingProxies/6c810d9baf1b3b975e38a02b3b948724 to your computer and use it in GitHub Desktop.
Python Requests Timeout
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import requests | |
| from requests.adapters import HTTPAdapter | |
| from requests.exceptions import Timeout | |
| class TimeoutAdapter(HTTPAdapter): | |
| def __init__(self, timeout=5, *args, **kwargs): | |
| self.timeout = timeout | |
| super().__init__(*args, **kwargs) | |
| def send(self, request, **kwargs): | |
| if kwargs.get("timeout") is None: | |
| kwargs["timeout"] = self.timeout | |
| return super().send(request, **kwargs) | |
| def create_session(default_timeout=5): | |
| session = requests.Session() | |
| adapter = TimeoutAdapter(timeout=default_timeout) | |
| session.mount("http://", adapter) | |
| session.mount("https://", adapter) | |
| return session | |
| # Create session with a 3-second default timeout | |
| session = create_session(default_timeout=3) | |
| # Test 1: Fast request (should succeed) | |
| try: | |
| response = session.get("https://postman-echo.com/get") | |
| print(f"Test 1 - Fast request: {response.status_code}") | |
| except Timeout: | |
| print("Test 1 - Fast request: Timed out") | |
| # Test 2: Slow request with default timeout (should fail) | |
| try: | |
| response = session.get("https://postman-echo.com/delay/5") | |
| print(f"Test 2 - Slow request (default timeout): {response.status_code}") | |
| except Timeout: | |
| print("Test 2 - Slow request (default timeout): Timed out") | |
| # Test 3: Slow request with override timeout (should succeed) | |
| try: | |
| response = session.get( | |
| "https://postman-echo.com/delay/5", | |
| timeout=10 | |
| ) | |
| print(f"Test 3 - Slow request (override timeout): {response.status_code}") | |
| except Timeout: | |
| print("Test 3 - Slow request (override timeout): Timed out") |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment