1. import json
  2. import os
  3. import logging
  4. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  5. def restore_data(filepath, backup_dir):
  6. """
  7. Restores data from a backup file.
  8. Args:
  9. filepath (str): The path to the backup file.
  10. backup_dir (str): The directory where the backup files are stored.
  11. Returns:
  12. bool: True if the restoration was successful, False otherwise.
  13. """
  14. try:
  15. if not os.path.exists(filepath):
  16. logging.warning(f"Backup file not found: {filepath}")
  17. return False
  18. if not os.path.exists(backup_dir):
  19. logging.error(f"Backup directory not found: {backup_dir}")
  20. return False
  21. with open(filepath, 'r') as f:
  22. try:
  23. data = json.load(f)
  24. except json.JSONDecodeError as e:
  25. logging.error(f"Error decoding JSON from {filepath}: {e}")
  26. return False
  27. # Simulate data restoration (replace with actual restoration logic)
  28. try:
  29. # Example: Assuming data is a dictionary to be loaded into a variable
  30. # data_loaded = load_data(data) # Replace load_data with your actual loading logic
  31. #For this example, just print the restored data
  32. print("Restored Data:")
  33. print(data)
  34. return True
  35. except Exception as e:
  36. logging.error(f"Error restoring data: {e}")
  37. return False
  38. except Exception as e:
  39. logging.error(f"An unexpected error occurred: {e}")
  40. return False
  41. if __name__ == '__main__':
  42. #Example Usage
  43. backup_file = "data_backup.json"
  44. backup_directory = "backups"
  45. #Create dummy data and backup file for testing
  46. if not os.path.exists(backup_directory):
  47. os.makedirs(backup_directory)
  48. dummy_data = {"name": "John Doe", "age": 30, "city": "New York"}
  49. with open(backup_file, 'w') as f:
  50. json.dump(dummy_data, f, indent=4)
  51. success = restore_data(backup_file, backup_directory)
  52. if success:
  53. print("Data restoration successful.")
  54. else:
  55. print("Data restoration failed.")

Add your comment