Flask 在哪里寻找图像文件? [英] Where does flask look for image files?
问题描述
我正在使用 Flask 设置本地服务器.我目前想要做的就是在 index.html 页面中使用 img 标签显示图像.但我不断收到错误
I am setting up a local server using flask. All I want to do currently is display an image using the img tag in the index.html page. But I keep getting error
GET http://localhost:5000/
ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg 404 (NOT FOUND)
flask 在哪里查找文件?一点帮助会很棒.我的 HTML 代码是
Where does flask look for files? A Little help would be great. My HTML code is
<html>
<head>
</head>
<body>
<h1>Hi Lionel Messi</h1>
<img src= "ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg ">
</body>
</html>
我的python代码是:
My python code is :
@app.route('/index', methods=['GET', 'POST'])
def lionel():
return app.send_static_file('index.html')
推荐答案
图像文件 ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
是否在您的 static
目录中?如果你将它移动到你的静态目录并更新你的 HTML:
Is the image file ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
in your static
directory? If you move it to your static directory and update your HTML as such:
<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">
它应该可以工作.
另外,值得注意的是,有一种更好的方法来构造它.
Also, it is worth noting, there is a better way to structure this.
文件结构:
app.py
static
|----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
|----index.html
app.py
from flask import Flask, render_template, url_for
app = Flask(__name__)
@app.route('/index', methods=['GET', 'POST'])
def lionel():
return render_template('index.html')
if __name__ == '__main__':
app.run()
模板/index.html
templates/index.html
<html>
<head>
</head>
<body>
<h1>Hi Lionel Messi</h1>
<img src="{{url_for('static', filename='ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg')}}" />
</body>
</html>
这样做可确保您不会对静态资产的 URL 路径进行硬编码.
Doing it this way ensures that you are not hard-coding a URL path for your static assets.
这篇关于Flask 在哪里寻找图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!