本文介绍了如何列出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

我想做的就是不必使用os来获取文件,除非有使用flask方法的方法.我知道这种方式仅适用于我的计算机,而不适用于我尝试将其上传到的任何服务器.

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.

推荐答案

Flask应用程序具有属性static_folder,该属性返回静态文件夹的绝对路径.您可以使用它来知道要列出的目录,而不必将其绑定到计算机的特定文件夹结构.要为要在HTML <img/>标记中使用的图像生成一个url,请使用url_for('static',filename ='static_relative_path_to/file')'.

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)

这篇关于如何列出Flask静态子目录中的所有图像文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 12:59