Serving Static Files in Flask
Let’s configure the virtual environment first. Although this step is optional, we always recommend using a dedicated development environment for each project. This can be achieved in a Python virtual environment.
Now that we have created our Flask app, let’s see how to serve static files using the Flask app we just created. First, static files are files served by a web server and do not change over time like CSS and Javascript files used in web applications to improve user experience. Below you will find a demonstration of various static files served by the Flask app.
File Structure
HTML File
Serving HTML files using Flask is fairly simple just create a templates folder in the project root directory and create the HTML files, as templates/index.html. Here, we are passing text, and with the help of Jinja {{message}}, we are printing text that is present in the variable.
HTML
< html > < head > < title >Flask Static Demo</ title > </ head > < body > < h1 >{{message}}</ h1 > </ body > </ html > |
main.py
In main.py we render the HTML file when we run it, we are using the render_template() function provided by Flask to render the HTML file. The final code looks like this:
Python3
from flask import Flask from flask import render_template # creates a Flask application app = Flask(__name__) @app .route( "/" ) def hello(): message = "Hello, World" return render_template( 'index.html' , message = message) # run the application if __name__ = = "__main__" : app.run(debug = True ) |
Output:
The Flask is up and running on localhost port http://127.0.0.1:5000/
Serve CSS file in Flask
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.
CSS
h 1 { color : red ; font-size : 36px ; } |
Now, let us link it with the HTML template file using the link tag referring to the CSS file in the static folder.
HTML
< html > < head > < title >Flask Static Demo</ title > < link rel = "stylesheet" href = "/static/style.css" /> </ head > < body > < h1 >{{message}}</ h1 > </ body > </ html > |
Output:
Serve JavaScript file in Flask
To serve Javascript it is the same as a CSS file create a javascript file in the static folder.
Javascript
document.write( "This is a Javascript static file" ) |
Now link it with the HTML and run the Flask app.
HTML
< html > < head > < title >Flask Static Demo</ title > < link rel = "stylesheet" href = "/static/style.css" /> </ head > < body > < h1 >{{message}}</ h1 > < script src = "/static/serve.js" charset = "utf-8" ></ script > </ body > </ html > |
Output: