Serving Static Files in Flask
Serving static files is a common task in web development. Flask offers several methods for handling this, including using the built-in static folder route or the send_from_directory function.
Built-in Static Folder Route
Flask automatically creates a route for static files under the /static/
from flask import url_for @app.route('/') def home(): return url_for('static', filename='css/style.css')
send_from_directory Function
The send_from_directory function allows you to serve files from any directory in your app. It takes two arguments: the base directory and the requested file path. It ensures that the requested path is contained within the base directory, preventing directory traversal attacks.
from flask import send_from_directory @app.route('/reports/<path:path>') def send_report(path): return send_from_directory('reports', path)
Note:
Do not use send_file or send_static_file with user-supplied paths, as this can expose you to vulnerabilities. Instead, use send_from_directory, which is designed to safely handle user-supplied paths.
Serving In-Memory Files
If you need to serve a file that is generated in memory without writing it to disk, you can use BytesIO to create an in-memory file object and pass it to send_file. You will also need to specify the file name, content type, and other attributes.
from io import BytesIO import zipfile @app.route('/download.zip') def download_zip(): buffer = BytesIO() zipfile.ZipFile(buffer, 'w').write('file.txt') buffer.seek(0) return send_file(buffer, mimetype='application/zip', as_attachment=True, attachment_filename='download.zip')
The above is the detailed content of How Can I Serve Static Files Efficiently in a Flask Application?. For more information, please follow other related articles on the PHP Chinese website!