How to Validate and Cache Data with Redis in Python
A beginner-friendly helper that validates email, phone, and age data and caches validated entries in Redis for 5 minutes.
pip install redis
Python code
44 linesimport redis
import json
from functools import wraps
class DataValidator:
def __init__(self, host="localhost", port=6379, db=0):
self.cache = redis.Redis(host=host, port=port, db=db)
self.validators = {
"email": lambda v: "@" in v and "." in v.split("@")[-1],
"phone": lambda v: len(v) == 10 and v.isdigit(),
"age": lambda v: isinstance(v, int) and 0 < v < 120,
}
def validate_and_cache(self, key, data, data_type):
validator = self.validators.get(data_type)
if not validator:
raise ValueError(f"Unknown type: {data_type}")
if not validator(data):
raise ValueError(f"Invalid {data_type}: {data}")
cache_key = f"{data_type}:{key}"
if self.cache.exists(cache_key):
return json.loads(self.cache.get(cache_key).decode())
self.cache.set(cache_key, json.dumps(data), ex=300)
return data
if __name__ == "__main__":
validator = DataValidator()
# Validate and cache an email
email_result = validator.validate_and_cache("user1", "john@example.com", "email")
print(f"Email cached: {email_result}")
# Retrieve from cache (no validation needed again)
cached_result = validator.validate_and_cache("user1", "john@example.com", "email")
print(f"Email from cache: {cached_result}")
# This will raise an error
try:
validator.validate_and_cache("user2", "not-an-email", "email")
except ValueError as e:
print(f"Error: {e}")
Output
Email cached: john@example.com
Email from cache: john@example.com
Error: Invalid email: not-an-email
How it works
This class wraps Redis operations behind a simple validation API. Each data type has a lambda validator that checks the format. validate_and_cache first checks if a cached value exists under a type-prefixed key; if so, it returns the JSON-decoded value without re-validating. Otherwise it validates the data, stores it as JSON with a 300-second TTL, and returns it. The wraps import isn't used directly here, but it hints at extending with caching decorators in variations.
Common mistakes
- Forgetting to decode the bytes returned by redis.get before json.loads.
- Not checking if the data type is supported before validation, leading to AttributeError.
- Overwriting valid data with invalid data because validation order is reversed.
- Ignoring that Redis stores only bytes; JSON serialization is required for complex types.
Variations
- Wrap the validate function with a `@cache` decorator using functools.lru_cache for in-memory caching.
- Use redis-py's `get` and `set` with `ex` parameter directly in a decorator pattern.
Real-world use cases
- Caching user profile validation results in a web API to avoid re-checking on every request.
- Storing session metadata after server-side validation to reduce database load.
- Pre-validating and caching product form inputs during checkout to speed up repeated submissions.
Sponsored
More from Caching & Redis
- Cache Asides in Python with a Read-Through Loader easy
- Cache Data in Redis with Python easy
- Cache Penetration Null Object Mock in Python medium
- Cache Stampede Prevention with SingleFlight in Python medium
- Cache Warming with Python: Preload Hot Keys easy
- Coalescing duplicate in-flight requests: one shared result for concurrent callers hard
Keep learning
Related tutorials and quizzes for this topic.