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>

效果图

相关推荐
yzx99101315 分钟前
Gensim 是一个专为 Python 设计的开源库
开发语言·python·开源
麻雀无能为力32 分钟前
python自学笔记2 数据类型
开发语言·笔记·python
Ndmzi36 分钟前
matlab与python问题解析
python·matlab
懒大王爱吃狼41 分钟前
怎么使用python进行PostgreSQL 数据库连接?
数据库·python·postgresql
猫猫村晨总43 分钟前
网络爬虫学习之httpx的使用
爬虫·python·httpx
web1508541593544 分钟前
Python线性回归:从理论到实践的完整指南
python·机器学习·线性回归
ayiya_Oese1 小时前
[训练和优化] 3. 模型优化
人工智能·python·深度学习·神经网络·机器学习
抽风的雨6101 小时前
【python基础知识】Day 27 函数专题2:装饰器
开发语言·python
漫谈网络3 小时前
Python logging模块使用指南
python·logging·日志
言之。3 小时前
Python3 简易DNS服务器实现
python·dns