|
| 1 | +import requests |
| 2 | + |
| 3 | + |
| 4 | +def get_request_handler(url: str, headers: dict): |
| 5 | + try: |
| 6 | + # Send a GET request to the specified URL |
| 7 | + response = requests.get(url, headers=headers) |
| 8 | + |
| 9 | + # Check if the request was successful |
| 10 | + if response.status_code == 200: |
| 11 | + print("Request successful!") |
| 12 | + return ( |
| 13 | + response.json() |
| 14 | + ) # or response.text, based on the API's response format |
| 15 | + elif response.status_code == 401: |
| 16 | + print("Authorization failed: Token may need to be refreshed or changed.") |
| 17 | + raise PermissionError("Token authorization failed (401 Unauthorized).") |
| 18 | + else: |
| 19 | + print(f"Request failed with status code: {response.status_code}") |
| 20 | + response.raise_for_status() # Raise an exception for error status codes |
| 21 | + |
| 22 | + except requests.exceptions.HTTPError as http_err: |
| 23 | + print(f"HTTP error occurred: {http_err}") |
| 24 | + raise requests.exceptions.HTTPError("An HTTP error occurred.") from http_err |
| 25 | + except requests.exceptions.ConnectionError as conn_err: |
| 26 | + print("Connection error occurred. Please check the URL or network connection.") |
| 27 | + raise ConnectionError("Failed to connect to the server.") from conn_err |
| 28 | + except requests.exceptions.Timeout as timeout_err: |
| 29 | + print("Request timed out. Try again later.") |
| 30 | + raise TimeoutError("The request timed out.") from timeout_err |
| 31 | + except requests.exceptions.RequestException as req_err: |
| 32 | + print(f"An error occurred: {req_err}") |
| 33 | + raise RuntimeError("An unspecified request error occurred.") from req_err |
0 commit comments