function load_all_sessions
Loads all chat session data from JSON files stored in a sessions directory into memory on application startup.
/tf/active/vicechatdev/docchat/app.py
149 - 160
moderate
Purpose
This function is designed to restore application state by reading persisted session data from disk during initialization. It iterates through all JSON files in the SESSIONS_DIR, deserializes each session, and populates the in-memory chat_sessions dictionary with thread-safe locking. This enables session persistence across application restarts and ensures users can resume their conversations.
Source Code
def load_all_sessions():
"""Load all sessions from disk on startup"""
try:
for session_file in SESSIONS_DIR.glob("*.json"):
session_id = session_file.stem
session_data = load_session_from_disk(session_id)
if session_data:
with session_lock:
chat_sessions[session_id] = session_data
logger.info(f"Loaded {len(chat_sessions)} sessions from disk")
except Exception as e:
logger.error(f"Failed to load sessions: {e}")
Return Value
This function does not return any value (implicitly returns None). It performs side effects by populating the global chat_sessions dictionary and logging the operation results.
Dependencies
pathlibloggingthreading
Required Imports
from pathlib import Path
import logging
from threading import Lock
Usage Example
# Setup required globals and dependencies
import logging
from pathlib import Path
from threading import Lock
logger = logging.getLogger(__name__)
SESSIONS_DIR = Path('./sessions')
session_lock = Lock()
chat_sessions = {}
# Define the helper function
def load_session_from_disk(session_id):
session_file = SESSIONS_DIR / f"{session_id}.json"
if session_file.exists():
with open(session_file, 'r') as f:
return json.load(f)
return None
# Ensure sessions directory exists
SESSIONS_DIR.mkdir(exist_ok=True)
# Call the function during application startup
load_all_sessions()
# Check loaded sessions
print(f"Loaded {len(chat_sessions)} sessions")
Best Practices
- This function should be called only once during application startup to avoid duplicate session loading
- Ensure SESSIONS_DIR exists and is writable before calling this function
- The session_lock must be properly initialized as a threading.Lock before calling this function
- The load_session_from_disk helper function must be defined and handle JSON deserialization errors gracefully
- Consider implementing session validation after loading to ensure data integrity
- The function catches all exceptions to prevent startup failures, but logs errors for debugging
- For large numbers of sessions, consider implementing lazy loading or pagination to reduce startup time
- Ensure the logger is configured before calling this function to capture load status and errors
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_all_chat_sessions 91.7% similar
-
function load_chat_session_from_file 79.4% similar
-
function save_session_to_disk_v1 72.4% similar
-
function load_session_from_disk 71.3% similar
-
function save_session_to_disk 71.1% similar