🔍 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 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
  • function test_multiple_file_upload 55.6% similar

    A test function that validates multiple file upload functionality to a Flask application endpoint by sending a transcript file and multiple previous report files.

    From: /tf/active/vicechatdev/leexi/test_flask_upload.py
  • function index 55.1% similar

    Flask route handler that renders the main landing page containing a form for the meeting minutes application.

    From: /tf/active/vicechatdev/leexi/app.py
  • function generate_minutes 51.7% similar

    Flask route handler that processes uploaded meeting transcripts and optional supporting documents to generate structured meeting minutes using AI, with configurable output styles and validation.

    From: /tf/active/vicechatdev/leexi/app.py
  • function health_check 48.2% similar

    A Flask route handler that provides a health check endpoint returning the application's status and current timestamp.

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