![]() |
VOOZH | about |
Flask uses a dedicated static directory to serve files that do not change dynamically, such as stylesheets, JavaScript code, images, videos, and other media assets. These files can be linked directly from templates and are automatically made available by the Flask application. This guide will show how to serve different types of static files in a Flask web application efficiently.
To serve HTML files in Flask, just create a templates folder in the project root and add your HTML files (e.g., templates/index.html). Using Jinja ({{ message }}), you can display text stored in a variable.
In main.py, we use Flask's render_template() function to render the HTML file when the app runs. The final code looks like this:
Output:
The Flask is up and running on localhost port http://127.0.0.1:5000/
Now serving a CSS file is the same as an HTML file but instead of /templates folder, we create a static folder in the root directory and add all CSS files to it, For simplicity, we have used a very simple CSS file.
Now, let us link it with the HTML template file using the link tag referring to the CSS file in the static folder.
Output:
To serve Javascript it is the same as a CSS file create a javascript file in the static folder.
Now link it with the HTML and run the Flask app.
Output:
Flask can also serve media files like images, videos, audio, text files, and PDFs using the static folder. Just like CSS and JavaScript, media files are stored in static/ and linked to HTML files.
Steps to Serve Media Files:
Create an image.html file in the templates folder and add the following code to the main.py and image.html respectively.
Output:
To serve a video file, create a video.html file in your templates folder and add the following code to your main.py and video.html files.
templates/video.html
As you see the mp4 video file is been served by Flask over localhost.
Output:
Respectively an audio file can be served by creating an audio.html template file and adding the following code to the main.py.
Output:
In addition to media files, Flask can serve documents such as PDF and text files directly from the static directory. These files can be linked in HTML using the url_for() function, allowing users to view or download them.
1. Serving a PDF File
Place a PDF file inside the static folder and add the following link to an HTML template:
2. Serving a Text File
Similarly, a text file stored in the static directory can be accessed using:
Explanation:
For simplicity, we have created a simple Flask application for a better understanding of how to serve static files in Flask.
Let's test the Flask app by running it, to run the app just run the python main.py which will serve output as shown above: