Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do I load image in python flask? [duplicate]

so.... I'm a beginner in python flask trying to make a dashboard.

I have a folder where my uploaded pictures are located.

structure:

manage.py  # this is where I run the program.
src
    |--pic
        |--items
            |-- pic_here.jpg

how should I set up so I could load the picture and get it into <img>?

I tried searching but all they showed was how to set up static folders. I don't think this is one for static, the pictures are what I upload via dashboard.

in other words, src/pic/items is where my saved images are located and how do I set my flask to load this picture?

like image 899
sol-invictii Avatar asked Nov 27 '25 04:11

sol-invictii


2 Answers

When you create a 'static' folder, you can use url_for in jinja to load your pictures in html.

Put your pictures in: /app_homedirectory/static/PictureName.jpg

Then you can load your pictures in html with: <img src={{ url_for('static', filename='PictureName.jpg') }}>

This works out of the box, you just need to create a folder named 'static' and flask will recognize it.

add from flask import url_for to the file that contains the view of your rendered html document.

like image 148
Joost Barendregt Avatar answered Nov 28 '25 20:11

Joost Barendregt


What i would advise is to create a view that serves the image (a simple API).

app = Flask(__name__, upload_folder='upload') 

@app.route('/img/<path:filename>') 
def send_file(filename): 
    return send_from_directory(app.upload_folder, filename)

This should get the job done, but you can check this question for more.

like image 37
booluw Avatar answered Nov 28 '25 19:11

booluw



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!