🔍 Code Extractor

function download_file

Maturity: 46

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

File:
/tf/active/vicechatdev/leexi/app.py
Lines:
399 - 408
Complexity:
simple

Purpose

This function provides a secure file download endpoint for a Flask web application. It validates that the requested file exists in the REPORTS_FOLDER directory, serves it as an attachment for download, and handles errors gracefully by returning appropriate JSON error responses with HTTP status codes.

Source Code

def download_file(filename):
    """Download generated report"""
    try:
        file_path = REPORTS_FOLDER / filename
        if file_path.exists():
            return send_file(file_path, as_attachment=True)
        else:
            return jsonify({'error': 'File not found'}), 404
    except Exception as e:
        return jsonify({'error': str(e)}), 500

Parameters

Name Type Default Kind
filename - - positional_or_keyword

Parameter Details

filename: The path/name of the file to download, captured from the URL path parameter. This should be a relative path within the REPORTS_FOLDER. The path: converter in the route allows for filenames with forward slashes (subdirectories).

Return Value

Returns a Flask Response object. On success: sends the file as an attachment for download. On file not found: returns a JSON object {'error': 'File not found'} with HTTP 404 status. On exception: returns a JSON object {'error': '<error message>'} with HTTP 500 status.

Dependencies

  • flask
  • pathlib

Required Imports

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

Usage Example

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

app = Flask(__name__)
REPORTS_FOLDER = Path('./reports')
REPORTS_FOLDER.mkdir(exist_ok=True)

@app.route('/download/<path:filename>')
def download_file(filename):
    try:
        file_path = REPORTS_FOLDER / filename
        if file_path.exists():
            return send_file(file_path, as_attachment=True)
        else:
            return jsonify({'error': 'File not found'}), 404
    except Exception as e:
        return jsonify({'error': str(e)}), 500

if __name__ == '__main__':
    # Create a test file
    test_file = REPORTS_FOLDER / 'test_report.txt'
    test_file.write_text('Sample report content')
    
    # Access via: http://localhost:5000/download/test_report.txt
    app.run(debug=True)

Best Practices

  • Always validate and sanitize the filename parameter to prevent directory traversal attacks (consider using werkzeug.utils.secure_filename)
  • Ensure REPORTS_FOLDER is properly configured and has appropriate read permissions
  • Consider adding authentication/authorization checks before allowing file downloads
  • The path: converter in the route allows subdirectories, which could be a security risk if not properly validated
  • Consider implementing rate limiting to prevent abuse of the download endpoint
  • Log download attempts for audit purposes
  • Verify that the resolved file_path stays within REPORTS_FOLDER boundaries to prevent path traversal attacks
  • Consider adding file size checks to prevent serving extremely large files that could impact server performance

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function download_generated_file 80.9% 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_generated_file 73.2% 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 export_report 71.9% similar

    Flask route handler that exports an analysis report for a given session in either PDF or Word format, retrieving session data and generating a downloadable file.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function serve_plot 68.7% 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 test_upload 63.7% similar

    Flask route handler that serves a static HTML test page for debugging multiple file upload functionality.

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