In the last tutorial, we learned about rendering HTML in Flask. Continuing the series, in this tutorial we are going to learn how to serve static files such as images, files etc in Flask.
To serve static files, first, create a folder and store your static files in it, such as images, CSS and JavaScript files.
We are going to use url_for() function to serve static content.
About url_for() function
url_for() function in Flask allows us to create a absolute URL of resources. It takes two parameters:
1: Endpoint
2: Values
For example:
This will generate the path by using the file name present in the static folder.
Here is the sample code to serve the static file using the url_for() function in Flask.
Note: You should have a file present in the folder called static.
Here is the Flask Server code.
app = Flask(__name__)
@app.route('/')
def home():
return render_template('home.html')
if __name__ == '__main__':
app.run()
Now, run the Flask.
Navigate your browser to localhost:5000 to view the static file.
You can use the same code to serve CSS files like this:
In the next tutorial, we will learn about dynamic templating in Flask.