function load_session_from_disk
Loads a session from disk storage by reading a JSON file identified by session_id, deserializing the data, and converting timestamp strings back to datetime objects.
/tf/active/vicechatdev/docchat/app.py
133 - 146
simple
Purpose
This function retrieves persisted session data from the filesystem for session management in a Flask application. It handles the deserialization of session data including conversion of ISO format timestamp strings back to datetime objects. The function is designed to restore session state across application restarts or for session recovery purposes.
Source Code
def load_session_from_disk(session_id):
"""Load session from disk"""
try:
session_file = SESSIONS_DIR / f"{session_id}.json"
if session_file.exists():
with open(session_file, 'r') as f:
session_data = json.load(f)
# Convert string timestamps back to datetime
session_data['created_at'] = datetime.fromisoformat(session_data['created_at'])
session_data['updated_at'] = datetime.fromisoformat(session_data['updated_at'])
return session_data
except Exception as e:
logger.error(f"Failed to load session {session_id}: {e}")
return None
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
session_id |
- | - | positional_or_keyword |
Parameter Details
session_id: A unique identifier (typically a string or UUID) used to locate the corresponding session file on disk. The function expects a file named '{session_id}.json' to exist in the SESSIONS_DIR directory.
Return Value
Returns a dictionary containing the session data with keys including 'created_at' and 'updated_at' as datetime objects, along with other session-specific data. Returns None if the session file doesn't exist, the session_id is invalid, or if any error occurs during loading (e.g., JSON parsing errors, file read errors).
Dependencies
jsondatetimeloggingpathlib
Required Imports
import json
from datetime import datetime
import logging
from pathlib import Path
Usage Example
import json
from datetime import datetime
from pathlib import Path
import logging
# Setup required configuration
SESSIONS_DIR = Path('./sessions')
SESSIONS_DIR.mkdir(exist_ok=True)
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.INFO)
# Create a sample session file for testing
session_id = 'test-session-123'
sample_session = {
'user_id': 'user123',
'created_at': datetime.now().isoformat(),
'updated_at': datetime.now().isoformat(),
'data': {'key': 'value'}
}
with open(SESSIONS_DIR / f'{session_id}.json', 'w') as f:
json.dump(sample_session, f)
# Load the session
def load_session_from_disk(session_id):
try:
session_file = SESSIONS_DIR / f"{session_id}.json"
if session_file.exists():
with open(session_file, 'r') as f:
session_data = json.load(f)
session_data['created_at'] = datetime.fromisoformat(session_data['created_at'])
session_data['updated_at'] = datetime.fromisoformat(session_data['updated_at'])
return session_data
except Exception as e:
logger.error(f"Failed to load session {session_id}: {e}")
return None
loaded_session = load_session_from_disk(session_id)
if loaded_session:
print(f"Session loaded: {loaded_session['user_id']}")
print(f"Created at: {loaded_session['created_at']}")
else:
print("Session not found or failed to load")
Best Practices
- Ensure SESSIONS_DIR exists and has appropriate read permissions before calling this function
- The function expects session files to contain 'created_at' and 'updated_at' fields in ISO format strings
- Always check if the returned value is None before accessing session data to handle missing or corrupted sessions
- Consider implementing session file validation or schema checking for production use
- The function silently returns None on errors - check logs for detailed error information
- Session files should be stored securely with appropriate file permissions to prevent unauthorized access
- Consider adding file locking mechanisms if multiple processes might access the same session file concurrently
- Implement session cleanup/expiration logic to prevent accumulation of old session files
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function save_session_to_disk_v1 74.4% similar
-
function save_session_to_disk 74.2% similar
-
function load_chat_session_from_file 72.5% similar
-
function load_all_sessions 71.3% similar
-
function load_all_chat_sessions 65.7% similar