-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathredis_data.py
More file actions
138 lines (111 loc) · 4.52 KB
/
Copy pathredis_data.py
File metadata and controls
138 lines (111 loc) · 4.52 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
import redis
r = redis.Redis(host='localhost', port=6379, db=0)
def populate_test_data():
print("Populating Redis with test data...")
# Clear existing data first (optional)
r.flushdb()
print("\nCleared existing data")
# USERS (Hash data type) - like user profiles
print("\nCreating user profiles...")
r.hset('user:1', mapping={
'name': 'Alice Johnson',
'email': 'alice@example.com',
'age': '25',
'city': 'New York'
})
r.hset('user:2', mapping={
'name': 'Bob Smith',
'email': 'bob@example.com',
'age': '30',
'city': 'Los Angeles'
})
r.hset('user:3', mapping={
'name': 'Charlie Brown',
'email': 'charlie@example.com',
'age': '28',
'city': 'Chicago'
})
# POSTS (Hash data type) - blog posts or content
print("\nCreating posts...")
r.hset('post:101', mapping={
'title': 'Getting Started with Redis',
'author_id': '1',
'content': 'Redis is a powerful in-memory database...',
'created_at': '2024-01-15',
'tags': 'redis,database,tutorial'
})
r.hset('post:102', mapping={
'title': 'NoSQL vs SQL Databases',
'author_id': '2',
'content': 'Understanding the differences between...',
'created_at': '2024-01-20',
'tags': 'nosql,sql,comparison'
})
r.hset('post:103', mapping={
'title': 'Python Redis Integration',
'author_id': '1',
'content': 'How to use Redis with Python applications...',
'created_at': '2024-01-25',
'tags': 'python,redis,programming'
})
# USER POSTS (Lists) - which posts belong to which user
print("\nCreating user post lists...")
r.lpush('user:1:posts', '101', '103') # Alice wrote posts 101 and 103
r.lpush('user:2:posts', '102') # Bob wrote post 102
# TAGS (Sets) - unique tags for each post
print("\nCreating tag sets...")
r.sadd('tags:101', 'redis', 'database', 'tutorial', 'beginner')
r.sadd('tags:102', 'nosql', 'sql', 'comparison', 'database')
r.sadd('tags:103', 'python', 'redis', 'programming', 'integration')
# SIMPLE STRINGS - counters, settings, etc.
print("\nCreating simple strings and counters...")
r.set('site:visitor_count', '1250')
r.set('site:maintenance_mode', 'false')
r.set('config:max_posts_per_user', '100')
# SORTED SETS - leaderboards, rankings
print("\nCreating leaderboard (sorted set)...")
r.zadd('leaderboard:posts', {'user:1': 2, 'user:2': 1, 'user:3': 0})
# USER SESSIONS (Strings with expiration)
print("\nCreating user sessions...")
r.setex('session:user1_abc123', 3600, 'alice_session_data') # expires in 1 hour
r.setex('session:user2_def456', 3600, 'bob_session_data')
print("\nTest data population complete!")
print(f"Total keys created: {len(r.keys('*'))}")
def verify_redis_data():
#prints all created data
print("\n" + "="*60)
print("VERIFYING REDIS DATA - COMPLETE DATABASE DUMP")
print("="*60)
keys = r.keys('*')
print(f"Total keys found: {len(keys)}\n")
for key in sorted(keys):
key_str = key.decode('utf-8')
key_type = r.type(key).decode('utf-8')
print(f"KEY: {key_str}")
print(f"TYPE: {key_type}")
try:
if key_type == 'string':
value = r.get(key).decode('utf-8')
print(f"VALUE: {value}")
elif key_type == 'hash':
value = {k.decode('utf-8'): v.decode('utf-8')
for k, v in r.hgetall(key).items()}
print(f"HASH:")
for k, v in value.items():
print(f" {k}: {v}")
elif key_type == 'list':
value = [item.decode('utf-8') for item in r.lrange(key, 0, -1)]
print(f"LIST: {value}")
elif key_type == 'set':
value = [item.decode('utf-8') for item in r.smembers(key)]
print(f"SET: {value}")
elif key_type == 'zset':
value = [(item.decode('utf-8'), score)
for item, score in r.zrange(key, 0, -1, withscores=True)]
print(f"SORTED SET: {value}")
except Exception as e:
print(f"ERROR reading {key_str}: {e}")
print("-" * 40)
if __name__ == "__main__":
populate_test_data()
verify_redis_data()