Flask allows downloads, just like JavaScript-based web applications do.
There are two components to this process.
There needs to be an HTML href
, which will call the appropriate Python function for the download.
<a href="{{ url_for('download', filename="downloadFile.txt") }}">File</a>
The Python component will consist of a function that will return the required file to the client.
@app.route('/uploads/<path:filename>', methods=['GET', 'POST'])def download(filename):# Appending app path to upload folder path within app root folderuploads = os.path.join(current_app.root_path, app.config['UPLOAD_FOLDER'])# Returning file from appended pathreturn send_from_directory(directory=uploads, filename=filename)
This function takes the required file’s name as an argument. It then uses the os
module’s path.join
function to append the Flask app’s root path stored in current_app.root_path
and the upload folder’s path from the root folder stored in app.config['UPLOAD_FOLDER']
.
current_app
is the application context. It can be used wherever an application context has been set up. app.config
is a dictionary that stores a number of variables assigned by Flask itself or by the programmer. The UPLOAD_FOLDER
variable has to be set up by the user.
From the appended path, the function returns the file found by send_from_directory
, which takes the folder path in the first parameter and the file name in the second parameter.
Remember that you need to have access to the file you are downloading.
Free Resources