function serve_analysis_plot
Flask route handler that serves analysis plot image files from the data analysis service's plots directory, with authentication and error handling.
/tf/active/vicechatdev/vice_ai/new_app.py
6120 - 6130
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
flaskloggingos
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function serve_plot 86.8% similar
-
function smartstat_get_plot 81.6% similar
-
function serve_generated_file 70.4% similar
-
function get_analysis_files 70.0% similar
-
function upload_analysis_dataset 69.9% similar