Flask 创建文件目录,删除文件目录

项目结构

app.py

复制代码
from flask import Flask, render_template, request, redirect, url_for
import os

app = Flask(__name__)
BASE_DIR = os.path.abspath(os.path.dirname(__file__))
FILE_DIR = os.path.join(BASE_DIR, 'testfile')


@app.route('/', methods=['GET', 'POST'])
def index():

    if request.method == 'POST':
        if 'create' in request.form:
            dirname = request.form.get('dirname')
            os.mkdir(os.path.join(FILE_DIR, dirname))
        elif 'delete' in request.form:
            dirname = request.form.get('dirname')
            os.rmdir(os.path.join(FILE_DIR, dirname))
        return redirect(url_for('index'))

    directories = os.listdir(FILE_DIR)
    return render_template('index.html', directories=directories)

if __name__ == '__main__':
    if not os.path.isdir('testfile'):
        os.makedirs('testfile')
    app.run(debug=True)

templates / index.html

复制代码
<!DOCTYPE html>
<html>
<head>
    <title>File Manager</title>
</head>
<body>
    <h1>File Manager</h1>
    <form method="POST">
        <input type="text" name="dirname" placeholder="Directory Name">
        <input type="submit" name="create" value="Create Directory">
        <input type="submit" name="delete" value="Delete Directory">
    </form>
    <ul>
        {% for directory in directories %}
            <li>{{ directory }}</li>
        {% endfor %}
    </ul>
</body>
</html>

效果图

相关推荐
飞Link3 小时前
什么是 AirSim?一文读懂无人机仿真平台
python·算法·无人机
曲径海盗3 小时前
【Python 学习第 38 天】for 循环
python·学习笔记·编程入门
在世修行4 小时前
智学文枢:变式题生成引擎
python·ai·pyside·题目生成
On The Road :6 小时前
Java 多线程详解:从入门到线程安全
java·python·安全
岁月宁静6 小时前
如何设计支持 Skills 的 Agent?一套可扩展的四层架构
python·agent
岁月宁静6 小时前
CrewAI 快速上手:10 分钟搭建你的第一个 Agent 团队
python·agent
曲径海盗6 小时前
【Python 学习第 40 天】for 循环
python·学习笔记·编程入门
专注仿真7 小时前
知识问答大模型-rag算法详解
人工智能·python·控制算法
染指11107 小时前
158.Agent-LangGraph-子图(共享状态和不共享状态模式)
开发语言·人工智能·python·ui·agent·agents
云和数据.ChenGuang9 小时前
Python 常见特殊方法详解:__new__、__init__、__del__、__str__、__repr__ 与 __getattribute__
开发语言·人工智能·python·1024程序员节