How to use Flask to serve static files

Overview of Static Files

Static files are resources that, when viewed by a user, do not alter dynamically in the context of web development. Without any server-side processing, these files are transmitted straight from the server to the client’s browser. Static files, in contrast to dynamic content, don’t require server-side logic or database interaction and stay the same for every request.

An explanation of static files and some examples
Typical static file types are:

  • CSS files: These specify the website’s style and appearance, including the colors, font, and layout. Take style.css as an example.
  • JavaScript files: These enhance client-side functionality and add interactivity. Take app.js as an example.
  • Images: The website’s graphics, which may end in .jpg, .png, .gif, or .svg. For instance, logo.png
  • Fonts: The font files used to style text in a customized way .fontawesome-webfont.woff2 for instance
  • Media Files: Additional media resources, such as audio or video files.

Static files are necessary to build an interactive, aesthetically pleasing, and user-friendly online application with Flask.

The Significance of Serving Static Files in Web Applications

1.Enhancing User Experience: Web pages are designed and function better thanks to static files like CSS and JavaScript, which also make the site more readable, engaging, and responsive.

2.Performance Optimization: Static files can be swiftly served to users because they don’t require server-side processing. Static files can be sent more quickly and server load can be decreased with the right caching and content delivery network (CDN) tactics.

3.Consistency Among Users: Static files don’t change for any user, thus any person who visits the website will see the same functionality, design, and layout. For instance, consistent branding is ensured by applying a stylesheet to every user.

4.Separation of Concerns: Developers can establish distinct boundaries between client-side and server-side operations by keeping static files and dynamic content apart. This division facilitates better maintainability and code organization.

5.Cross-browser compatibility: refers to how an online application works consistently across browsers thanks to static resources like polyfills and fallback fonts.

In general, developing scalable, effective, and user-focused online applications requires the servering of static files.

Configuring Static Files in Flask

With Flask, static files are handled quite easily because it provides an option to do so right out-of-the-box. When you initialize a Flask application, by convention it configures itself to serve static files from a directory named static by default. That’s really helpful because the developer doesn’t have to add extra code or introduce third-party utilities only for serving static content.

Serving Static Files Flask Default Behaviour

Flask serves static files from a folder called static located at the root of your project. Any file placed in this folder is reachable by URL, and Flask will handle the process of delivering them to the client.

For instance, if you had a file called style.css in the static directory, it would be available in the browser at the following URL:

http://localhost:5000/static/style.css

Herein, localhost:5000 is the default URL for Flask’s development server, and /static/ is the default route Flask uses to access static files.

Explanation of the Static Folder and How Flask Uses It

This would contain things like CSS, JavaScript, images, and any other resources that aren’t dynamic when you are creating a Flask project. By default, Flask knows to look in this folder when serving static files.

The folder structure might look like this:

/my_flask_app/
    /static/
        css/
            style.css
        js/
            app.js
        images/
            logo.png
    app.py

In this example:

  • The CSS file style.css is located at /static/css/style.css
  • The JavaScript file app.js can be accessed via /static/js/app.js
  • The image logo.png can be accessed by /static/images/logo.png

Flask makes it very easy to reference static files in your HTML templates by using the url_for() function. That function builds the appropriate URL for static files so that no matter where you deploy your application, your static files are properly linked.

Example usage in an HTML template:

<link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
<script src="{{ url_for('static', filename='js/app.js') }}"></script>
<img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo">

This template code ensures that your static files are properly linked, even if your app is running in a different environment (e.g., production or development).

Serving Static Files in Flask

Serving static files is made easy by Flask as it has provided a default directory and a method to access these static files. We will go through the minimum setup here – creation of the static directory and usage of url_for() function to access the static files.

Basic Setup: Creating the static Directory

To serve static files in Flask, you should create a directory named static in the root of your Flask project. It would contain all the CSS files, all the JavaScript files, images, fonts, and other static assets.

Here’s how the folder structure might look:

/my_flask_app/
    /static/
        css/
            style.css
        js/
            app.js
        images/
            logo.png
    app.py

  • /static/css/style.css: You can write your CSS style here for the web application.
  • /static/js/app.js: This would contain JavaScript for client-side interactions.
  • /static/images/logo.png: This might be an image file for your site’s logo or any type of graphics.

Flask automatically serves files placed in this static directory via the /static/ route. Therefore, it is fairly easy to reach them in the browser.

Serving Static Files with url_for(‘static’, filename=’path_to_file’)

For referencing static files within your HTML templates, you always want to use the url_for() function. This will dynamically create URLs for the static files so they properly link no matter where your application runs – development or production.

Here’s an example of how to access static files using url_for():

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Flask Static Files</title>
    
    <!-- Linking to CSS file -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/style.css') }}">
</head>
<body>

    <!-- Linking to JavaScript file -->
    <script src="{{ url_for('static', filename='js/app.js') }}"></script>

    <!-- Linking to image -->
    <img src="{{ url_for('static', filename='images/logo.png') }}" alt="Logo">

</body>
</html>

In this example:

  • CSS File In this case, the link tag uses url_for(‘static’, filename=’css/style.css’) to point to style.css inside the static/css/ directory.
  • JavaScript File app.js: The script tag utilizes the url_for(‘static’, filename=’js/app.js’) to link the app.js file.
  • Image File: The img tag uses url_for(‘static’, filename=’images/logo.png’) to get the image from static/images/.

The url_for() function makes sure the proper URL for static files is generated in case the application was moved into another environment, perhaps hosted on a different server or a different structure of the URL.

Example Application Code:

from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

  • In this example, the index() function renders an HTML template that references static files using the url_for() function.
  • The static files (e.g., style.css, app.js, logo.png) are automatically served from the /static/ directory when the page is loaded.

Customizing the Static Folder in Flask

Though Flask has used a default directory, which is static, for serving static files, you can change this kind of default behavior for certain project requirements. In Flask, you are allowed to personalize the location of static files by specifying another directory at the time of creating the Flask application.

Changing the Default Static Folder

You can change the default static folder by passing the static_folder parameter when you create your Flask app instance. You’d thereby serve the static files from a different directory than the default static folder.

Here’s how you’d go about changing the default folder for serving static files:

from flask import Flask

# Customizing the static folder
app = Flask(__name__, static_folder='assets')

@app.route('/')
def index():
    return 'Custom static folder example'

if __name__ == '__main__':
    app.run(debug=True)

In this example:

  • The static_folder=’assets’ argument tells Flask to serve static files from a folder named assets instead of the default static folder.
  • You can still access the static files in the assets folder using the /static/ route by default (though the folder itself is named assets).

Example: Serving Static Files from a Custom Directory

Assume you have the directory structure shown below, with your static files kept in the assets directory rather than the static directory:

/my_flask_app/
    /assets/
        css/
            custom_style.css
        js/
            custom_app.js
        images/
            custom_logo.png
    app.py

Here’s how you would configure Flask to serve these static files from the assets directory:

from flask import Flask, render_template, url_for

# Customize static folder to 'assets'
app = Flask(__name__, static_folder='assets')

@app.route('/')
def index():
    return render_template('index.html')

if __name__ == '__main__':
    app.run(debug=True)

In the index.html file, you would still use url_for() to link the static files:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Custom Static Folder</title>

    <!-- Linking to CSS file in 'assets' directory -->
    <link rel="stylesheet" href="{{ url_for('static', filename='css/custom_style.css') }}">
</head>
<body>

    <!-- Linking to JavaScript file in 'assets' directory -->
    <script src="{{ url_for('static', filename='js/custom_app.js') }}"></script>

    <!-- Linking to image in 'assets' directory -->
    <img src="{{ url_for('static', filename='images/custom_logo.png') }}" alt="Custom Logo">

</body>
</html>

In this setup:

  • The custom assets folder is used to serve static files.
  • You still reference these files using url_for(‘static’, filename=’path_to_file’), ensuring consistent linking, regardless of the folder name.

Changing the Static URL Path

By default, Flask serves static files using the /static/ URL path, regardless of the actual folder name. Of course, you can configure it if you prefer a different URL path. For example, you may want to change /static/ to /assets/.

You can achieve this by setting the static_url_path argument:

app = Flask(__name__, static_folder='assets', static_url_path='/assets')

Now, the static files will be served at the /assets/ URL path, matching the folder name. For example:

  • CSS file: /assets/css/custom_style.css
  • JavaScript file: /assets/js/custom_app.js

Key Points:

1.Customizing the static folder: Use the static_folder parameter when initializing the Flask app to specify a custom directory for static files.

2.Custom URL path: Use the static_url_path parameter to change the URL path where static files are accessed.

3.Accessing static files: Continue using url_for(‘static’, filename=’path_to_file’) to ensure proper linking.

This flexibility in the serving of static files has been achieved in such a way that it allows Flask to adapt this functionality of serving static files to best suit the structure and needs of your web application.

Share The Tutorial With Your Friends
Twiter
Facebook
LinkedIn
Email
WhatsApp
Skype
Reddit

Check Our Ebook for This Online Course

Advanced topics are covered in this ebook with many practical examples.