pythonflask

How to list all image files in Flask static subdirectory?


def get_path():
    imgs = []

    for img in os.listdir('/Users/MYUSERNAME/Desktop/app/static/imgs/'):
        imgs.append(img)
    image = random.randint(0, len(imgs)-1) #gen random image path from images in directory
    return imgs[image].split(".")[0] #get filename without extension

@app.route("/blahblah")
def show_blah():
    img = get_path()
    return render_template('blahblah.html', img=img) #template just shows image

What I want to do is not have to get the files using os unless there is a way to do it using flask methods. I know this way will only work with my computer and not any server I try and upload it on.


Solution

  • The Flask app has a property static_folder that returns the absolute path to the static folder. You can use this to know what directory to list without tying it to your computer's specific folder structure. To generate a url for the image to be used in an HTML <img/> tag, use url_for('static', filename='static_relative_path_to/file').

    import os
    from random import choice
    from flask import url_for, render_template
    
    
    @app.route('/random_image')
    def random_image():
        names = os.listdir(os.path.join(app.static_folder, 'imgs'))
        img_url = url_for('static', filename=os.path.join('imgs', choice(names)))
        
        return render_template('random_image.html', img_url=img_url)