OverIQ.com

Serving Static Files in Flask

Last updated on July 27, 2020


Static Files are files which don't change very often, for example, CSS files, JS files, font files etc. By default, Flask looks for static files in the static sub-directory inside the application directory. We can change this default, by passing name of the directory to the static_folder keyword argument while creating application instance as follows:

app = Flask(__name__, static_folder="static_dir")

This will change the default location of static files to static_dir directory inside the application directory.

For now, we will stick to the default static directory. Create a directory names static inside flask_app directory. Inside the static directory create a CSS file style.css with the following content.

flask_app/static/style.css

1
2
3
body {
    color: red
}

Recall that in lesson Flask Basics we had discussed that Flask automatically adds a route of the form /static/<filename> to handle static files. So all we need to serve static files is to create URLs using the url_for() function as follows:

<script src="{{ url_for('static', filename='jquery.js') }}"></script>

Output:

<script src="/static/jquery.js"></script>

Open index.html template and add <link> tag as follows (changes are highlighted):

flask_app/templates/index.html

1
2
3
4
5
6
7
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='style.css') }}">
</head>

Start the server if not already running and visit http://localhost:5000/, you should see the body of the page in red color like this:

The method described here to serve static files is only for development. In production, we use a real web server like Nginx or Apache to serve static files.