🔍 Code Extractor

function index_v1

Maturity: 48

Flask route handler that renders the main application page with user session management, authentication checks, and document collection statistics.

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

  • flask
  • uuid
  • logging
  • datetime
  • config
  • document_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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function index 85.8% similar

    Flask route handler that serves as the main landing page for authenticated users, displaying their documents and text sections in a workspace interface.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function index_v5 83.5% similar

    Flask route handler that renders and serves the main application interface page.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function index_v6 82.7% similar

    Flask route handler that renders the main landing page containing a form for the meeting minutes application.

    From: /tf/active/vicechatdev/leexi/app.py
  • function index_v3 79.4% similar

    Flask route handler that serves as the application's main entry point, redirecting users to either the chat page if authenticated or the login page if not.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function index_v4 79.1% similar

    Flask route handler for the root URL ('/') that redirects authenticated users to the document workspace and unauthenticated users to the login page.

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