我正在用烧瓶建立一个本地服务器。我目前要做的就是在index.html页面中使用img标记显示图像。但是我一直得到错误
GET http://localhost:5000/
ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg 404 (NOT FOUND) 烧瓶在哪里找文件?帮个忙就好了。我的HTML代码是
<html>
<head>
</head>
<body>
<h1>Hi Lionel Messi</h1>
<img src= "ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg ">
</body>
</html>我的python代码是:
@app.route('/index', methods=['GET', 'POST'])
def lionel():
return app.send_static_file('index.html')发布于 2015-01-29 06:22:04
图像文件ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg在static目录中吗?如果将其移动到静态目录并按如下方式更新HTML:
<img src="/static/ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg">应该管用的。
此外,值得注意的是,有一种更好的方法来构建这个结构。
档案结构:
app.py
static
|----ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg
templates
|----index.htmlapp.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
<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路径。
发布于 2015-01-29 06:29:25
在图像实际存在的情况下使用绝对路径(例如)‘/home/artitra/图片/filename.jpg’
或者在项目目录中创建静态文件夹,如下所示
| templates
- static/
- images/
- yourimagename.jpg那就这么做
app = Flask(__name__, static_url_path='/static')然后,您可以在index.html中这样访问您的图像。
src ="/static/images/yourimage.jpg" 在img标签中
发布于 2017-03-18 16:12:59
我也花了一段时间才弄明白。url_for中的routes.py查找您在routes.py脚本中指定的端点。
因此,如果您的routes.py文件中有一个像@blah.route('/folder.subfolder')这样的装饰器,那么Flask将识别命令{{ url_for('folder.subfolder') , filename = "some_image.jpg" }}。'folder.subfolder'参数将其发送到它识别的一个Flask端点。
但是,假设您将映像文件some_image.jpg存储在您的子文件夹中,但没有将该子文件夹指定为您的烧瓶routes.py中的路由端点,则您的路由装饰器看起来类似于@blah.routes('/folder')。然后,您必须这样要求您的图像文件:{{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}
也就是说,您告诉Flask转到它知道的端点“文件夹”,然后通过在文件名参数中放置子目录路径来引导它。
https://stackoverflow.com/questions/28207761
复制相似问题