无法在Flask模板中显示来自STATIC_FOLDER的图像 [英] Cannot show image from STATIC_FOLDER in Flask template
问题描述
我为这样的静态文件设置了文件夹
I set folder for static files like this
app.config['STATIC_FOLDER'] = 'tmp'
在模板中,我使用img标签显示存储在/tmp中的图像:
In template i use img tag to show an image stored in /tmp:
<img src='IKE2low.jpg' width="200" height="85">
在萤火虫中,我看到404错误而不是图像.请告诉我我做错了什么?
In firebug i see 404 error instead of image. Please tell me what did i do wrong?
谢谢.
推荐答案
我不确定您正在使用的STATIC_FOLDER
配置项是什么.您在哪里找到的?
I'm not sure what is this STATIC_FOLDER
configuration item you are using. Where did you find it?
Flask
类构造函数实际上有两个参数来控制静态文件的配置:
There are actually two arguments to the Flask
class constructor that govern the configuration of static files:
-
static_folder :默认为静态".这是您必须在URL中使用的前缀才能访问静态文件.
static_folder: defaults to "static". This is the prefix that you have to use in URLs to access the static files.
static_url_path :这是静态文件夹的磁盘位置.默认情况下,该值与static_folder设置相同.
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 /
.
但是执行此操作的最佳方法是不显式引用图像路径,而是使用url_for
生成正确的URL.如果您使用的是Jinja2模板,则将是:
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.
这篇关于无法在Flask模板中显示来自STATIC_FOLDER的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!