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>
相关推荐
Python私教11 分钟前
Rust基本语法
后端
Python私教12 分钟前
Rust环境搭建
后端
jakeswang15 分钟前
ServletLess架构简介
java·后端·servletless
nn_(nana)16 分钟前
修改文件权限--- chmod ,vi/vim,查看文件内容,yum-软件包管理器,systemctl管理系统服务
前端
Mr_Dwj43 分钟前
【Python】Python 基本概念
开发语言·人工智能·python·大模型·编程语言
夕颜1111 小时前
如何让 AI 按照你的预期输出
后端
烛阴1 小时前
从零开始掌握C#核心:变量与数据类型
前端·c#
q***56381 小时前
Spring Boot--@PathVariable、@RequestParam、@RequestBody
java·spring boot·后端