import requests
import time
import random
def retry_header_operation(url, headers, max_retries=3, delay=1):
"""
Retries an operation to set response headers with rate limiting.
Args:
url (str): The URL to make the request to.
headers (dict): The headers to set in the response.
max_retries (int): The maximum number of retries.
delay (int): The delay in seconds between retries.
Returns:
bool: True if the operation was successful, False otherwise.
"""
for attempt in range(max_retries):
try:
response = requests.get(url, headers=headers) # Make the request
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return True # Success!
except requests.exceptions.RequestException as e:
if attempt < max_retries - 1:
wait_time = delay + random.uniform(0, delay) # Add some randomness to delay
print(f"Attempt {attempt + 1} failed: {e}. Retrying in {wait_time:.2f} seconds...")
time.sleep(wait_time)
else:
print(f"Max retries reached. Operation failed: {e}")
return False
if __name__ == '__main__':
# Example Usage
url = "https://httpbin.org/headers" # Example URL
headers = {'X-Custom-Header': 'MyValue'}
if retry_header_operation(url, headers):
print("Successfully set response headers.")
else:
print("Failed to set response headers after multiple retries.")
Add your comment