Flask 页面展示文件目录及文件,通过勾选复习框删除

(45条消息) flask 读取文件夹文件,展示在页面,可以通过勾选删除_U盘失踪了的博客-CSDN博客

基本实现

针对上面的功能再优化

项目结构 

Flask 页面展示文件目录及文件,通过勾选复习框删除_第1张图片

app.py

import os
import shutil
from flask import Flask, render_template, request, redirect, url_for

app = Flask(__name__)

def generate_file_tree(path):
    root = {
        'name': os.path.basename(path),
        'type': 'directory',
        'children': []
    }
    for item in os.listdir(path):
        item_path = os.path.join(path, item)
        if os.path.isdir(item_path):
            child = generate_file_tree(item_path)
        else:
            child = {
                'name': item,
                'type': 'file'
            }
        root['children'].append(child)
    return root

def delete_selected_files_and_dirs(path, file_tree):
    selected_files = request.form.getlist('file-checkbox')
    for item in file_tree['children']:
        item_path = os.path.join(path, item['name'])
        if item['type'] == 'file':
            if item['name'] in selected_files:
                os.remove(item_path)
        elif item['type'] == 'directory':
            if item['name'] in selected_files:
                shutil.rmtree(item_path)
            else:
                delete_selected_files_and_dirs(item_path, item)

@app.route('/', methods=['GET', 'POST'])
def index():
    if not os.path.isdir('testfile'):
        os.makedirs('testfile')
    file_tree = generate_file_tree('testfile')
    if request.method == 'POST':
        delete_selected_files_and_dirs('testfile', file_tree)
        return redirect(url_for('index'))  # 重定向到相同的URL
    return render_template('index.html', file_tree=file_tree)

if __name__ == '__main__':
    app.run()

 templates / index.html




    File Manager
    


    

File Manager

    {% for item in file_tree['children'] %} {% if item['type'] == 'directory' %}
    • {% for child in item['children'] %} {% if child['type'] == 'file' %}
    • {% endif %} {% endfor %}
  • {% endif %} {% endfor %}

效果图

Flask 页面展示文件目录及文件,通过勾选复习框删除_第2张图片

 Flask 页面展示文件目录及文件,通过勾选复习框删除_第3张图片

优化一

目录折叠/展开文件




    File Manager
    
    


    

File Manager

    {% for item in file_tree['children'] %} {% if item['type'] == 'directory' %}
    • {% for child in item['children'] %} {% if child['type'] == 'file' %}
    • {% endif %} {% endfor %}
  • {% endif %} {% endfor %}

Flask 页面展示文件目录及文件,通过勾选复习框删除_第4张图片

优化二

隐藏目录的复选框




    File Manager
    
    


    

File Manager

    {% for item in file_tree['children'] %} {% if item['type'] == 'directory' %}
    • {% for child in item['children'] %} {% if child['type'] == 'file' %}
    • {% endif %} {% endfor %}
  • {% endif %} {% endfor %}

Flask 页面展示文件目录及文件,通过勾选复习框删除_第5张图片

 

你可能感兴趣的:(#,Flask,flask,python)