2023.11.19使用flask制作一个文件夹生成器

2023.11.19使用flask制作一个文件夹生成器

实现功能:

(1)在指定路径上建立文件夹

(2)返回文件夹的路径和建立成功与否的提示

main.py

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

app = Flask(__name__)

@app.route('/')
def index():
    return render_template('index.html')


@app.route('/create_folder', methods=['POST'])
def create_folder():
    folder_name = request.json['folder_name'] # 获取前端传递的文件夹名称

    # 指定路径和文件夹名称
    base_path = 'static'  # 替换为实际的路径
    folder_path = os.path.join(base_path, folder_name)

    try:
        os.makedirs(folder_path)  # 在指定路径创建文件夹
        response = {
            'message': '文件夹创建成功',
            'folder_path': folder_path
        }
        return jsonify(response)
    except Exception as e:
        response = {
            'message': '文件夹创建失败',
            'error': str(e)
        }
        return jsonify(response), 500

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

index.html

复制代码
<!DOCTYPE html>
<html>
<head>
    <title>创建文件夹</title>
</head>
<body>
    <h2>创建文件夹</h2>
    <input type="text" id="folderName" placeholder="请输入文件夹名称">
    <button onclick="createFolder()">创建</button>
    <p id="response"></p>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script>
        function createFolder() {
            var folderName = $('#folderName').val();

            $.ajax({
                url: '/create_folder',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify({ 'folder_name': folderName }),
                success: function(response) {
                    $('#response').text(response.message + ',路径为:' + response.folder_path);
                },
                error: function(xhr, status, error) {
                    var errorMessage = xhr.responseText ? JSON.parse(xhr.responseText).message : '请求失败';
                    $('#response').text('错误:' + errorMessage);
                }
            });
        }
    </script>
</body>
</html>
相关推荐
threerocks1 小时前
什么?我连 A2A、MCP 都没学会,现在又来了 AG-UI、A2UI.
前端·aigc·ai编程
牛奶2 小时前
如何自己写一个浏览器插件?
前端·chrome·浏览器
亿元程序员2 小时前
为什么Cocos都4.0了还有人用2.x?
前端
MomentYY3 小时前
AI 到底是“懂”,还是在“猜”?
前端·人工智能·ai编程
鹏毓网络科技3 小时前
Cursor Rules 文件配置实战:3 个隐藏参数让我每月少写 40% 样板代码
前端·github
没烦恼3013 小时前
无痕模式下 HTTP\-First 拦截引发的“页面刷新”误判
前端
文心快码BaiduComate3 小时前
从个人提效到组织提效:Comate辅助构建自我进化的AI研发系统
前端·程序员
掘金者阿豪3 小时前
高可用读写分离实战(二):我把数据库主库停了,结果整个集群的反应和我想象的不一样
后端
掘金者阿豪3 小时前
《高可用读写分离集群实战》系列(一)
后端