Skip to main content
 首页 » 编程设计

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

2024年10月25日9TianFang

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 

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

请您参考如下方法:

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