Session Examples๏
This section contains examples demonstrating the session management capabilities of True Storage.
Basic Session Usage๏
The following example shows basic session operations:
1"""
2Basic Session Management Demo
3
4This demo shows the fundamental operations of the True Storage session management system.
5"""
6
7from true_storage.session import SessionStore, SessionStoreConfig
8
9def main():
10 # Initialize session store with default configuration
11 print("๐ Initializing session store...")
12 store = SessionStore()
13
14 # Basic key-value operations
15 print("\n๐ Basic key-value operations:")
16 store['user_id'] = 'user123' # Dict-style setting
17 store.set('username', 'John Doe') # Method-style setting
18
19 print(f"User ID: {store.get('user_id')}")
20 print(f"Username: {store['username']}") # Dict-style getting
21
22 # Default values
23 print("\n๐ Using default values:")
24 print(f"Age (with default): {store.get('age', default=25)}")
25 print(f"Email (with default): {store.get('email', default='no-email')}")
26
27 # Check key existence
28 print("\n๐ Checking key existence:")
29 print(f"'user_id' exists: {'user_id' in store}")
30 print(f"'age' exists: {'age' in store}")
31
32 # Store different types of data
33 print("\n๐ฆ Storing different data types:")
34 store.set('numbers', [1, 2, 3, 4, 5])
35 store.set('config', {'theme': 'dark', 'language': 'en'})
36 store.set('is_active', True)
37
38 print(f"Numbers: {store.get('numbers')}")
39 print(f"Config: {store.get('config')}")
40 print(f"Is Active: {store.get('is_active')}")
41
42 # Delete operations
43 print("\nโ Delete operations:")
44 store.delete('username')
45 print(f"After deletion, username exists: {'username' in store}")
46
47 # Clear all sessions
48 print("\n๐งน Clearing all sessions...")
49 store.clear()
50 print(f"Store size after clear: {len(store)}")
51
52if __name__ == '__main__':
53 main()
- Key features demonstrated:
Session creation
Data storage and retrieval
Session cleanup
Basic error handling
Session Expiration๏
This example demonstrates session expiration handling:
1"""
2Session Expiration and Cleanup Demo
3
4This demo demonstrates session expiration and cleanup features of True Storage.
5"""
6
7import time
8from true_storage.session import SessionStore, SessionStoreConfig
9
10def main():
11 # Initialize session store with custom expiration settings
12 print("๐ Initializing session store with custom expiration...")
13 config = SessionStoreConfig(
14 max_size=100,
15 expiration_time=5, # 5 seconds expiration
16 cleanup_interval=2 # Clean up every 2 seconds
17 )
18 store = SessionStore(config)
19
20 # Set some session data
21 print("\n๐ Setting session data...")
22 store.set('quick_expire', 'This will expire in 5 seconds')
23 store.set('user_data', {'name': 'John', 'age': 30})
24
25 print("Initial data:")
26 print(f"quick_expire: {store.get('quick_expire')}")
27 print(f"user_data: {store.get('user_data')}")
28
29 # Wait for expiration
30 print("\nโณ Waiting for session expiration (6 seconds)...")
31 time.sleep(6)
32
33 print("\nAfter waiting:")
34 print(f"quick_expire exists: {'quick_expire' in store}")
35 print(f"quick_expire value: {store.get('quick_expire', 'EXPIRED!')}")
36 print(f"user_data exists: {'user_data' in store}")
37
38 # Set data with different expiration times
39 print("\n๐ Setting data with different expiration times...")
40 store.set('short_lived', 'Expires quickly')
41 store.set('long_lived', 'Stays longer')
42
43 print("\nInitial state:")
44 print(f"short_lived: {store.get('short_lived')}")
45 print(f"long_lived: {store.get('long_lived')}")
46
47 print("\nโณ Waiting for 3 seconds...")
48 time.sleep(3)
49
50 print("\nAfter 3 seconds:")
51 print(f"short_lived: {store.get('short_lived', 'EXPIRED!')}")
52 print(f"long_lived: {store.get('long_lived', 'EXPIRED!')}")
53
54 # Check session metadata
55 print("\n๐ Checking session metadata...")
56 if metadata := store.get_metadata('long_lived'):
57 print(f"Created at: {metadata.created_at}")
58 print(f"Last accessed: {metadata.last_accessed}")
59 print(f"Access count: {metadata.access_count}")
60 print(f"Status: {metadata.status}")
61
62 # Demonstrate cleanup
63 print("\n๐งน Demonstrating cleanup...")
64 print(f"Store size before cleanup: {len(store)}")
65 time.sleep(3) # Wait for cleanup cycle
66 print(f"Store size after cleanup: {len(store)}")
67
68 # Stop the session store properly
69 print("\n๐ Stopping session store...")
70 store.stop()
71
72if __name__ == '__main__':
73 main()
- Key features demonstrated:
Setting session timeouts
Handling expired sessions
Auto-cleanup
Time-based operations
Session Locking๏
The following example shows thread-safe session operations:
1"""
2Session Locking Demo
3
4This demo shows how to use session locking for thread-safe operations.
5"""
6
7import threading
8import time
9from true_storage.session import SessionStore, SessionStoreConfig, StorageError
10
11def worker(name: str, store: SessionStore, key: str):
12 """Worker function that tries to access and modify a locked session."""
13 try:
14 print(f"\n๐ค Worker {name}: Attempting to access key '{key}'")
15 value = store.get(key)
16 print(f"๐ค Worker {name}: Read value: {value}")
17
18 # Try to modify the value
19 new_value = f"Modified by {name}"
20 store.set(key, new_value)
21 print(f"๐ค Worker {name}: Successfully modified value to: {new_value}")
22
23 except StorageError as e:
24 print(f"โ Worker {name}: Access denied - {e}")
25
26def main():
27 # Initialize session store with shorter lock timeout
28 print("๐ Initializing session store...")
29 config = SessionStoreConfig(
30 max_size=100,
31 max_lock_time=5 # 5 seconds maximum lock time
32 )
33 store = SessionStore(config)
34
35 # Set initial data
36 key = 'shared_data'
37 store.set(key, 'Initial value')
38
39 # Demonstrate basic locking
40 print("\n๐ Basic locking demonstration:")
41 print(f"Initial value: {store.get(key)}")
42
43 # Lock the session
44 print("\nLocking session...")
45 store.lock(key)
46
47 # Try to access locked session
48 try:
49 store.set(key, 'New value')
50 print("โ
Set new value (shouldn't happen when locked)")
51 except StorageError as e:
52 print(f"โ Failed to set value: {e}")
53
54 # Check lock status
55 status = store.get_status(key)
56 print(f"\n๐ Session status: {status}")
57
58 # Unlock the session
59 print("\n๐ Unlocking session...")
60 store.unlock(key)
61
62 # Demonstrate concurrent access
63 print("\n๐ Demonstrating concurrent access...")
64
65 # Lock the session again
66 store.lock(key)
67
68 # Create worker threads
69 threads = []
70 for i in range(3):
71 thread = threading.Thread(
72 target=worker,
73 args=(f"Worker-{i}", store, key)
74 )
75 threads.append(thread)
76 thread.start()
77
78 # Wait a bit before unlocking
79 print("\nโณ Waiting with lock held...")
80 time.sleep(2)
81
82 # Unlock for workers
83 print("\n๐ Unlocking for workers...")
84 store.unlock(key)
85
86 # Wait for all threads to complete
87 for thread in threads:
88 thread.join()
89
90 # Show final value
91 print(f"\n๐ Final value: {store.get(key)}")
92
93 # Demonstrate lock timeout
94 print("\nโฒ๏ธ Demonstrating lock timeout...")
95 store.lock(key, duration=3) # Lock for 3 seconds
96 print("Session locked for 3 seconds")
97
98 print("Waiting for lock to expire...")
99 time.sleep(4)
100
101 # Try to access after timeout
102 try:
103 store.set(key, 'After timeout')
104 print("โ
Successfully set value after lock timeout")
105 except StorageError as e:
106 print(f"โ Failed to set value: {e}")
107
108 # Stop the session store
109 print("\n๐ Stopping session store...")
110 store.stop()
111
112if __name__ == '__main__':
113 main()
- Key features demonstrated:
Thread synchronization
Lock acquisition
Deadlock prevention
Concurrent access
Session Persistence๏
This example demonstrates session persistence features:
1"""
2Session Persistence and Recovery Demo
3
4This demo shows how to use session persistence features for data durability.
5"""
6
7import os
8import time
9from pathlib import Path
10from true_storage.session import SessionStore, SessionStoreConfig
11
12def main():
13 # Setup persistence directory
14 persistence_dir = Path("session_data")
15 persistence_dir.mkdir(exist_ok=True)
16 persistence_path = str(persistence_dir / "sessions.json")
17
18 # Initialize session store with persistence
19 print("๐ Initializing session store with persistence...")
20 config = SessionStoreConfig(
21 max_size=100,
22 persistence_path=persistence_path,
23 backup_interval=5, # Backup every 5 seconds
24 enable_logging=True
25 )
26 store = SessionStore(config)
27
28 # Check if we have any restored sessions
29 print("\n๐ฅ Checking for restored sessions...")
30 print(f"Current store size: {len(store)}")
31
32 # Set some session data
33 print("\n๐ Setting new session data...")
34 store.set('user_prefs', {
35 'theme': 'dark',
36 'language': 'en',
37 'notifications': True
38 })
39 store.set('cart_items', [
40 {'id': 1, 'name': 'Widget', 'quantity': 2},
41 {'id': 2, 'name': 'Gadget', 'quantity': 1}
42 ])
43
44 # Wait for automatic backup
45 print("\nโณ Waiting for automatic backup (6 seconds)...")
46 time.sleep(6)
47
48 # Verify data was persisted
49 print("\n๐ Verifying persistence file...")
50 if os.path.exists(persistence_path):
51 print(f"โ
Persistence file exists at: {persistence_path}")
52 print(f"File size: {os.path.getsize(persistence_path)} bytes")
53
54 # Simulate application restart
55 print("\n๐ Simulating application restart...")
56 store.stop()
57
58 print("\nโณ Waiting a moment...")
59 time.sleep(2)
60
61 # Create new store instance
62 print("\n๐ Creating new store instance...")
63 new_store = SessionStore(config)
64
65 # Verify data was restored
66 print("\n๐ Verifying restored data...")
67 print("\nRestored user preferences:")
68 print(new_store.get('user_prefs'))
69 print("\nRestored cart items:")
70 print(new_store.get('cart_items'))
71
72 # Demonstrate atomic updates
73 print("\nโก Demonstrating atomic updates...")
74 for i in range(5):
75 new_store.set(f'counter_{i}', i)
76 print(f"Set counter_{i} = {i}")
77 time.sleep(1) # Allow time for backup
78
79 # Final verification
80 print("\n๐ Final store statistics:")
81 print(f"Total sessions: {len(new_store)}")
82 print(f"Persistence file size: {os.path.getsize(persistence_path)} bytes")
83
84 # Clean up
85 print("\n๐งน Cleaning up...")
86 new_store.stop()
87
88 # Optionally remove persistence file
89 if input("\nRemove persistence file? (y/n): ").lower() == 'y':
90 os.remove(persistence_path)
91 persistence_dir.rmdir()
92 print("โ
Persistence file and directory removed")
93 else:
94 print(f"โน๏ธ Persistence file kept at: {persistence_path}")
95
96if __name__ == '__main__':
97 main()
- Key features demonstrated:
Session storage backends
Data persistence
Recovery mechanisms
Backend configuration
Advanced Session Features๏
This example shows advanced session management features:
1"""
2Advanced Session Features Demo
3
4This demo showcases advanced features of the True Storage session management system.
5"""
6
7import threading
8import time
9import logging
10from datetime import datetime
11from true_storage.session import SessionStore, SessionStoreConfig
12
13class SessionMonitor:
14 """Utility class to monitor session store metrics."""
15
16 def __init__(self, store: SessionStore):
17 self.store = store
18 self.start_time = time.time()
19 self._stop_monitor = threading.Event()
20 self._monitor_thread = threading.Thread(
21 target=self._monitor_loop,
22 daemon=True
23 )
24 self._monitor_thread.start()
25
26 def _monitor_loop(self):
27 while not self._stop_monitor.is_set():
28 active_sessions = len(self.store)
29 total_accesses = sum(
30 metadata.access_count
31 for metadata in self.store._metadata.values()
32 )
33 print(f"\n๐ Monitor Stats ({datetime.now().strftime('%H:%M:%S')})")
34 print(f"Active Sessions: {active_sessions}")
35 print(f"Total Accesses: {total_accesses}")
36 print(f"Uptime: {int(time.time() - self.start_time)} seconds")
37 self._stop_monitor.wait(5)
38
39 def stop(self):
40 self._stop_monitor.set()
41 self._monitor_thread.join()
42
43def session_worker(name: str, store: SessionStore):
44 """Worker function that performs various session operations."""
45 for i in range(5):
46 try:
47 # Create a session
48 key = f"worker_{name}_session_{i}"
49 store.set(key, {
50 'worker': name,
51 'iteration': i,
52 'timestamp': time.time()
53 })
54
55 # Simulate some work
56 time.sleep(0.5)
57
58 # Access the session
59 data = store.get(key)
60 if data:
61 # Modify the session
62 data['accessed'] = True
63 store.set(key, data)
64
65 # Sometimes lock the session
66 if i % 2 == 0:
67 store.lock(key, duration=1)
68 time.sleep(0.5)
69 store.unlock(key)
70
71 except Exception as e:
72 logging.error(f"Worker {name} error: {e}")
73
74def main():
75 # Configure logging
76 logging.basicConfig(
77 level=logging.INFO,
78 format='%(asctime)s - %(levelname)s - %(message)s'
79 )
80
81 # Initialize session store with advanced configuration
82 print("๐ Initializing session store with advanced features...")
83 config = SessionStoreConfig(
84 max_size=1000,
85 expiration_time=30,
86 cleanup_interval=5,
87 enable_logging=True,
88 log_level=logging.INFO
89 )
90 store = SessionStore(config)
91
92 # Start session monitoring
93 print("\n๐ Starting session monitoring...")
94 monitor = SessionMonitor(store)
95
96 # Create worker threads
97 print("\n๐ฅ Starting worker threads...")
98 workers = []
99 for i in range(3):
100 worker = threading.Thread(
101 target=session_worker,
102 args=(f"Worker-{i}", store)
103 )
104 workers.append(worker)
105 worker.start()
106
107 # Demonstrate metadata tracking
108 print("\n๐ Demonstrating metadata tracking...")
109 test_key = 'metadata_test'
110 store.set(test_key, 'test_value')
111
112 # Access the value multiple times
113 for _ in range(5):
114 store.get(test_key)
115 time.sleep(0.1)
116
117 # Display metadata
118 if metadata := store.get_metadata(test_key):
119 print(f"\nSession Metadata for '{test_key}':")
120 print(f"Created: {datetime.fromtimestamp(metadata.created_at)}")
121 print(f"Last Accessed: {datetime.fromtimestamp(metadata.last_accessed)}")
122 print(f"Access Count: {metadata.access_count}")
123 print(f"Status: {metadata.status}")
124
125 # Demonstrate session status transitions
126 print("\n๐ Demonstrating session status transitions...")
127 status_key = 'status_test'
128 store.set(status_key, 'initial_value')
129
130 print(f"Initial status: {store.get_status(status_key)}")
131
132 store.lock(status_key)
133 print(f"After lock: {store.get_status(status_key)}")
134
135 store.unlock(status_key)
136 print(f"After unlock: {store.get_status(status_key)}")
137
138 # Wait for workers to complete
139 print("\nโณ Waiting for workers to complete...")
140 for worker in workers:
141 worker.join()
142
143 # Final statistics
144 print("\n๐ Final Statistics:")
145 print(f"Total Sessions: {len(store)}")
146 print("Session Keys:", list(store.keys()))
147
148 # Stop monitoring and cleanup
149 print("\n๐ Stopping services...")
150 monitor.stop()
151 store.stop()
152
153if __name__ == '__main__':
154 main()
- Key features demonstrated:
Custom session handlers
Event callbacks
Session migration
Advanced configuration