import time
import random
import requests
def retry_submission(url, data, max_retries=3, delay=1):
"""
Retries a form submission with graceful failure handling.
Args:
url (str): The URL to submit the form to.
data (dict): The data to submit in the form.
max_retries (int): The maximum number of retries.
delay (int): The delay between retries in seconds.
Returns:
requests.Response or None: The response object if successful, None otherwise.
"""
for attempt in range(max_retries):
try:
response = requests.post(url, data=data) # Attempt the submission
response.raise_for_status() # Raise HTTPError for bad responses (4xx or 5xx)
return response # Return the response on success
except requests.exceptions.RequestException as e:
print(f"Attempt {attempt + 1} failed: {e}")
if attempt < max_retries - 1:
print(f"Retrying in {delay} seconds...")
time.sleep(delay + random.uniform(0, delay/2)) # Add some jitter to delay
else:
print("Max retries reached. Submission failed.")
return None # Return None if all retries fail
if __name__ == '__main__':
# Example Usage
form_url = "https://httpbin.org/post" # Replace with your form URL
form_data = {"key1": "value1", "key2": "value2"}
response = retry_submission(form_url, form_data)
if response:
print("Submission successful!")
print(response.json())
else:
print("Submission failed after multiple retries.")
Add your comment