Python+Layui实现树状文件目录

具体要求

展示文件树状结构,普通文件在前,文件夹在后,文件夹没有内容则不可点击

技术支持

Python flask

Lauyi树形组件

Python 代码

#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#a test for traverse directory

from flask import Flask,request
import json
import os
import os.path

def dfs_showdir(path):
    # 定义两个数组 分别存文件夹和普通文件  普通文件在前 文件夹在后
    a = [];
    c = [];

    # 遍历根目录
    for item in os.listdir(path):
        b = {};
        b['title'] = item;

        newitem = path +'/'+ item;
        if os.path.isdir(newitem):
            b['children'] = dfs_showdir(newitem); # 获取子节点

        # 区分文件和普通文件
        if 'children' in b.keys():
            if b['children'] == []:
                b['disabled'] = 'true'; # 子节点为空不可点击
            a.append(b);
        else:
            c.append(b);

    return c + a

app = Flask(__name__)

# 只接受get方法访问
@app.route("/", methods=["GET"])
def main():
    get_data = request.args.to_dict()
    path = get_data.get('path')

    return json.dumps(dfs_showdir(path), ensure_ascii=False), 200, [('Access-Control-Allow-Origin', '*')]

if __name__ == "__main__":
    app.run(host="0.0.0.0", debug=True)

HTML代码

<link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css"  media="all">

<fieldset class="layui-elem-field layui-field-title" style="margin-top: 30px;">
    <legend>常规用法</legend>
</fieldset>

<div id="test1" class="demo-tree demo-tree-box"></div>
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<script src="https://www.layuicdn.com/layui/layui.js" charset="utf-8"></script>

<script>
        layui.use(['tree'], function() {
            var tree = layui.tree
            // 请求后端接口
            $.get('http://192.168.222.128:5000?path=./aaaa', function (res) {
            	// 组件初始化
                tree.render({
                    elem: '#test1',
                    data: res
                });
            },'json');
        })
</script>

目录结构及实现效果

在这里插入图片描述
在这里插入图片描述

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 4
    评论
评论 4
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值