2023.11.19使用flask制作一个文件夹生成器
实现功能:
(1)在指定路径上建立文件夹
(2)返回文件夹的路径和建立成功与否的提示
main.py
import os
from flask import Flask, request, jsonify, render_templateapp = 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), 500if __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>