flask在哪里寻找图像文件? [英] Where does flask look for image files?

查看:99
本文介绍了flask在哪里寻找图像文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用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')

推荐答案

图像文件是否在您的static目录中的ayrton_senna_movie_wallpaper_by_bashgfx-d4cm6x6.jpg?如果将其移动到静态目录并按如下方式更新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()

templates/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆