Serving image with flask

15,562

Are you sure the image is indeed in the location ./, i.e. in the root of your project? In any case, it is better to use Flask's url_for() method to determine URLs (see http://flask.pocoo.org/docs/api/#flask.url_for) This makes sure that when you move things around, the URLs don't break.

Share:
15,562
Shan-x
Author by

Shan-x

Updated on June 17, 2022

Comments

  • Shan-x
    Shan-x almost 2 years

    I have a program which generates an image. Now I want to use Flask to make this picture accessible to other users, but I can’t display this image with the following code:

    #!/usr/bin/python2
    #coding: utf-8
    
    from flask import *
    app = Flask(__name__)
    
    #app.run(host='0.0.0.0')
    
    @app.route('/')
    def index():
        return render_template('hello.html')
    
    if __name__ == '__main__':
        app.run(debug=True,host='0.0.0.0')
    

    My template hello.html is:

    <!doctype html>
    <title>Hello from Flask</title>
    <h1>Hello World!</h1>
    <img src="./weather-plot.png">
    

    When I run this program and visit the page, I see this:

    192.168.0.61 - - [10/Jul/2013 10:22:09] "GET / HTTP/1.1" 200 -
    192.168.0.61 - - [10/Jul/2013 10:22:09] "GET /weather-plot.png HTTP/1.1" 200 -
    

    And in my browser I see the title, but not the picture. What’s wrong?

    By the way, is there a better method to display a picture without anything else? Maybe I don’t have to use a template?