1. import time
  2. import logging
  3. # Configure logging
  4. logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
  5. def validate_user_record(user_record):
  6. """
  7. Validates a user record. Returns True if valid, False otherwise.
  8. Raises an exception if validation fails.
  9. """
  10. if not isinstance(user_record, dict):
  11. raise ValueError("User record must be a dictionary.")
  12. if not all(key in user_record for key in ("user_id", "email", "name")):
  13. raise ValueError("User record missing required fields (user_id, email, name).")
  14. if not isinstance(user_record["user_id"], (int, str)):
  15. raise ValueError("user_id must be an integer or string.")
  16. if not isinstance(user_record["email"], str):
  17. raise ValueError("email must be a string.")
  18. if not user_record["email"].contains("@"):
  19. raise ValueError("Invalid email format.")
  20. if not isinstance(user_record["name"], str):
  21. raise ValueError("name must be a string.")
  22. return True
  23. def process_user_record(user_record, max_retries=3, retry_interval=5):
  24. """
  25. Processes a user record with retry logic for validation errors.
  26. """
  27. for attempt in range(max_retries):
  28. try:
  29. validate_user_record(user_record)
  30. logging.info(f"User record validated successfully: {user_record}")
  31. return True # Record is valid
  32. except ValueError as e:
  33. logging.warning(f"Validation failed (attempt {attempt + 1}/{max_retries}): {e}")
  34. if attempt < max_retries - 1:
  35. time.sleep(retry_interval) # Wait before retrying
  36. else:
  37. logging.error(f"Validation failed after {max_retries} attempts: {e}")
  38. return False # Record is invalid after all retries
  39. if __name__ == '__main__':
  40. # Example Usage
  41. user_record1 = {"user_id": 123, "email": "test@example.com", "name": "John Doe"}
  42. user_record2 = {"user_id": "abc", "email": "invalid-email", "name": 123} # Invalid record
  43. user_record3 = {"user_id": 456, "email": "valid@example.com", "name": "Jane Smith"}
  44. print(f"Processing record 1: {process_user_record(user_record1)}")
  45. print(f"Processing record 2: {process_user_record(user_record2)}")
  46. print(f"Processing record 3: {process_user_record(user_record3)}")

Add your comment