🔍 Code Extractor

function smartstat_download_script

Maturity: 50

Flask route handler that downloads a generated Python analysis script for a specific SmartStat session by locating the most recent project directory and returning the analysis.py file.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
5424 - 5452
Complexity:
moderate

Purpose

This endpoint allows users to download the Python analysis script that was automatically generated during a SmartStat data analysis session. It searches for the most recent project directory within the session's folder structure and serves the analysis.py file as a downloadable attachment. This is useful for users who want to review, modify, or re-run the analysis code locally.

Source Code

def smartstat_download_script(session_id):
    """Download the generated Python analysis script"""
    from pathlib import Path
    from flask import send_file
    
    try:
        base_path = Path(smartstat_config.GENERATED_SCRIPTS_FOLDER) / session_id
        
        # Find the most recent project directory
        project_dirs = list(base_path.glob('project_*'))
        if not project_dirs:
            return jsonify({'error': 'No analysis script found'}), 404
        
        latest_project = max(project_dirs, key=lambda p: p.stat().st_mtime)
        script_path = latest_project / 'analysis.py'
        
        if script_path.exists():
            return send_file(
                str(script_path), 
                as_attachment=True,
                download_name=f'analysis_{session_id}.py',
                mimetype='text/x-python'
            )
        else:
            return jsonify({'error': 'Analysis script not found'}), 404
        
    except Exception as e:
        logger.error(f"Error downloading script: {e}")
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
session_id - - positional_or_keyword

Parameter Details

session_id: Unique identifier for the SmartStat session. This is used to locate the correct session folder containing generated analysis scripts. Expected to be a string (typically UUID format) that corresponds to a valid session directory.

Return Value

Returns a Flask Response object. On success (200), sends the analysis.py file as a downloadable attachment with mimetype 'text/x-python' and filename 'analysis_{session_id}.py'. On error, returns a JSON response with an 'error' key and appropriate HTTP status code: 404 if no script is found, or 500 for other exceptions.

Dependencies

  • flask
  • pathlib

Required Imports

from pathlib import Path
from flask import send_file
from flask import jsonify

Conditional/Optional Imports

These imports are only needed under specific conditions:

from pathlib import Path

Condition: imported inside the function for file system operations

Required (conditional)
from flask import send_file

Condition: imported inside the function for file download functionality

Required (conditional)

Usage Example

# Example Flask app setup
from flask import Flask, jsonify, send_file
from pathlib import Path
import logging

app = Flask(__name__)
logger = logging.getLogger(__name__)

class smartstat_config:
    GENERATED_SCRIPTS_FOLDER = '/path/to/generated/scripts'

def require_auth(f):
    def wrapper(*args, **kwargs):
        # Authentication logic here
        return f(*args, **kwargs)
    return wrapper

@app.route('/api/smartstat/<session_id>/download-script', methods=['GET'])
@require_auth
def smartstat_download_script(session_id):
    from pathlib import Path
    from flask import send_file
    
    try:
        base_path = Path(smartstat_config.GENERATED_SCRIPTS_FOLDER) / session_id
        project_dirs = list(base_path.glob('project_*'))
        if not project_dirs:
            return jsonify({'error': 'No analysis script found'}), 404
        
        latest_project = max(project_dirs, key=lambda p: p.stat().st_mtime)
        script_path = latest_project / 'analysis.py'
        
        if script_path.exists():
            return send_file(
                str(script_path), 
                as_attachment=True,
                download_name=f'analysis_{session_id}.py',
                mimetype='text/x-python'
            )
        else:
            return jsonify({'error': 'Analysis script not found'}), 404
    except Exception as e:
        logger.error(f"Error downloading script: {e}")
        return jsonify({'error': str(e)}), 500

# Client usage example:
# GET /api/smartstat/abc123-session-id/download-script
# Response: Downloads file 'analysis_abc123-session-id.py'

Best Practices

  • Ensure the GENERATED_SCRIPTS_FOLDER path is properly configured and accessible
  • The function uses modification time (st_mtime) to determine the most recent project directory, which assumes system clock accuracy
  • Authentication is required via the require_auth decorator - ensure proper authentication is implemented
  • Error handling returns appropriate HTTP status codes (404 for not found, 500 for server errors)
  • The function converts Path objects to strings for send_file compatibility
  • Session IDs should be validated to prevent directory traversal attacks
  • Consider implementing rate limiting to prevent abuse of the download endpoint
  • The glob pattern 'project_*' assumes a specific naming convention for project directories
  • Logging is used for error tracking - ensure logger is properly configured
  • The download_name parameter provides a user-friendly filename that includes the session_id

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function smartstat_download_log 81.8% similar

    Flask API endpoint that generates and downloads an execution log file containing the analysis history and debug information for a SmartStat session.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function download_generated_file 71.2% similar

    Flask route handler that downloads generated files from a user's session directory, with security checks and support for nested analysis subdirectories.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function smartstat_get_plot 70.8% similar

    Flask route handler that serves plot image files (PNG, JPG, SVG) generated by SmartStat analysis sessions from project directories.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function smartstat_upload_data 69.8% similar

    Flask route handler that uploads CSV or Excel data files to a SmartStat analysis session, with support for multi-sheet Excel files and session recovery.

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function smartstat_save_to_document 69.5% similar

    Flask route handler that saves SmartStat statistical analysis results back to a data section document, generating a final report with queries, results, and plots.

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