1. import requests
  2. def attach_header_metadata(url, headers=None, metadata=None, follow_redirects=True):
  3. """
  4. Attaches metadata to headers as a workaround.
  5. Args:
  6. url (str): The URL to request.
  7. headers (dict, optional): Existing headers to modify. Defaults to None.
  8. metadata (dict, optional): Metadata to attach to headers. Defaults to None.
  9. follow_redirects (bool, optional): Whether to follow redirects. Defaults to True.
  10. Returns:
  11. requests.Response: The response object.
  12. """
  13. if headers is None:
  14. headers = {}
  15. if metadata is not None:
  16. # Add metadata to headers. Using a custom header name.
  17. headers['X-Custom-Metadata'] = str(metadata) # Convert metadata to string
  18. try:
  19. response = requests.get(url, headers=headers, follow_redirects=follow_redirects)
  20. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  21. return response
  22. except requests.exceptions.RequestException as e:
  23. print(f"An error occurred: {e}")
  24. return None
  25. if __name__ == '__main__':
  26. # Example Usage
  27. url = "https://httpbin.org/headers" # A useful URL for testing headers
  28. # Example 1: No custom metadata
  29. response = attach_header_metadata(url)
  30. if response:
  31. print("Response (no metadata):")
  32. print(response.json())
  33. # Example 2: With custom metadata
  34. metadata = {"key1": "value1", "key2": 123}
  35. response = attach_header_metadata(url, metadata=metadata)
  36. if response:
  37. print("\nResponse (with metadata):")
  38. print(response.json())
  39. # Example 3: Modifying existing headers.
  40. headers = {"User-Agent": "MyCustomAgent"}
  41. response = attach_header_metadata(url, headers=headers, metadata=metadata)
  42. if response:
  43. print("\nResponse (with modified headers):")
  44. print(response.json())

Add your comment