import requests
import argparse
import json
def attach_metadata(url, headers=None, data=None, method='GET'):
"""
Attaches metadata to an HTTP request.
Args:
url (str): The URL to make the request to.
headers (dict, optional): HTTP headers to include. Defaults to None.
data (dict, optional): Data to send in the request body. Defaults to None.
method (str, optional): HTTP method (GET, POST, PUT, DELETE, etc.). Defaults to 'GET'.
Returns:
requests.Response: The response object from the request.
"""
# Default headers with metadata
default_headers = {
'X-Request-Source': 'local_utility',
'X-Request-Timestamp': requests.utils.get_timestamp(), # Timestamp
'X-Request-User-Agent': 'local_utility/1.0' # User agent
}
# Merge user-provided headers with default headers
if headers:
merged_headers = {**default_headers, **headers}
else:
merged_headers = default_headers
try:
if method.upper() == 'GET':
response = requests.get(url, headers=merged_headers, params=data)
elif method.upper() == 'POST':
response = requests.post(url, headers=merged_headers, json=data)
elif method.upper() == 'PUT':
response = requests.put(url, headers=merged_headers, json=data)
elif method.upper() == 'DELETE':
response = requests.delete(url, headers=merged_headers)
else:
raise ValueError(f"Unsupported HTTP method: {method}")
return response
except requests.exceptions.RequestException as e:
print(f"Request failed: {e}")
return None
if __name__ == '__main__':
parser = argparse.ArgumentParser(description='Attach metadata to HTTP requests.')
parser.add_argument('url', help='The URL to make the request to.')
parser.add_argument('--headers', help='Additional HTTP headers (JSON format).')
parser.add_argument('--data', help='Data to send in the request body (JSON format).')
parser.add_argument('--method', default='GET', choices=['GET', 'POST', 'PUT', 'DELETE'], help='HTTP method.')
args = parser.parse_args()
headers = None
if args.headers:
try:
headers = json.loads(args.headers)
except json.JSONDecodeError:
print("Invalid JSON format for headers.")
exit(1)
data = None
if args.data:
try:
data = json.loads(args.data)
except json.JSONDecodeError:
print("Invalid JSON format for data.")
exit(1)
response = attach_metadata(args.url, headers=headers, data=data, method=args.method)
if response:
print("Status Code:", response.status_code)
print("Response Headers:", response.headers)
try:
print("Response Body:", response.json()) #try to print as json
except json.JSONDecodeError:
print("Response Body:", response.text)
Add your comment