Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages

Flask Static Files – Implementation of Static Files in Python Flask

Flask Static Files

Hola Coders! This article is all about Flask static files and its implementation. So let’s get started!

The need for Static Files in Flask

You would have observed that almost all the websites consist of photos, Background colors, and many other beautification elements.

Airbnb Website Example
Airbnb webstite Example

This aesthetic nature of websites is achieved by using static files, which comprise of Images, CSS files, and JS scripts. 

We save these static files in a separate folder called static located beside our main Flask application. 


Now that we have some knowledge about static files let’s see implement them.

Hands-on with Flask Static Files

We will now display a background static file image on our webpage using Flask.

1. Coding our Main application

Consider the following Flask application code

from flask import Flask,render_template

app = Flask(__name__)

def blog():
    return render_template('blog.html')'localhost', port=5000)

Here we are rendering an HTML template using the render_template function.

If you get any trouble understanding the application syntax, check out our Introduction to Flask article for better understanding.

2. Coding our Templates

Here we use the special URL attribute to specify the Static File location.

<img src = "{{ url_for('static',filename="<filename>") }}>

The url_for attribute pulls out the path of the file located inside the static folder.

You can download the below image for this demonstration and save it in the static folder.


Now create a “blog.html” Template File and add the below code in it:

        <img src= "{{ url_for('static',filename='blog.jpg') }}">
        <h2>This is a blog website</h2>

Do checkout our Flask Templates article to know more about rendering Templates in Flask

3. Implementation of the Code

That’s it; let us now run the server and check our web page

Static Website
Static Website

Perfect !!


That’s it for this tutorial, guys! I hope the article helped you improve your knowledge of Static Files in Flask. Do check out our Flask Template article to learn more about Templates.

See you in the next article! Till then, Happy coding!!