Serving Static FIles in Flask

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:

url_for('static', filename = 'name_of_file')

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.

<h1>Welcome to the HomePage!</h1>
<img src= "{{url_for('static', filename='1.jpg')}}">

Note: You should have a file present in the folder called static.

Here is the Flask Server code.

from flask import Flask, render_template
app = Flask(__name__)

@app.route('/')
def home():
   return render_template('home.html')
if __name__ == '__main__':
   app.run()

Now, run the Flask.

flask run

Navigate your browser to localhost:5000 to view the static file.

You can use the same code to serve CSS files like this:

<link rel="stylesheet" href="{{url_for('static', filename='borders.css')}}" />

In the next tutorial, we will learn about dynamic templating in Flask.

Pankaj Kumar
Pankaj Kumar
Articles: 208