[MRIQC 3-1] Opening an HTML file using Flask
21 May 2024 #bio #brainImaging
MRIQC analyzes and evaluates the quality of MRI images and outputs a report as an HTML file. To view the HTML file, I used Flask. Here is a summary of the method I used.
Flask
Flask is a micro web framework written in Python. With its lightweight and flexible structure, it helps you quickly develop simple web applications and API servers. Since it includes only basic features, it is highly extensible, allowing you to add various plugins and extension modules as needed. It also has an easy-to-learn and intuitive code structure, making it suitable for beginners. However, because it comes with minimal features, you need to use external libraries to add complex functionalities, and maintaining the project can become challenging as the project size grows.
Opening an HTML file using Flask
Installing Flask
You can install it via PyPI:
pip install Flask
‘static/’ and ‘templates/’
Flask requires two folders, static/
and templates/
. static/
stores static files such as images, CSS, and JavaScript that exist in or are applied to HTML files. templates/
stores the HTML files to be rendered.
Let me explain the process of opening an MRIQC report as an example. After creating these two folders in your project folder, save the static files and the HTML file you want to open in each respective folder:
If the file path stored in the HTML file under static/
already exists, it will be updated to the new path. When opening the MRIQC report HTML file, you’ll find that image files are specified with relative paths. Since the images have been moved to the static/
directory, the paths will be changed to absolute paths accordingly:
Writing execution code
And then, write the code to render the HTML file. Here is the code I used in main.py
:
from flask import *
app = Flask(__name__)
@app.route("/")
def test():
return render_template("sub-001_ses-001_T1w.html")
app.run("0.0.0.0", port=5001)
app = Flask(__name__)
: Creates an instance of a Flask application.__name__
refers to the name of the current module and is used by Flask to locate resources for the application.@app.route("/")
: A decorator that instructs Flask to call the test function for the root URL (/).test()
: The function that will be executed when the root URL is requestedreturn render_template("HTML_FILE_NAME.html")
: Renders and returns the HTML file located in thetemplates/
directory.app.run("0.0.0.0", port=5001)
: Runs the application on address 0.0.0.0 and port 5001.
Result
When you visit the specified address, you will see that the HTML file is displayed correctly.