Browse Source

添加删除操作

Gogs 9 months ago
parent
commit
f1b9bc286d
3 changed files with 142 additions and 62 deletions
  1. 14 36
      app.py
  2. 74 0
      db_utils/files.py
  3. 54 26
      templates/index.html

+ 14 - 36
app.py

@@ -50,47 +50,25 @@ def get_table():
     # 返回 JSON 格式的数据
     return jsonify(category_list)
 
-
-# 添加水果数据
-@app.route('/add_fruit', methods=['POST'])
-def add_fruit():
-    data = request.json
-    name = data.get('name')
-    origin = data.get('origin')
-
-    if not name or not origin:
-        return jsonify({"error": "Missing name or origin"}), 400
+@app.route('/delete_files', methods=['DELETE'])
+def delete_files():
+    # 获取 URL 查询参数
+    file_table = request.args.get('tableName')
+    row_id = request.args.get('rowId')
+
+    # 检查是否提供了表名和记录 ID
+    if not file_table:
+        return jsonify({"error": "Missing table"}), 400
+    if not row_id:
+        return jsonify({"error": "Missing rowId"}), 400
 
     try:
-        insert_data(name, origin)
-        return jsonify({"message": f"Fruit {name} from {origin} added successfully!"}), 200
+        # 调用删除数据的函数
+        delete_file(file_table, row_id)
+        return jsonify({"message": f"{row_id} deleted successfully from table {file_table}!"}), 200
     except Exception as e:
         return jsonify({"error": str(e)}), 500
 
-# 获取所有水果数据
-@app.route('/fruits', methods=['GET'])
-def get_fruits():
-    try:
-        fruits = fetch_data()
-        return jsonify({"fruits": fruits})
-    except Exception as e:
-        return jsonify({"error": str(e)}), 500
-
-@app.route('/delete_fruit', methods=['POST'])
-def delete_fruit():
-    data = request.json
-    name = data.get('name')
-
-    if not name:
-        return jsonify({"error": "Missing name"}), 400
-
-    try:
-        delete_data(name)
-        return jsonify({"message": f"Fruit {name} deleted successfully!"}), 200
-    except Exception as e:
-        return jsonify({"error": str(e)}), 500
-
-
 
 # 上传文件接口
 @app.route('/upload', methods=['POST'])

+ 74 - 0
db_utils/files.py

@@ -1,4 +1,5 @@
 # -*- coding: utf-8 -*-
+import os
 from unicodedata import category
 
 import mysql.connector
@@ -131,6 +132,79 @@ def insert_url(name, url, table_name="category"):
             print("MySQL 连接已关闭")
 
 
+def delete_file(table, rowid, file_path='../uploads'):
+    # 检查 table 和 rowid 是否为空
+    if not table or not rowid:
+        print("表名或名称不能为空!")
+        return
+
+    try:
+        # 建立数据库连接
+        connection = mysql.connector.connect(**DB_CONFIG)
+        if connection.is_connected():
+            cursor = connection.cursor()
+
+            # 确保 table 仅包含合法的表名(为了安全,避免 SQL 注入)
+            valid_tables = ['image_table', 'another_table']  # 将所有有效表名列出
+            if table not in valid_tables:
+                print(f"无效的表名:{table}")
+                return
+
+            # 查询 category 表,检查是否存在该表名
+            cursor.execute("SELECT * FROM category WHERE name = %s", (table,))
+            result = cursor.fetchone()
+
+            if not result:
+                print(f"无效的表名:{table}(没有找到对应的记录)")
+                return
+
+            # 执行查询数据库记录的操作
+            cursor.execute(f"SELECT * FROM {table} WHERE id = %s", (rowid,))
+            result = cursor.fetchone()
+
+            # 如果查询结果不为空,处理数据
+            if result:
+                print(f"成功查询到要删除的文件数据")
+
+                # 将元组转换为字典,假设你的字段是 id, categoryName, url
+                columns = [col[0] for col in cursor.description]  # 获取列名
+                result_dict = dict(zip(columns, result))  # 将结果转化为字典
+
+                # 获取文件名
+                file_name = result_dict.get('name')  # 这里假设 'name' 是存储文件名的字段
+
+                # 如果获取到文件路径,进行删除操作
+                if file_name:
+                    # 获取当前工作目录
+                    current_path = os.getcwd()  # 获取当前目录路径
+
+                    # 拼接相对路径
+                    file_path = os.path.join(current_path, '..', 'uploads', file_name)
+
+                    if os.path.exists(file_path):
+                        try:
+                            os.remove(file_path)  # 删除文件
+                            print(f"文件 {file_path} 已被删除")
+                        except Exception as e:
+                            print(f"删除文件时发生错误:{e}")
+                    else:
+                        print(f"文件路径 {file_path} 无效或文件不存在")
+
+            # 执行删除数据库记录的操作
+            cursor.execute(f"DELETE FROM {table} WHERE id = %s", (rowid,))
+            connection.commit()
+            print(f"成功删除名称为 {rowid} 的记录")
+
+    except Error as err:
+        print(f"删除数据时发生错误:{err}")
+    finally:
+        # 确保连接关闭
+        if connection.is_connected():
+            cursor.close()
+            connection.close()
+            print("MySQL 连接已关闭")
+
+
 
 # 查询数据
 def fetch_data(table_name):

+ 54 - 26
templates/index.html

@@ -22,34 +22,43 @@
         }
 
         async function fetchTableData(tableName) {
-            const response = await fetch(`/category-data?categoryName=${tableName}`); // Backend endpoint for table data
-            const tableData = await response.json();
-            const tableBody = document.getElementById('table-body');
-
-            // Populate the right-side table with data
-            tableBody.innerHTML = '';
-            tableData.forEach(row => {
-                const tableRow = document.createElement('tr');
-                // 显示 id 和 categoryName
-                const cells = [row.id, row.categoryName];
-                cells.forEach(value => {
-                    const cell = document.createElement('td');
-                    cell.textContent = value;
-                    tableRow.appendChild(cell);
-                });
+    const response = await fetch(`/category-data?categoryName=${tableName}`);
+    const tableData = await response.json();
+    const tableBody = document.getElementById('table-body');
 
-                // Add the download button in the last column
-                const downloadCell = document.createElement('td');
-                const downloadButton = document.createElement('button');
+    // Populate the right-side table with data
+    tableBody.innerHTML = '';
+    tableData.forEach(row => {
+        const tableRow = document.createElement('tr');
 
-                downloadButton.textContent = 'Download';
-                downloadButton.onclick = () => downloadFile(row.categoryName); // Assuming row[1] is the filename
-                downloadCell.appendChild(downloadButton);
-                tableRow.appendChild(downloadCell);
+        // Display id and categoryName
+        const cells = [row.id, row.categoryName];
+        cells.forEach(value => {
+            const cell = document.createElement('td');
+            cell.textContent = value;
+            tableRow.appendChild(cell);
+        });
+
+        // Add the download button in the last column
+        const downloadCell = document.createElement('td');
+        const downloadButton = document.createElement('button');
+        downloadButton.textContent = 'Download';
+        downloadButton.onclick = () => downloadFile(row.categoryName);
+        downloadCell.appendChild(downloadButton);
+
+        // Add the delete button in the last column
+        const deleteCell = document.createElement('td');
+        const deleteButton = document.createElement('button');
+        deleteButton.textContent = 'Delete';
+        deleteButton.onclick = () => deleteRow(tableName, row.id); // Pass the table name and row id
+        deleteCell.appendChild(deleteButton);
+
+        tableRow.appendChild(downloadCell);
+        tableRow.appendChild(deleteCell);
+        tableBody.appendChild(tableRow);
+    });
+}
 
-                tableBody.appendChild(tableRow);
-            });
-        }
 
         async function downloadFile(filename) {
             const response = await fetch(`/download/${filename}`, {
@@ -105,6 +114,24 @@
             }
         }
 
+        // Function to handle file deletion
+        // Function to handle delete
+        async function deleteRow(tableName, rowId) {
+            const confirmation = confirm('Are you sure you want to delete this row?');
+            if (confirmation) {
+                const response = await fetch(`/delete_files?tableName=${tableName}&rowId=${rowId}`, {
+                    method: 'DELETE',
+                });
+
+                if (response.ok) {
+                    alert('Row deleted successfully!');
+                    fetchTableData(tableName); // Reload the table data after deletion
+                } else {
+                    alert('Failed to delete the row');
+                }
+            }
+        }
+
         // Initial load
         document.addEventListener('DOMContentLoaded', fetchCategories);
     </script>
@@ -219,8 +246,9 @@
             <thead>
                 <tr>
                     <th>ID</th>
-                    <th>Category Name</th>
+                    <th>文件名</th>
                     <th>操作</th>
+                    <th>删除</th> <!-- Added Delete column -->
                 </tr>
             </thead>
             <tbody id="table-body">