Flask | Download Dynamic File [verified]
Generating dynamic files for download in Flask is a common requirement for applications that need to export reports, CSV data, or personalized PDF documents on the fly. Instead of saving a file to the server's disk and then serving it, you can generate the file content in memory and stream it directly to the user's browser. Core Method: Using send_file with In-Memory Buffers
import io import csv from flask import Flask, send_file app = Flask(__name__) @app.route('/download-csv') def download_csv(): # 1. Create a dynamic dataset data = [ ['Name', 'Email', 'Role'], ['Alice', 'alice@example.com', 'Admin'], ['Bob', 'bob@example.com', 'User'] ] # 2. Use StringIO to create an in-memory text buffer proxy = io.StringIO() writer = csv.writer(proxy) writer.writerows(data) # 3. Move the cursor to the beginning of the buffer # This is critical so send_file reads from the start mem = io.BytesIO() mem.write(proxy.getvalue().encode('utf-8')) mem.seek(0) proxy.close() # 4. Return the file using send_file return send_file( mem, mimetype='text/csv', as_attachment=True, download_name='user_report.csv' # formerly attachment_filename ) Use code with caution. Essential Parameters for send_file flask download dynamic file
This example creates a CSV file from a list of data without ever writing a physical file to your server. Generating dynamic files for download in Flask is
The most efficient way to handle dynamic downloads is by using the io module to create a "file-like" object in memory. Create a dynamic dataset data = [ ['Name',
When serving dynamic content, you must explicitly define how the browser should handle the response: Generating Dynamic PDFs With Flask
Use io.BytesIO for raw bytes. Example: Generating a Dynamic CSV
Use io.StringIO to buffer text data.