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

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

我想做的是不必使用 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)

关于python - 如何列出 Flask 静态子目录中的所有图像文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26052561/

相关文章:

python - 获取 n 的所有约数的该算法的运行时间复杂度是多少?

python - _tkinter.Tcl错误: invalid command name ".!treeview"

python - 无法找出使用 apply lambda 在数据帧上实现 if 语句的正确方法

python - python和 Elasticsearch 更新错误

python - 使用 celery 作为模型层

python - python内存错误的解决方法

python - Scrapy Mysql管道如果表没有AUTO_INCRMENT并且没有UNIQUE - 如何分配category_id?

python - 目标 WSGI 脚本 '/opt/python/current/app/application.py' 不包含 WSGI 应用程序 'application'

python - Flask Mysql 连接器问题

python - 从flask调用的sqlite db仅返回变量,而不返回值