Flask网页找不到图像文件

时间:2017-03-11 04:32:55

标签: python image flask

在Raspberry Pi上,我编写了一个简单的Flask应用程序,它在网页上显示服务器的当前日期和时间。那部分效果很好。 该页面还应显示图像。那部分不起作用。图像存储在app文件夹下的照片文件夹中:Web_Test / photos。 我使用存储在静态文件夹中的css文件,效果很好。 我使用url_for创建图像的URL:

<p><img src="{{url_for('photos', filename='image1.jpg')}}"></p>

由于照片不是url_for命令的已知端点,因此我使用:app.add_url_rule('/photos/<path:filename>', view_func=app.send_static_file)将照片文件夹添加为端点。 每次我从Web浏览器访问网页时,我运行python(python3 photo.py)的命令窗口都会显示GET /photos/image1/jpg HTTP/1.1" 404。 没有特定的错误,也没有图像。 我已经阅读了很多关于这个问题的帖子,但没有任何帮助。 这是我的photo.py代码:

from flask import Flask, render_template
import datetime
app = Flask(__name__)

app.add_url_rule('/photos/<path:filename>', endpoint='photos', view_func=app.send_static_file)
@app.route('/')
def photo():
    now = datetime.datetime.now()
    timeString = now.strftime("%Y-%m-%d %H:%M")
    templateData = {
        'title' : 'Latest Photo',
        'time' : timeString
        }
    return render_template('photo1.html', **templateData)

if __name__ == '__main__':
    app.run(debug=True, host='0.0.0.0', port=80)

这是我的photo1.html代码:

<!DOCTYPE html>
  <head>
    <link rel="stylesheet" href='/static/style.css' />
    <title>{{title}}</title>
  </head>

  <body>
    <h1>Latest Photo</h1>
    <h2>Current date and time: {{time}}</h2>
    <p> <img src="{{url_for('photos', filename='image1.jpg')}}"></p>
  </body>
</html>

任何想法或建议都将不胜感激。 谢谢!

2 个答案:

答案 0 :(得分:2)

当前编写程序的方式,如果您重新组织项目布局,图像将可见:

project
├── app.py
├── static
│   └── image1.jpg
└── templates
    └── photo1.html

您希望使用send_static_file显示照片这一事实表明照片是静态资源。如果是这样,那么最好:

1)将image1.jpg移至static/photos/image1.jpg

2)更改模板如下:

<p> <img src="{{url_for('static', filename='photos/image1.jpg')}}"></p>

3)将app.add_url_rule('/photos/<path:filename>', ...)放入app.py

答案 1 :(得分:0)

我刚刚在项目文件夹中创建了一个名为“static”的文件夹并将我的图像移到该文件夹​​中,我的问题得到了解决。

app.py
static
   |----image.jpg
templates
   |----index.html

并像这样更改index.html文件:

<img src="/static/image.jpg">