Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cannot show image from STATIC_FOLDER in Flask template

Tags:

python

flask

I set folder for static files like this

app.config['STATIC_FOLDER'] = 'tmp'

In template i use img tag to show an image stored in /tmp:

<img src='IKE2low.jpg' width="200" height="85">

In firebug i see 404 error instead of image. Please tell me what did i do wrong?

Thanks in advance.

like image 516
Aleksei Yerokhin Avatar asked Jul 20 '13 16:07

Aleksei Yerokhin


1 Answers

I'm not sure what is this STATIC_FOLDER configuration item you are using. Where did you find it?

There are actually two arguments to the Flask class constructor that govern the configuration of static files:

  • static_folder: defaults to "static". This is the prefix that you have to use in URLs to access the static files.

  • static_url_path: this is the disk location of the static folder. By default this value is the same as the static_folder setting.

For example, if you use this configuration:

from flask import Flask
app = Flask(__name__, static_url_path = "/tmp", static_folder = "tmp")

Then you can access your images as follows:

<img src='/tmp/IKE2low.jpg' width="200" height="85">

You can also remove the need to have a prefix in the URLs as follows:

from flask import Flask
app = Flask(__name__, static_url_path = "", static_folder = "tmp")

And then you can access your images as:

<img src='/IKE2low.jpg' width="200" height="85">

Note that you still need to have a root /.

But the best way to do this is to not reference image paths explicitly and instead use url_for to generate the correct URLs. If you are using Jinja2 templates that would be:

<img src="{{ url_for('static', filename = 'IKE2low.jpg') }}" width="200" height="85">

This last expression would work regardless of where and how the static files are configured.

like image 55
Miguel Avatar answered Nov 06 '22 18:11

Miguel