🔍 Code Extractor

function create_data_section_analysis_session

Maturity: 48

Flask API endpoint that creates or retrieves an analysis session for a specific data section, ensuring user ownership and linking the session to the data section.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
4419 - 4460
Complexity:
moderate

Purpose

This endpoint serves as a REST API route to initialize data analysis sessions for data sections. It verifies user authentication and ownership, checks for existing analysis sessions to avoid duplicates, creates new sessions when needed, and maintains the relationship between data sections and their analysis sessions. It's designed to be the entry point for users to begin analyzing data within their data sections.

Source Code

def create_data_section_analysis_session(section_id):
    """Create a new analysis session for a data section"""
    if not DATA_ANALYSIS_AVAILABLE:
        return jsonify({'error': 'Data analysis service not available'}), 503
    
    user_email = get_current_user()
    
    # Verify ownership of data section
    data_section = data_section_service.get_data_section(section_id)
    if not data_section or data_section.owner != user_email:
        return jsonify({'error': 'Data section not found or access denied'}), 404
    
    try:
        # Check if section already has an analysis session
        if data_section.analysis_session_id:
            # Return existing session
            session = data_analysis_service.get_analysis_session(data_section.analysis_session_id)
            if session:
                return jsonify({
                    'success': True,
                    'session_id': session.session_id,
                    'existing': True
                })
        
        # Create new analysis session
        session_id = data_analysis_service.create_analysis_session(
            user_id=user_email,
            session_name=f"Analysis: {data_section.title}"
        )
        
        # Link session to data section using the service method
        data_section_service.update_analysis_session(section_id, session_id)
        
        return jsonify({
            'success': True,
            'session_id': session_id,
            'existing': False
        })
        
    except Exception as e:
        logger.error(f"Error creating analysis session: {e}")
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
section_id - - positional_or_keyword

Parameter Details

section_id: String identifier for the data section. This is extracted from the URL path parameter and used to retrieve and verify the data section. Must correspond to an existing data section owned by the authenticated user.

Return Value

Returns a Flask JSON response tuple. On success (200): {'success': True, 'session_id': str, 'existing': bool} where 'existing' indicates if the session was already created. On error: 404 if data section not found or access denied, 503 if data analysis service unavailable, 500 for other exceptions. Error responses include {'error': str} with descriptive message.

Dependencies

  • flask
  • logging

Required Imports

from flask import jsonify
import logging

Usage Example

# Client-side usage (JavaScript fetch example)
fetch('/api/data-sections/abc123/analysis/session', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
    'Authorization': 'Bearer <token>'
  }
})
.then(response => response.json())
.then(data => {
  if (data.success) {
    console.log('Session ID:', data.session_id);
    console.log('Is existing session:', data.existing);
  } else {
    console.error('Error:', data.error);
  }
});

# Server-side context (Flask app setup)
# from flask import Flask
# from auth.azure_auth import require_auth
# from services import DataSectionService, DataAnalysisService
# 
# app = Flask(__name__)
# data_section_service = DataSectionService()
# data_analysis_service = DataAnalysisService()
# DATA_ANALYSIS_AVAILABLE = True
# 
# @app.route('/api/data-sections/<section_id>/analysis/session', methods=['POST'])
# @require_auth
# def create_data_section_analysis_session(section_id):
#     # function implementation

Best Practices

  • Always check DATA_ANALYSIS_AVAILABLE before attempting to use data analysis features
  • Verify user ownership of resources before allowing operations
  • Reuse existing analysis sessions instead of creating duplicates to avoid resource waste
  • Use try-except blocks to catch and log service-layer exceptions
  • Return appropriate HTTP status codes (503 for service unavailable, 404 for not found, 500 for server errors)
  • Log errors with sufficient context for debugging
  • Use the require_auth decorator to ensure only authenticated users can access this endpoint
  • The endpoint is idempotent - calling it multiple times returns the same session
  • Session names are automatically generated from data section titles for better traceability

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_analysis_session 88.4% similar

    Creates a new data analysis session for a text section, verifying ownership and section type before linking the session to the section.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function get_analysis_session 83.9% similar

    Flask API endpoint that retrieves details of a specific data analysis session for an authenticated user, ensuring the user has access to the requested session.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function save_data_section_analysis 82.7% similar

    Flask API endpoint that saves analysis results (plots, conclusions, and analysis data) from a data analysis session to a data section in the database.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function create_data_section 81.5% similar

    Flask API endpoint that creates a new data section for authenticated users, accepting title and description from JSON request body.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function create_new_session 79.6% similar

    Flask route handler that creates a new analysis session with an optional title and description, returning a unique session ID.

    From: /tf/active/vicechatdev/full_smartstat/app.py
← Back to Browse