🔍 Code Extractor

function serve_generated_file

Maturity: 48

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

File:
/tf/active/vicechatdev/full_smartstat/app.py
Lines:
1738 - 1791
Complexity:
moderate

Purpose

This function serves as a secure file delivery endpoint for a Flask web application. It locates and serves files generated during analysis sessions, searching through analysis subdirectories and handling nested paths. It includes security measures to prevent directory traversal attacks and automatically determines appropriate MIME types for different file formats. The function prioritizes files in the most recent analysis directory before falling back to the session root directory.

Source Code

def serve_generated_file(session_id, filename):
    """Serve generated file (for viewing in browser)"""
    try:
        session_dir = Path(app_config.OUTPUT_DIR) / session_id
        
        # Try to find the file in analysis subdirectories first
        file_path = None
        
        # Check analysis subdirectories
        analysis_dirs = [d for d in session_dir.iterdir() if d.is_dir() and d.name.startswith('analysis_')]
        if analysis_dirs:
            # Use the most recent analysis directory
            latest_analysis_dir = max(analysis_dirs, key=lambda d: d.stat().st_mtime)
            potential_path = latest_analysis_dir / filename
            if potential_path.exists() and potential_path.is_file():
                file_path = potential_path
        
        # Fallback to direct session directory
        if not file_path:
            potential_path = session_dir / filename
            if potential_path.exists() and potential_path.is_file():
                file_path = potential_path
        
        # Handle nested paths (analysis_hash/filename)
        if not file_path and '/' in filename:
            potential_path = session_dir / filename
            if potential_path.exists() and potential_path.is_file():
                file_path = potential_path
        
        if not file_path:
            return jsonify({'error': 'File not found'}), 404
        
        # Security check: ensure file is within session directory
        if not str(file_path.resolve()).startswith(str(session_dir.resolve())):
            return jsonify({'error': 'Access denied'}), 403
        
        # Determine MIME type
        mime_type = 'text/plain'
        if filename.lower().endswith(('.png', '.jpg', '.jpeg')):
            mime_type = f'image/{filename.split(".")[-1].lower()}'
        elif filename.lower().endswith('.svg'):
            mime_type = 'image/svg+xml'
        elif filename.lower().endswith('.html'):
            mime_type = 'text/html'
        elif filename.lower().endswith('.css'):
            mime_type = 'text/css'
        elif filename.lower().endswith('.js'):
            mime_type = 'application/javascript'
        
        return send_file(file_path, mimetype=mime_type)
        
    except Exception as e:
        logger.error(f"Error serving file {filename} for session {session_id}: {str(e)}")
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
session_id - - positional_or_keyword
filename - - positional_or_keyword

Parameter Details

session_id: Unique identifier for the user session. Used to locate the session-specific directory under app_config.OUTPUT_DIR. Expected to be a string (typically UUID format) that corresponds to an existing session directory.

filename: Name or relative path of the file to serve. Can be a simple filename (e.g., 'chart.png') or a nested path (e.g., 'analysis_abc123/report.html'). The function will search for this file in analysis subdirectories and the session root directory.

Return Value

Returns a Flask response object. On success, returns the requested file with appropriate MIME type using send_file(). On error, returns a JSON response with an 'error' key and appropriate HTTP status code: 404 if file not found, 403 if access denied (security violation), or 500 for other exceptions.

Dependencies

  • flask
  • pathlib
  • logging

Required Imports

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

Usage Example

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

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

class AppConfig:
    OUTPUT_DIR = '/path/to/output'

app_config = AppConfig()

# Register route
@app.route('/serve/<session_id>/<path:filename>')
def serve_generated_file(session_id, filename):
    # ... function code here ...
    pass

# Usage in browser or API call:
# GET http://localhost:5000/serve/abc-123-def/chart.png
# GET http://localhost:5000/serve/abc-123-def/analysis_xyz/report.html

# Programmatic usage:
with app.test_client() as client:
    response = client.get('/serve/session123/output.png')
    if response.status_code == 200:
        image_data = response.data

Best Practices

  • Always validate that app_config.OUTPUT_DIR is properly configured before using this endpoint
  • Ensure session directories are created with appropriate permissions to prevent unauthorized access
  • The function includes path traversal protection - do not modify the security check that verifies files are within the session directory
  • File paths are resolved and checked against the session directory to prevent accessing files outside the intended scope
  • The function searches analysis subdirectories by modification time, prioritizing the most recent analysis
  • MIME type detection is basic - extend the mime_type logic if serving additional file types
  • Consider implementing rate limiting or authentication for production use to prevent abuse
  • The function logs errors but returns generic error messages to clients - avoid exposing sensitive path information
  • Ensure proper cleanup of old session directories to prevent disk space issues

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function download_generated_file 82.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 serve_plot 76.5% 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 download_file 73.2% similar

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

    From: /tf/active/vicechatdev/leexi/app.py
  • function serve_analysis_plot 70.4% 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 view_document 66.5% similar

    Flask route handler that serves documents for in-browser viewing by accepting a file path as a query parameter, validating security constraints, and returning the file with appropriate MIME types and CORS headers.

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