🔍 Code Extractor

function serve_plot

Maturity: 50

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

File:
/tf/active/vicechatdev/full_smartstat/app.py
Lines:
1450 - 1463
Complexity:
simple

Purpose

This function is a Flask endpoint that retrieves and serves plot files (typically images like PNG, JPG, SVG) that have been generated during data analysis sessions. It constructs the file path based on session ID and filename, validates the file exists, and returns it to the client. This enables web applications to display dynamically generated visualizations to users.

Source Code

def serve_plot(session_id, plot_filename):
    """Serve generated plot files"""
    try:
        # Construct plot path
        plot_path = app_config.SANDBOX_FOLDER / session_id / 'plots' / plot_filename
        
        if not plot_path.exists():
            return jsonify({'error': 'Plot not found'}), 404
        
        return send_file(plot_path, as_attachment=False)
        
    except Exception as e:
        logger.error(f"Error serving plot: {str(e)}")
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
session_id - - positional_or_keyword
plot_filename - - positional_or_keyword

Parameter Details

session_id: String identifier for the user session. Used to locate the session-specific directory containing plots. Should be a valid directory name (typically UUID or alphanumeric string).

plot_filename: Name of the plot file to serve, including extension (e.g., 'scatter_plot.png'). This is a path parameter that can include subdirectories. The filename should be URL-safe and point to an existing file in the session's plots directory.

Return Value

Returns a Flask Response object. On success (200), returns the plot file for display in browser using send_file(). On error, returns a JSON object with an 'error' key containing the error message, along with appropriate HTTP status code (404 if plot not found, 500 for other exceptions).

Dependencies

  • flask
  • pathlib
  • logging

Required Imports

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

Usage Example

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

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

# Configuration object
class AppConfig:
    SANDBOX_FOLDER = Path('/tmp/analysis_sessions')

app_config = AppConfig()

# Route handler
@app.route('/plot/<session_id>/<path:plot_filename>')
def serve_plot(session_id, plot_filename):
    try:
        plot_path = app_config.SANDBOX_FOLDER / session_id / 'plots' / plot_filename
        if not plot_path.exists():
            return jsonify({'error': 'Plot not found'}), 404
        return send_file(plot_path, as_attachment=False)
    except Exception as e:
        logger.error(f"Error serving plot: {str(e)}")
        return jsonify({'error': str(e)}), 500

# Client usage example:
# GET http://localhost:5000/plot/abc123/scatter_plot.png
# Returns the image file for display in browser

Best Practices

  • Ensure SANDBOX_FOLDER is properly configured and has appropriate read permissions
  • Validate session_id format before use to prevent directory traversal attacks (though Path handles this reasonably well)
  • Consider implementing file type validation to only serve image files (PNG, JPG, SVG, etc.)
  • Use secure_filename() from werkzeug.utils on plot_filename if accepting user input to prevent path traversal
  • Implement session validation to ensure users can only access their own plots
  • Consider adding cache headers to the response for better performance
  • Log access attempts for security auditing
  • Set appropriate MIME types based on file extension for proper browser rendering
  • Consider implementing rate limiting to prevent abuse
  • Clean up old session directories periodically to prevent disk space issues

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function serve_analysis_plot 86.8% similar

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

    From: /tf/active/vicechatdev/vice_ai/new_app.py
  • function smartstat_get_plot 82.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 serve_generated_file 76.5% 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 download_file 68.7% similar

    Flask route handler that serves generated report files for download from a designated reports folder.

    From: /tf/active/vicechatdev/leexi/app.py
  • function download_generated_file 67.7% 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
← Back to Browse