🔍 Code Extractor

function serve_analysis_plot

Maturity: 50

Flask route handler that serves analysis plot image files from the data analysis service's plots directory, with authentication and error handling.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
6120 - 6130
Complexity:
simple

Purpose

This endpoint provides secure access to generated analysis plot images stored on the server. It checks if the data analysis service is available, validates the requested file exists, and returns the image file to authenticated users. Used in web applications to display dynamically generated statistical plots and visualizations.

Source Code

def serve_analysis_plot(filename):
    """Serve analysis plot images"""
    if not DATA_ANALYSIS_AVAILABLE:
        return jsonify({'error': 'Data analysis service not available'}), 503
    
    try:
        plots_dir = data_analysis_service.plots_dir
        return send_file(os.path.join(plots_dir, filename))
    except Exception as e:
        logger.error(f"Error serving plot {filename}: {e}")
        return jsonify({'error': 'Plot not found'}), 404

Parameters

Name Type Default Kind
filename - - positional_or_keyword

Parameter Details

filename: The name of the plot image file to serve (e.g., 'histogram_2024.png'). This is extracted from the URL path and should be a valid filename without directory traversal characters. The file must exist in the data analysis service's plots directory.

Return Value

Returns a Flask Response object containing the requested image file on success. On failure, returns a JSON response with an error message and appropriate HTTP status code: 503 if data analysis service is unavailable, or 404 if the plot file is not found or cannot be accessed.

Dependencies

  • flask
  • logging
  • os

Required Imports

from flask import jsonify
from flask import send_file
import os
import logging

Usage Example

# In Flask application setup:
from flask import Flask, jsonify, send_file
import os
import logging
from data_analysis_service import DataAnalysisService
from functools import wraps

app = Flask(__name__)
logger = logging.getLogger(__name__)
DATA_ANALYSIS_AVAILABLE = True
data_analysis_service = DataAnalysisService()

# Authentication decorator (simplified example)
def require_auth(f):
    @wraps(f)
    def decorated(*args, **kwargs):
        # Add authentication logic here
        return f(*args, **kwargs)
    return decorated

@app.route('/api/analysis-plots/<path:filename>')
@require_auth
def serve_analysis_plot(filename):
    if not DATA_ANALYSIS_AVAILABLE:
        return jsonify({'error': 'Data analysis service not available'}), 503
    try:
        plots_dir = data_analysis_service.plots_dir
        return send_file(os.path.join(plots_dir, filename))
    except Exception as e:
        logger.error(f"Error serving plot {filename}: {e}")
        return jsonify({'error': 'Plot not found'}), 404

# Client-side usage:
# GET request to: http://your-domain/api/analysis-plots/my_plot.png
# Returns the image file if authenticated and file exists

Best Practices

  • Always validate and sanitize the filename parameter to prevent directory traversal attacks (e.g., using werkzeug.utils.secure_filename)
  • Ensure the plots directory has appropriate read permissions for the application user
  • Consider implementing rate limiting to prevent abuse of the endpoint
  • Add MIME type validation to ensure only image files are served
  • Implement proper logging for security auditing and debugging
  • Consider adding cache headers to improve performance for frequently accessed plots
  • Use absolute paths when constructing file paths to avoid path traversal vulnerabilities
  • Implement file existence checks before attempting to serve files
  • Consider adding file size limits to prevent serving excessively large files
  • Ensure the authentication decorator properly validates user permissions before allowing access

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function serve_plot 86.8% similar

    Flask route handler that serves generated plot image files from a session-specific plots directory.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function smartstat_get_plot 81.6% 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 serve_generated_file 70.4% similar

    Flask route handler that serves generated files (images, HTML, CSS, JS, etc.) from session-specific directories, with security checks and automatic MIME type detection.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function get_analysis_files 70.0% similar

    Flask API endpoint that retrieves files associated with a specific analysis within a session, returning them as a JSON response.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function upload_analysis_dataset 69.9% similar

    Flask API endpoint that handles file upload for data analysis sessions, accepting CSV and Excel files, validating user access, and processing the dataset through a data analysis service.

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