function index_v1
Flask route handler that renders the main application page with user session management, authentication checks, and document collection statistics.
/tf/active/vicechatdev/docchat/app.py
798 - 819
moderate
Purpose
This function serves as the entry point for the web application's main page. It initializes user sessions with unique IDs, retrieves user authentication information, fetches document collection statistics from the indexer, and renders the index.html template with all relevant context data. It's designed to be the landing page after login, providing users with an overview of the document collection and their access level.
Source Code
def index():
"""Main page"""
# Create session ID if not exists
if 'session_id' not in session:
session['session_id'] = str(uuid_module.uuid4())
session.permanent = True
app.permanent_session_lifetime = timedelta(hours=config.SESSION_TIMEOUT_HOURS)
# Get user info
user = session.get('user', None)
user_id = get_current_user_id()
is_admin = is_admin_user()
# Get collection stats
stats = {'total_chunks': 0, 'total_documents': 0, 'file_names': []}
if document_indexer:
try:
stats = document_indexer.get_collection_stats()
except Exception as e:
logger.error(f"Failed to get stats: {e}")
return render_template('index.html', stats=stats, user=user, is_admin=is_admin)
Return Value
Returns a rendered HTML template (Flask Response object) containing the main page with three context variables: 'stats' (dictionary with keys 'total_chunks', 'total_documents', 'file_names'), 'user' (user information from session, can be None), and 'is_admin' (boolean indicating admin privileges).
Dependencies
flaskuuidloggingdatetimeconfigdocument_indexer
Required Imports
from flask import Flask, render_template, session
import uuid as uuid_module
from datetime import timedelta
import logging
import config
from document_indexer import DocumentIndexer
Usage Example
# This function is used as a Flask route handler
# Setup required:
from flask import Flask, session
from functools import wraps
import config
from document_indexer import DocumentIndexer
app = Flask(__name__)
app.secret_key = 'your-secret-key'
config.SESSION_TIMEOUT_HOURS = 24
# Initialize document indexer
document_indexer = DocumentIndexer()
# Define required helper functions
def login_required(f):
@wraps(f)
def decorated_function(*args, **kwargs):
if 'user' not in session:
return redirect(url_for('login'))
return f(*args, **kwargs)
return decorated_function
def get_current_user_id():
return session.get('user_id')
def is_admin_user():
return session.get('is_admin', False)
# Apply decorators and register route
@app.route('/')
@login_required
def index():
# Function implementation here
pass
# Access the page by navigating to http://localhost:5000/
Best Practices
- Ensure Flask session secret key is properly configured for secure session management
- The function relies on global variables (document_indexer, logger) which should be properly initialized before the route is accessed
- Error handling is implemented for stats retrieval but errors are only logged, not displayed to users
- Session timeout is configurable via config.SESSION_TIMEOUT_HOURS
- The function assumes login_required decorator handles authentication; ensure it's properly implemented
- Helper functions (get_current_user_id, is_admin_user) must be defined in the same module or imported
- The template 'index.html' must exist and accept stats, user, and is_admin context variables
- Session IDs are generated using UUID4 for uniqueness and security
- Consider implementing proper error pages if document_indexer is None or stats retrieval fails critically
Tags
Similar Components
AI-powered semantic similarity - components with related functionality: