如何列出Flask静态子目录中的所有图像文件?

use*_*369 5 python flask

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
Run Code Online (Sandbox Code Playgroud)

我想做的是不必使用操作系统获取文件,除非有办法使用 Flask 方法来获取文件。我知道这种方式仅适用于我的计算机,不适用于我尝试上传的任何服务器。

dav*_*ism 8

Flask 应用程序有一个属性static_folder,可以返回静态文件夹的绝对路径。您可以使用它来了解要列出的目录,而无需将其与计算机的特定文件夹结构联系起来。要生成要在 HTML 标记中使用的图像的 url <img/>,请使用“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)
Run Code Online (Sandbox Code Playgroud)