function download_file
Flask route handler that serves generated report files for download from a designated reports folder.
/tf/active/vicechatdev/leexi/app.py
399 - 408
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
flaskpathlib
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_upload 63.7% similar
-
function test_multiple_file_upload 55.6% similar
-
function index 55.1% similar
-
function generate_minutes 51.7% similar
-
function health_check 48.2% similar