Use statics in Flask application

If you are working with Flask you already know that the first thing to do to use static in application Flask is to save them in the /static folder.

This way when we are creating templates we will know where these files are located: images, javascript libraries, style sheets,…

First we could reference a static one from a template in the following way:

<img src="/static/images/logo.png"/>

And this code does not have to fail when we run our application Flask. Although it is true that the way the application is configured and deployed may not be under our control. So you can vary the URL where the application is run or rename the directory from the static ones.

So we will have to use the url_for method to obtain the URL in the most correct way.

{{ url_for('static', filename='resource_name') }}"/>

In this way we have the following resource:

/static/images/logo.png

We can reference it as follows:

{{ url_for('static', filename='images/logo.png') }}

And use it within our template in a simple way:

<img src="{{ url_for('static', filename='images/logo.png') }}" /><ยก

With this we have already seen how simple it is to use statics in an application Flask.

Leave a Comment