function on_load
Blueprint initialization hook that loads persisted chat sessions from disk when the DocChat blueprint is registered with the Flask application.
/tf/active/vicechatdev/docchat/blueprint.py
341 - 354
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
flaskpathlib
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function load_all_sessions 69.7% similar
-
function load_all_chat_sessions 69.0% similar
-
function register_docchat 65.8% similar
-
function load_chat_session_from_file 63.8% similar
-
function get_chat_session 63.7% similar