Python 无法在 Flask 模板中显示来自 STATIC_FOLDER 的图像

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17764156/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 09:08:28  来源:igfitidea点击:

Cannot show image from STATIC_FOLDER in Flask template

pythonflask

提问by Nervosa

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 标签来显示存储在 /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?

在萤火虫中,我看到 404 错误而不是图像。请告诉我我做错了什么?

Thanks in advance.

提前致谢。

采纳答案by Miguel

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

我不确定STATIC_FOLDER您使用的这个配置项是什么。你在哪里找到它?

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

Flask类构造函数实际上有两个参数来管理静态文件的配置:

  • 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.

  • static_folder:默认为“静态”。这是您必须在 URL 中使用以访问静态文件的前缀。

  • static_url_path:这是静态文件夹的磁盘位置。默认情况下,此值与 static_folder 设置相同。

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:

您还可以取消在 URL 中使用前缀的需要,如下所示:

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 /.

请注意,您仍然需要有一个 root /

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

但最好的方法是不显式引用图像路径,而是使用url_for生成正确的 URL。如果您使用的是 Jinja2 模板,则:

<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.

无论静态文件的配置位置和方式如何,最后一个表达式都可以使用。