Version 1.0.0
Simple, focused example of performing CRUD (create, read, update, delete) operations against Redis using JSON payloads in Python. It provides:
redis_tester.py: Class wrapper (AitRedisTester) around redis-py for connection + JSON key-value operations.statistics.py: Statistics tracker for monitoring Redis operations.main.py: Demo script exercising a full lifecycle on anAPP_CONFIGkey with statistics tracking..env.example: Sample environment configuration (copy to.env).requirements.txt: Dependencies (redis,python-dotenv).
Great for ultra-fast lookups of configuration and session-like objects by key. For relational queries or complex joins, pair Redis with a SQL database (PostgreSQL, etc.). Common pattern: SQL = source of truth, Redis = cache.
| File | Purpose |
|---|---|
redis_tester.py |
Defines AitRedisTester class with connect/insert/update/search/delete methods using JSON serialization. |
statistics.py |
Tracks operation counts (insert/update/search/delete) and provides runtime statistics. |
main.py |
Demonstrates connecting, inserting, verifying, updating, deleting and re-inserting APP_CONFIG with stats tracking. |
.env.example |
Template for Redis connection variables. |
requirements.txt |
Dependency pins. |
- Python 3.9+
- Accessible Redis server (local Docker, managed service, etc.)
python -m venv .venv
./.venv/Scripts/Activate.ps1
pip install -r requirements.txtOr quick install without a venv:
pip install redis python-dotenvCopy .env.example to .env and edit:
REDIS_HOST=127.0.0.1
REDIS_PORT=6379
REDIS_PASSWORD=
Then load automatically via load_dotenv() (already in the class) or export manually in your shell.
from redis_tester import AitRedisTester
tester = AitRedisTester()
if tester.connect():
tester.insert("MY_KEY", {"hello": "world"})
data = tester.search("MY_KEY")
tester.update("MY_KEY", {"hello": "redis"}) # same as insert
tester.delete("MY_KEY")Implementation details:
- Uses
redis.Redis(..., decode_responses=True)so string values are auto-decoded. - Dicts are stored as JSON strings via
json.dumpsand reconstructed withjson.loads. update()is an alias forinsert()(Redis SET is upsert).
python main.pyThe script will:
- Connect
- Insert
APP_CONFIG - Search & pretty-print JSON
- Verify a field
- Update a color
- Re-query
- Delete and confirm absence
- Re-insert and confirm again
- Display statistics summary
| Method | Parameters | Returns | Notes |
|---|---|---|---|
connect() |
none | bool | Connects (or verifies injected client) and pings Redis |
insert(key, dict) |
key:str, value:dict | bool | Upsert JSON |
update(key, dict) |
key:str, value:dict | bool | Alias of insert |
search(key) |
key:str | dict or None | Returns deserialized JSON |
delete(key) |
key:str | bool | True if key removed |
import redis, json
r = redis.Redis(host="localhost", port=6379, decode_responses=True)
r.set("TEST_KEY", json.dumps({"hello": "world"}))
print(json.loads(r.get("TEST_KEY")))AitRedisTester accepts an optional redis_client so you can inject a test double (e.g., fakeredis.FakeRedis).
import fakeredis
from redis_tester import AitRedisTester
fake = fakeredis.FakeRedis(decode_responses=True)
tester = AitRedisTester(redis_client=fake)
assert tester.connect() is TrueThe class uses the logging module instead of print. Configure logging in your app (see main.py).
The RedisStatistics class tracks operation counts and runtime metrics.
Usage:
from statistics import RedisStatistics
stats = RedisStatistics()
# Record operations as they happen
stats.record_operation("insert")
stats.record_operation("search")
stats.record_operation("update")
stats.record_operation("delete")
# Get current statistics
current_stats = stats.get_statistics()
print(current_stats) # {'insert': 1, 'update': 1, 'search': 1, 'delete': 1}
# Get total operation count
total = stats.get_total_operations()
print(total) # 4
# Print formatted summary
stats.print_summary()Example output:
2026-01-01 12:00:00,123 INFO statistics: === Redis Operations Summary ===
2026-01-01 12:00:00,123 INFO statistics: Runtime: 2.45 seconds
2026-01-01 12:00:00,123 INFO statistics: Total operations: 7
2026-01-01 12:00:00,123 INFO statistics: insert: 2
2026-01-01 12:00:00,123 INFO statistics: update: 1
2026-01-01 12:00:00,123 INFO statistics: search: 3
2026-01-01 12:00:00,123 INFO statistics: delete: 1
2026-01-01 12:00:00,123 INFO statistics: ==============================
API:
| Method | Returns | Description |
|---|---|---|
record_operation(type) |
None | Record an operation (insert/update/search/delete) |
get_statistics() |
dict | Get current operation counts |
get_total_operations() |
int | Get total number of operations |
print_summary() |
None | Print formatted summary to logs |
You can run unit tests locally without a real Redis server. Tests use fakeredis.
# 1) (Optional) activate your virtual environment
./.venv/Scripts/Activate.ps1
# 2) Install dev-only dependencies
pip install -r requirements-dev.txt
# 3) Run the tests
pytest -qNotes:
- Tests inject an in-memory
fakeredis.FakeRedisviaAitRedisTester(redis_client=...). - No network or external services are required.
| Symptom | Check | Fix |
|---|---|---|
| ConnectionError | Host/port/password | Correct .env, ensure server running |
| Empty search | Key spelled? TTL expired? | Re-insert or remove TTL elsewhere |
| Non-UTF8 bytes | Missing decode_responses=True |
Use provided class setup |
| Wrong host in logs | .env not loaded |
Ensure file named .env & in root |
Windows (via Redis for Windows):
# Download from: https://github.com/tporadowski/redis/releases
# Or use Chocolatey:
choco install redis-64
# Or use Windows Subsystem for Linux (WSL)macOS:
brew install redisLinux (Ubuntu/Debian):
sudo apt update
sudo apt install redis-toolsDocker (no installation needed):
docker run -it --rm redis redis-cli -h host.docker.internal -p 6379Connect to Redis:
# Local connection
redis-cli
# Remote connection
redis-cli -h 127.0.0.1 -p 6379
# With password
redis-cli -h 127.0.0.1 -p 6379 -a yourpasswordCommon Operations:
# Test connection
PING
# Set a key-value pair
SET mykey "Hello World"
# Get a value
GET mykey
# Set JSON (as string)
SET APP_CONFIG '{"app_name":"AIT-WEB","tenant":"AIT"}'
# Get JSON
GET APP_CONFIG
# Check if key exists
EXISTS mykey
# Delete a key
DEL mykey
# List all keys (careful in production!)
KEYS *
# Get key pattern
KEYS APP_*
# View key type
TYPE mykey
# Set expiration (in seconds)
EXPIRE mykey 3600
# Check time to live
TTL mykey
# View all databases
INFO keyspace
# Switch database (0-15)
SELECT 1
# Clear current database
FLUSHDB
# Clear all databases (DANGEROUS!)
FLUSHALL# Monitor all commands in real-time
MONITOR
# View server info
INFO
# View connected clients
CLIENT LIST
# View memory usage
MEMORY STATS
# View specific key memory
MEMORY USAGE mykeyRedis Insight is a free visual tool for managing Redis databases.
Download:
- Visit: https://redis.io/insight/
- Available for Windows, macOS, and Linux
- Web-based interface included
Features:
- Visual key browser with search and filtering
- Real-time performance monitoring
- Query builder and CLI integration
- Slow log analysis
- Memory analysis and optimization
- Support for Redis modules (JSON, Search, etc.)
Installation (Windows):
# Download installer from https://redis.io/insight/
# Or use Chocolatey:
choco install redis-insightQuick Start:
- Launch Redis Insight
- Click "Add Redis Database"
- Enter host (127.0.0.1), port (6379), and optional password
- Browse keys, run commands, and monitor performance
Useful for:
- Exploring data visually
- Debugging connection issues
- Performance profiling
- Learning Redis commands interactively
- Do NOT store real API tokens/secrets inside committed code.
- Use environment variables / secret manager.
- Treat
APP_CONFIG_DATAsample as placeholder only.
- Redis: speed, simple key-value, ephemeral/cache.
- SQL: relational integrity, complex queries, long-term storage.
- Use both: SQL as source of truth; Redis as low-latency cache.