import time
import logging
# Configure logging
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
def validate_user_record(user_record):
"""
Validates a user record. Returns True if valid, False otherwise.
Raises an exception if validation fails.
"""
if not isinstance(user_record, dict):
raise ValueError("User record must be a dictionary.")
if not all(key in user_record for key in ("user_id", "email", "name")):
raise ValueError("User record missing required fields (user_id, email, name).")
if not isinstance(user_record["user_id"], (int, str)):
raise ValueError("user_id must be an integer or string.")
if not isinstance(user_record["email"], str):
raise ValueError("email must be a string.")
if not user_record["email"].contains("@"):
raise ValueError("Invalid email format.")
if not isinstance(user_record["name"], str):
raise ValueError("name must be a string.")
return True
def process_user_record(user_record, max_retries=3, retry_interval=5):
"""
Processes a user record with retry logic for validation errors.
"""
for attempt in range(max_retries):
try:
validate_user_record(user_record)
logging.info(f"User record validated successfully: {user_record}")
return True # Record is valid
except ValueError as e:
logging.warning(f"Validation failed (attempt {attempt + 1}/{max_retries}): {e}")
if attempt < max_retries - 1:
time.sleep(retry_interval) # Wait before retrying
else:
logging.error(f"Validation failed after {max_retries} attempts: {e}")
return False # Record is invalid after all retries
if __name__ == '__main__':
# Example Usage
user_record1 = {"user_id": 123, "email": "test@example.com", "name": "John Doe"}
user_record2 = {"user_id": "abc", "email": "invalid-email", "name": 123} # Invalid record
user_record3 = {"user_id": 456, "email": "valid@example.com", "name": "Jane Smith"}
print(f"Processing record 1: {process_user_record(user_record1)}")
print(f"Processing record 2: {process_user_record(user_record2)}")
print(f"Processing record 3: {process_user_record(user_record3)}")
Add your comment