import requests
def attach_header_metadata(url, headers=None, metadata=None, follow_redirects=True):
"""
Attaches metadata to headers as a workaround.
Args:
url (str): The URL to request.
headers (dict, optional): Existing headers to modify. Defaults to None.
metadata (dict, optional): Metadata to attach to headers. Defaults to None.
follow_redirects (bool, optional): Whether to follow redirects. Defaults to True.
Returns:
requests.Response: The response object.
"""
if headers is None:
headers = {}
if metadata is not None:
# Add metadata to headers. Using a custom header name.
headers['X-Custom-Metadata'] = str(metadata) # Convert metadata to string
try:
response = requests.get(url, headers=headers, follow_redirects=follow_redirects)
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response
except requests.exceptions.RequestException as e:
print(f"An error occurred: {e}")
return None
if __name__ == '__main__':
# Example Usage
url = "https://httpbin.org/headers" # A useful URL for testing headers
# Example 1: No custom metadata
response = attach_header_metadata(url)
if response:
print("Response (no metadata):")
print(response.json())
# Example 2: With custom metadata
metadata = {"key1": "value1", "key2": 123}
response = attach_header_metadata(url, metadata=metadata)
if response:
print("\nResponse (with metadata):")
print(response.json())
# Example 3: Modifying existing headers.
headers = {"User-Agent": "MyCustomAgent"}
response = attach_header_metadata(url, headers=headers, metadata=metadata)
if response:
print("\nResponse (with modified headers):")
print(response.json())
Add your comment