Performance: Serving uploaded files
This affects page load speed and responsiveness when users request uploaded files from the server.
from flask import Flask, send_from_directory app = Flask(__name__) @app.route('/uploads/<filename>') def serve_file(filename): return send_from_directory('uploads', filename, as_attachment=False)
from flask import Flask, send_file app = Flask(__name__) @app.route('/uploads/<filename>') def serve_file(filename): return send_file(f'uploads/{filename}')
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| send_file with large files | 0 (server-side) | 0 | 0 | [X] Bad |
| send_from_directory streaming | 0 (server-side) | 0 | 0 | [OK] Good |
send_from_directory.render_template is for HTML templates, redirect sends users to a different URL, and url_for builds URLs. Only send_from_directory serves files.example.txt from the folder uploads in Flask?send_from_directory takes two arguments: the folder name and the filename.send_from_directory('uploads', 'example.txt'). Options A, B, and D use incorrect functions or formats.from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route('/uploads/<filename>')
def uploaded_file(filename):
return send_from_directory('uploads', filename)/uploads/photo.png?send_from_directory with 'uploads' folder and the filename./uploads/photo.png triggers the function to send the file 'photo.png' from the 'uploads' folder to the user.from flask import Flask, send_from_directory
app = Flask(__name__)
@app.route('/files/<filename>')
def files(filename):
return send_from_directory(filename, 'uploads')send_from_directory(filename, 'uploads'), but the first argument should be the folder, second the filename.send_from_directory('uploads', filename). The route and function name are valid, and send_from_directory is allowed in routes.user_uploads. Which Flask route setup correctly serves files while preventing directory traversal attacks?path:filename lets users include slashes, risking access outside the folder.@app.route('/files/<filename>')
def serve_file(filename):
return send_from_directory('user_uploads', filename) uses <filename> (no slashes) and send_from_directory, which safely serves files and prevents traversal.@app.route('/files/<path:filename>')
def serve_file(filename):
return send_from_directory('user_uploads', filename) allows paths, risking traversal. @app.route('/files/<filename>')
def serve_file(filename):
return send_file(f'user_uploads/{filename}') uses send_file with string path, less safe. @app.route('/files/<filename>')
def serve_file(filename):
return open(f'user_uploads/{filename}').read() reads file content directly, unsafe and breaks response.Pass the test and this pattern moves unknown