🔍 Code Extractor

function create_new_session

Maturity: 46

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

File:
/tf/active/vicechatdev/full_smartstat/app.py
Lines:
119 - 139
Complexity:
simple

Purpose

This endpoint creates a new analysis session in the system, generating a unique session identifier that can be used to track and manage statistical analysis workflows. It accepts optional title and description parameters via POST request, defaulting to a timestamp-based title if none is provided. The function delegates session creation to an analysis_service and returns the session details in JSON format.

Source Code

def create_new_session():
    """Create new analysis session"""
    try:
        data = request.get_json()
        title = data.get('title', f'Analysis {datetime.now().strftime("%Y%m%d_%H%M%S")}')
        description = data.get('description', '')
        
        session_id = analysis_service.create_analysis_session(title, description)
        
        return jsonify({
            'success': True,
            'session_id': session_id,
            'title': title
        })
        
    except Exception as e:
        logger.error(f"Error creating session: {str(e)}")
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500

Return Value

Returns a Flask JSON response object. On success (HTTP 200): {'success': True, 'session_id': <string>, 'title': <string>}. On error (HTTP 500): {'success': False, 'error': <error_message_string>}. The session_id is a unique identifier generated by the analysis_service.

Dependencies

  • flask
  • logging
  • datetime
  • typing
  • pathlib
  • tempfile
  • base64
  • pandas
  • threading
  • time
  • werkzeug
  • uuid
  • json
  • os

Required Imports

from flask import Flask, request, jsonify
from datetime import datetime
import logging

Usage Example

# Client-side usage example (JavaScript fetch)
fetch('/new_session', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    title: 'Customer Analysis 2024',
    description: 'Analyzing customer behavior patterns'
  })
})
.then(response => response.json())
.then(data => {
  if (data.success) {
    console.log('Session created:', data.session_id);
  } else {
    console.error('Error:', data.error);
  }
});

# Python client usage example
import requests

response = requests.post('http://localhost:5000/new_session', json={
    'title': 'Sales Analysis',
    'description': 'Q4 sales data analysis'
})

result = response.json()
if result['success']:
    session_id = result['session_id']
    print(f"Created session: {session_id}")
else:
    print(f"Error: {result['error']}")

Best Practices

  • Always send requests with 'Content-Type: application/json' header
  • Handle both success and error responses appropriately in client code
  • The session_id returned should be stored and used for subsequent operations on this analysis session
  • Title and description are optional but recommended for better session tracking
  • Check the 'success' field in the response before accessing 'session_id'
  • HTTP 500 errors indicate server-side issues that should be logged and monitored
  • The default title format includes timestamp to ensure uniqueness
  • Ensure the analysis_service is properly initialized before the Flask app starts accepting requests

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function create_data_section_analysis_session 79.6% similar

    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.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function create_analysis_session 77.0% 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 view_session 76.7% similar

    Flask route handler that retrieves and displays an analysis session by its ID, rendering the session details in a template or redirecting on error.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function get_analysis_session 76.3% 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 delete_session 73.9% similar

    Flask route handler that deletes an analysis session and all its associated data from the database, returning a JSON response indicating success or failure.

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