1. import json
  2. import logging
  3. import os
  4. # Configure logging
  5. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  6. def sanitize_data(data, allowed_fields):
  7. """
  8. Sanitizes user data by limiting output to allowed fields.
  9. Handles potential errors gracefully.
  10. """
  11. try:
  12. sanitized_data = {}
  13. for field in allowed_fields:
  14. if field in data:
  15. sanitized_data[field] = data[field]
  16. return sanitized_data
  17. except Exception as e:
  18. logging.error(f"Error sanitizing data: {e}")
  19. return {} # Return empty dict on error
  20. def process_user_data(user_id):
  21. """
  22. Processes user data, sanitizes it, and outputs it.
  23. Handles file access errors.
  24. """
  25. try:
  26. # Simulate reading user data from a file (replace with actual data source)
  27. filepath = f"user_data_{user_id}.json"
  28. if not os.path.exists(filepath):
  29. logging.warning(f"User data file not found: {filepath}")
  30. return
  31. with open(filepath, 'r') as f:
  32. user_data = json.load(f)
  33. # Define allowed fields
  34. allowed_fields = ["user_id", "username", "email"]
  35. sanitized_data = sanitize_data(user_data, allowed_fields)
  36. # Output sanitized data (handle potential errors)
  37. if sanitized_data:
  38. print(json.dumps(sanitized_data)) # Output as JSON for consistency
  39. else:
  40. logging.warning(f"No valid data to output for user {user_id}")
  41. except json.JSONDecodeError as e:
  42. logging.error(f"Error decoding JSON from file {filepath}: {e}")
  43. except FileNotFoundError as e:
  44. logging.error(f"File not found: {e}")
  45. except Exception as e:
  46. logging.error(f"An unexpected error occurred: {e}")
  47. if __name__ == "__main__":
  48. # Example usage with different user IDs
  49. process_user_data("123")
  50. process_user_data("456")
  51. process_user_data("789")
  52. process_user_data("nonexistent") # Test missing file

Add your comment