🔍 Code Extractor

function on_load

Maturity: 46

Blueprint initialization hook that loads persisted chat sessions from disk when the DocChat blueprint is registered with the Flask application.

File:
/tf/active/vicechatdev/docchat/blueprint.py
Lines:
341 - 354
Complexity:
moderate

Purpose

This function serves as a lifecycle hook for the Flask blueprint, executing once during application startup. It restores chat session state by reading JSON files from a sessions directory, populating the in-memory chat_sessions dictionary with previously saved conversation data. This enables session persistence across application restarts.

Source Code

def on_load(state):
    """Called when blueprint is registered with app"""
    logger.info("DocChat blueprint registered")
    
    # Load existing sessions from disk
    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:
                chat_sessions[session_id] = session_data
        logger.info(f"Loaded {len(chat_sessions)} chat sessions")
    except Exception as e:
        logger.error(f"Error loading sessions: {e}")

Parameters

Name Type Default Kind
state - - positional_or_keyword

Parameter Details

state: Flask blueprint state object passed automatically by the Flask framework when the blueprint is registered. Contains information about the blueprint's registration context, though it's not directly used in this implementation.

Return Value

No return value (implicitly returns None). The function performs side effects by populating the global chat_sessions dictionary with loaded session data.

Dependencies

  • flask
  • pathlib

Required Imports

from flask import Blueprint
from pathlib import Path
import logging
import json

Usage Example

# This function is automatically called by Flask, not invoked directly
# Setup required in the module:

from flask import Flask, Blueprint
from pathlib import Path
import logging
import json

logger = logging.getLogger(__name__)
SESSIONS_DIR = Path('./sessions')
chat_sessions = {}

def load_session_from_disk(session_id):
    """Helper function to load a session"""
    try:
        with open(SESSIONS_DIR / f"{session_id}.json", 'r') as f:
            return json.load(f)
    except Exception:
        return None

docchat_bp = Blueprint('docchat', __name__)

@docchat_bp.record_once
def on_load(state):
    """Called when blueprint is registered with app"""
    logger.info("DocChat blueprint registered")
    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:
                chat_sessions[session_id] = session_data
        logger.info(f"Loaded {len(chat_sessions)} chat sessions")
    except Exception as e:
        logger.error(f"Error loading sessions: {e}")

# Register blueprint with app
app = Flask(__name__)
app.register_blueprint(docchat_bp)
# on_load is automatically called during registration

Best Practices

  • This function should not be called directly; it's automatically invoked by Flask when the blueprint is registered
  • Ensure SESSIONS_DIR exists before application startup to avoid exceptions
  • The function uses broad exception handling to prevent application startup failures due to corrupted session files
  • Consider implementing session validation to ensure loaded data has the expected structure
  • The @record_once decorator ensures this function runs only once even if the blueprint is registered multiple times
  • Session files should be in valid JSON format with .json extension
  • The load_session_from_disk helper function should handle malformed JSON gracefully
  • Consider adding session cleanup logic to remove old or invalid sessions during load

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function load_all_sessions 69.7% 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 69.0% 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
  • function register_docchat 65.8% similar

    Registers a DocChat Flask blueprint with a Flask application instance, handling path configuration and error logging.

    From: /tf/active/vicechatdev/docchat/integration.py
  • function load_chat_session_from_file 63.8% 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 get_chat_session 63.7% similar

    Retrieves a chat session by its unique session ID, first checking an in-memory cache, then falling back to loading from persistent file storage if not found in memory.

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