import requests
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def safe_http_request(url, method='GET', data=None, headers=None, timeout=5):
"""
Performs an HTTP request with basic sanity checks.
Args:
url (str): The URL to request.
method (str): The HTTP method (GET, POST, etc.). Defaults to GET.
data (dict): The data to send in the request body (for POST, PUT, etc.). Defaults to None.
headers (dict): The headers to include in the request. Defaults to None.
timeout (int): Timeout in seconds. Defaults to 5.
Returns:
requests.Response: The response object if the request is successful.
None: If the request fails due to invalid URL, connection error, or other issues.
"""
try:
# Sanity check: Valid URL format
if not url.startswith(('http://', 'https://')):
raise ValueError("Invalid URL: URL must start with http:// or https://")
# Make the request
response = requests.request(method, url, data=data, headers=headers, timeout=timeout)
# Sanity check: Successful status code
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response
except requests.exceptions.RequestException as e:
logging.error(f"Request failed: {e}")
return None
except ValueError as e:
logging.error(f"Invalid URL: {e}")
return None
except Exception as e:
logging.error(f"An unexpected error occurred: {e}")
return None
if __name__ == '__main__':
# Example Usage
url = "https://www.example.com"
response = safe_http_request(url)
if response:
print(f"Request to {url} successful. Status code: {response.status_code}")
#print(response.text) # uncomment to print content
else:
print(f"Request to {url} failed.")
#Example with invalid URL
invalid_url = "example.com"
response = safe_http_request(invalid_url)
if response:
print(f"Request to {invalid_url} successful. Status code: {response.status_code}")
else:
print(f"Request to {invalid_url} failed.")
Add your comment