1. import json
  2. import logging
  3. # Configure logging
  4. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  5. def load_user_data(filepath="user_data.json"):
  6. """Loads user data from a JSON file. Falls back to an empty dictionary if the file doesn't exist or is invalid."""
  7. try:
  8. with open(filepath, 'r') as f:
  9. user_data = json.load(f)
  10. logging.info(f"Loaded user data from {filepath}")
  11. return user_data
  12. except FileNotFoundError:
  13. logging.warning(f"User data file not found: {filepath}. Using empty data.")
  14. return {}
  15. except json.JSONDecodeError:
  16. logging.error(f"Error decoding JSON from {filepath}. Using empty data.")
  17. return {}
  18. except Exception as e:
  19. logging.exception(f"An unexpected error occurred while loading user data: {e}. Using empty data.")
  20. return {}
  21. def save_user_data(data, filepath="user_data.json"):
  22. """Saves user data to a JSON file."""
  23. try:
  24. with open(filepath, 'w') as f:
  25. json.dump(data, f, indent=4) # Use indent for readability
  26. logging.info(f"Saved user data to {filepath}")
  27. except Exception as e:
  28. logging.error(f"Error saving user data to {filepath}: {e}")
  29. def get_user(user_id, user_data):
  30. """Retrieves user data by ID. Returns None if not found."""
  31. if user_id in user_data:
  32. return user_data[user_id]
  33. else:
  34. logging.warning(f"User with ID {user_id} not found.")
  35. return None
  36. def set_user(user_id, user_data):
  37. """Sets user data for a given ID."""
  38. user_data[user_id] = user_data
  39. return user_data
  40. if __name__ == '__main__':
  41. # Example Usage
  42. user_data = load_user_data() # Load data from file
  43. if user_data:
  44. user_data = set_user("user123", {"name": "Alice", "email": "alice@example.com"})
  45. print(f"User data for user123: {user_data}")
  46. retrieved_user = get_user("user123", user_data)
  47. print(f"Retrieved user: {retrieved_user}")
  48. save_user_data(user_data) # Save updated data
  49. else:
  50. print("No user data available.")

Add your comment