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')
The standard directory for storing static resources such as images, css, javascript files into Flask application is to put under static directory.
To display image on a HTML page with Python Flask, we can pass the image path to the template from the view. Then we call render_template with the template file name, and the user_image argument set to the image path. to interpolate the user_image in the template.
Static files in Flask have a special route. All application URLs that begin with "/static", by convention, are served from a folder located at "/static" inside your application's root folder.
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">
It should work.
Also, it is worth noting, there is a better way to structure this.
File structure:
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
<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>
Doing it this way ensures that you are not hard-coding a URL path for your static assets.
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
| templates - static/ - images/ - yourimagename.jpg
then do this
app = Flask(__name__, static_url_path='/static')
then you can access your image like this in index.html
src ="/static/images/yourimage.jpg"
in img tag
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With