1. import requests
  2. import argparse
  3. import json
  4. def attach_metadata(url, headers=None, data=None, method='GET'):
  5. """
  6. Attaches metadata to an HTTP request.
  7. Args:
  8. url (str): The URL to make the request to.
  9. headers (dict, optional): HTTP headers to include. Defaults to None.
  10. data (dict, optional): Data to send in the request body. Defaults to None.
  11. method (str, optional): HTTP method (GET, POST, PUT, DELETE, etc.). Defaults to 'GET'.
  12. Returns:
  13. requests.Response: The response object from the request.
  14. """
  15. # Default headers with metadata
  16. default_headers = {
  17. 'X-Request-Source': 'local_utility',
  18. 'X-Request-Timestamp': requests.utils.get_timestamp(), # Timestamp
  19. 'X-Request-User-Agent': 'local_utility/1.0' # User agent
  20. }
  21. # Merge user-provided headers with default headers
  22. if headers:
  23. merged_headers = {**default_headers, **headers}
  24. else:
  25. merged_headers = default_headers
  26. try:
  27. if method.upper() == 'GET':
  28. response = requests.get(url, headers=merged_headers, params=data)
  29. elif method.upper() == 'POST':
  30. response = requests.post(url, headers=merged_headers, json=data)
  31. elif method.upper() == 'PUT':
  32. response = requests.put(url, headers=merged_headers, json=data)
  33. elif method.upper() == 'DELETE':
  34. response = requests.delete(url, headers=merged_headers)
  35. else:
  36. raise ValueError(f"Unsupported HTTP method: {method}")
  37. return response
  38. except requests.exceptions.RequestException as e:
  39. print(f"Request failed: {e}")
  40. return None
  41. if __name__ == '__main__':
  42. parser = argparse.ArgumentParser(description='Attach metadata to HTTP requests.')
  43. parser.add_argument('url', help='The URL to make the request to.')
  44. parser.add_argument('--headers', help='Additional HTTP headers (JSON format).')
  45. parser.add_argument('--data', help='Data to send in the request body (JSON format).')
  46. parser.add_argument('--method', default='GET', choices=['GET', 'POST', 'PUT', 'DELETE'], help='HTTP method.')
  47. args = parser.parse_args()
  48. headers = None
  49. if args.headers:
  50. try:
  51. headers = json.loads(args.headers)
  52. except json.JSONDecodeError:
  53. print("Invalid JSON format for headers.")
  54. exit(1)
  55. data = None
  56. if args.data:
  57. try:
  58. data = json.loads(args.data)
  59. except json.JSONDecodeError:
  60. print("Invalid JSON format for data.")
  61. exit(1)
  62. response = attach_metadata(args.url, headers=headers, data=data, method=args.method)
  63. if response:
  64. print("Status Code:", response.status_code)
  65. print("Response Headers:", response.headers)
  66. try:
  67. print("Response Body:", response.json()) #try to print as json
  68. except json.JSONDecodeError:
  69. print("Response Body:", response.text)

Add your comment