1. import requests
  2. import time
  3. import random
  4. def retry_header_operation(url, headers, max_retries=3, delay=1):
  5. """
  6. Retries an operation to set response headers with rate limiting.
  7. Args:
  8. url (str): The URL to make the request to.
  9. headers (dict): The headers to set in the response.
  10. max_retries (int): The maximum number of retries.
  11. delay (int): The delay in seconds between retries.
  12. Returns:
  13. bool: True if the operation was successful, False otherwise.
  14. """
  15. for attempt in range(max_retries):
  16. try:
  17. response = requests.get(url, headers=headers) # Make the request
  18. response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
  19. return True # Success!
  20. except requests.exceptions.RequestException as e:
  21. if attempt < max_retries - 1:
  22. wait_time = delay + random.uniform(0, delay) # Add some randomness to delay
  23. print(f"Attempt {attempt + 1} failed: {e}. Retrying in {wait_time:.2f} seconds...")
  24. time.sleep(wait_time)
  25. else:
  26. print(f"Max retries reached. Operation failed: {e}")
  27. return False
  28. if __name__ == '__main__':
  29. # Example Usage
  30. url = "https://httpbin.org/headers" # Example URL
  31. headers = {'X-Custom-Header': 'MyValue'}
  32. if retry_header_operation(url, headers):
  33. print("Successfully set response headers.")
  34. else:
  35. print("Failed to set response headers after multiple retries.")

Add your comment