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

时间:2014-09-26 05:21:05

标签: 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

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

1 个答案:

答案 0 :(得分:2)

Flask应用程序有一个属性static_folder,它返回静态文件夹的绝对路径。您可以使用它来了解要列出的目录,而不必将其绑定到计算机的特定文件夹结构。要为要在HTML <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)
相关问题