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)
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>
My python code is :
@app.route('/index', methods=['GET', 'POST'])
def lionel():
return app.send_static_file('index.html')
use absolute path where the image actually exists (e.g) '/home/artitra/pictures/filename.jpg'
or create static folder inside your project directory like this
then do this
then you can access your image like this in index.html
in img tag
It took me a while to figure this out too.
url_for
in Flask looks for endpoints that you specified in theroutes.py
script.So if you have a decorator in your
routes.py
file like@blah.route('/folder.subfolder')
then Flask will recognize the command{{ url_for('folder.subfolder') , filename = "some_image.jpg" }}
. The'folder.subfolder'
argument sends it to a Flask endpoint it recognizes.However let us say that you stored your image file,
some_image.jpg
, in your subfolder, BUT did not specify this subfolder as a route endpoint in your flaskroutes.py
, your route decorator looks like@blah.routes('/folder')
. You then have to ask for your image file this way:{{ url_for('folder'), filename = 'subfolder/some_image.jpg' }}
I.E. you tell Flask to go to the endpoint it knows, "folder", then direct it from there by putting the subdirectory path in the filename argument.
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:It should work.
Also, it is worth noting, there is a better way to structure this.
File structure:
app.py
templates/index.html
Doing it this way ensures that you are not hard-coding a URL path for your static assets.
From the documentation: