1. import hashlib
  2. import time
  3. def hash_response_headers(response):
  4. """Hashes response headers for retry logic."""
  5. header_string = ""
  6. for key, value in response.headers.items():
  7. header_string += f"{key}:{value}" # Concatenate key:value pairs
  8. hash_object = hashlib.sha256(header_string.encode('utf-8')) # Use SHA256 for hashing
  9. return hash_object.hexdigest() # Return hexadecimal representation
  10. def retry_with_fixed_interval(response, max_retries=3, initial_delay=1):
  11. """Retries request with fixed intervals based on header hash."""
  12. retries = 0
  13. while retries < max_retries:
  14. try:
  15. # Process the response (e.g., check status code, content)
  16. # Replace this with your actual response processing logic
  17. print(f"Response received (attempt {retries + 1})")
  18. return # Success!
  19. except Exception as e:
  20. print(f"Attempt {retries + 1} failed: {e}")
  21. retries += 1
  22. if retries < max_retries:
  23. delay = initial_delay * (2 ** retries) # Exponential backoff
  24. print(f"Retrying in {delay} seconds...")
  25. time.sleep(delay)
  26. print("Max retries reached. Request failed.")
  27. if __name__ == '__main__':
  28. # Example Usage (replace with your actual response object)
  29. class MockResponse:
  30. def __init__(self, headers, status_code, content=""):
  31. self.headers = headers
  32. self.status_code = status_code
  33. self.content = content
  34. #Simulate a response
  35. headers = {"Content-Type": "application/json", "X-Custom-Header": "value1"}
  36. response = MockResponse(headers, 200)
  37. header_hash = hash_response_headers(response)
  38. print(f"Header Hash: {header_hash}")
  39. retry_with_fixed_interval(response, max_retries=2, initial_delay=1)

Add your comment