1. import json
  2. import time
  3. import datetime
  4. def export_user_data(user_data, filename="user_data.json", retry_interval=60):
  5. """
  6. Exports user data to a JSON file with retry mechanism.
  7. Args:
  8. user_data (list): A list of dictionaries, where each dictionary represents user data.
  9. filename (str): The name of the file to export to. Defaults to "user_data.json".
  10. retry_interval (int): Retry interval in seconds. Defaults to 60.
  11. """
  12. max_retries = 3 #Limit the number of retries
  13. for attempt in range(max_retries):
  14. try:
  15. with open(filename, 'w') as f:
  16. json.dump(user_data, f, indent=4) # Write the data to the file with indentation
  17. print(f"Successfully exported data to {filename}")
  18. return # Exit the function if successful
  19. except Exception as e:
  20. print(f"Export failed on attempt {attempt+1}: {e}")
  21. if attempt < max_retries - 1:
  22. print(f"Retrying in {retry_interval} seconds...")
  23. time.sleep(retry_interval)
  24. else:
  25. print("Export failed after multiple retries.")
  26. if __name__ == '__main__':
  27. # Example usage:
  28. sample_user_data = [
  29. {"user_id": 1, "name": "Alice", "email": "alice@example.com"},
  30. {"user_id": 2, "name": "Bob", "email": "bob@example.com"}
  31. ]
  32. export_user_data(sample_user_data, "my_user_data.json", 30)
  33. # Simulate data update and export again
  34. time.sleep(5)
  35. updated_user_data = sample_user_data + [{"user_id": 3, "name":"Charlie", "email":"charlie@example.com"}]
  36. export_user_data(updated_user_data, "updated_user_data.json", 60)

Add your comment