🔍 Code Extractor

function load_session_from_disk

Maturity: 46

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.

File:
/tf/active/vicechatdev/docchat/app.py
Lines:
133 - 146
Complexity:
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

  • json
  • datetime
  • logging
  • pathlib

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function save_session_to_disk_v1 74.4% similar

    Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings for storage.

    From: /tf/active/vicechatdev/docchat/blueprint.py
  • function save_session_to_disk 74.2% similar

    Persists a chat session to disk by serializing session data to a JSON file, converting datetime objects to ISO format strings.

    From: /tf/active/vicechatdev/docchat/app.py
  • function load_chat_session_from_file 72.5% similar

    Loads a chat session from a JSON file stored in the CHAT_SESSIONS_DIR directory using the provided session_id as the filename.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
  • function load_all_sessions 71.3% similar

    Loads all chat session data from JSON files stored in a sessions directory into memory on application startup.

    From: /tf/active/vicechatdev/docchat/app.py
  • function load_all_chat_sessions 65.7% similar

    Loads all chat session data from JSON files stored in a designated directory and returns them as a dictionary indexed by session ID.

    From: /tf/active/vicechatdev/vice_ai/complex_app.py
← Back to Browse