Jelajahi Sumber

添加category表

Gogs 9 bulan lalu
induk
melakukan
774ab547ef
6 mengubah file dengan 195 tambahan dan 106 penghapusan
  1. 4 4
      app.py
  2. 1 1
      db_utils/data.py
  3. 30 60
      db_utils/files.py
  4. 48 26
      file_uploader.py
  5. 2 1
      requirements.txt
  6. 110 14
      templates/index.html

+ 4 - 4
app.py

@@ -8,12 +8,12 @@ from file_uploader import upload_file  # 导入文件上传的函数
 app = Flask(__name__)
 
 # 初始化数据库和表
-initialize_database()
-initialize_table()
+#initialize_database()
+#initialize_table()
 
 # 初始化数据库和表
-initialize_files_database()
-initialize_files_table()
+#initialize_files_database()
+#initialize_files_table("filePath")
 
 @app.route('/')
 def home():

+ 1 - 1
db_utils/data.py

@@ -8,7 +8,7 @@ DB_CONFIG = {
     'user': 'root',
     'password': '1',
     'port': 6003,
-    'database': 'fruit'  # 替换为数据库名称
+    'database': 'files'  # 替换为数据库名称
 }
 
 # 初始化数据库

+ 30 - 60
db_utils/files.py

@@ -1,4 +1,6 @@
 # -*- coding: utf-8 -*-
+from unicodedata import category
+
 import mysql.connector
 from mysql.connector import Error
 
@@ -46,15 +48,7 @@ def initialize_files_database():
             print("MySQL 服务器连接已关闭")
 
 # 初始化表
-def initialize_files_table(table_name=None):
-    if not table_name:
-        table_name = 'filePath'
-
-    # 验证表名是否合法(这里的规则可以根据你的需求做调整)
-    allowed_tables = ['fruit', 'filePath']  # 你可以在这里列出允许的表名
-    if table_name not in allowed_tables:
-        raise ValueError(f"不允许使用此表名:{table_name}")
-
+def initialize_files_table(table_name = "category"):
     try:
         connection = mysql.connector.connect(**DB_CONFIG)
         if connection.is_connected():
@@ -64,12 +58,13 @@ def initialize_files_table(table_name=None):
             create_table_query = f'''
                 CREATE TABLE IF NOT EXISTS `{table_name}` (
                     id INT AUTO_INCREMENT PRIMARY KEY,
-                    name VARCHAR(100)
+                    name VARCHAR(255),
+                    url VARCHAR(255)
                 )
             '''
 
             cursor.execute(create_table_query)
-            print(f"--- 创建 {table_name} 表 ---")
+            print(f"表 {table_name} 初始化成功。")
     except Error as err:
         print(f"初始化表时发生错误:{err}")
     finally:
@@ -79,55 +74,32 @@ def initialize_files_table(table_name=None):
             print("MySQL 连接已关闭")
 
 # 插入数据
-def insert_url(name):
+def insert_url(name, url, table_name="category"):
     try:
         connection = mysql.connector.connect(**DB_CONFIG)
         if connection.is_connected():
             cursor = connection.cursor()
 
-            # 插入数据
-            cursor.execute("INSERT INTO filePath (name) VALUES (%s)", (name,))
-            connection.commit()
-            print(f"插入数据成功:({name})")
-    except Error as err:
-        print(f"插入数据时发生错误:{err}")
-    finally:
-        if connection.is_connected():
-            cursor.close()
-            connection.close()
-            print("MySQL 连接已关闭")
+            # 确保目标文件表存在
+            initialize_files_table(table_name)
 
-# 插入数据
-def insert_data(name, origin):
-    try:
-        connection = mysql.connector.connect(**DB_CONFIG)
-        if connection.is_connected():
-            cursor = connection.cursor()
-
-            # 插入数据
-            cursor.execute("INSERT INTO filePath (name, origin) VALUES (%s, %s)", (name, origin))
+            # 插入文件数据到目标表
+            insert_query = f"INSERT INTO `{table_name}` (name, url) VALUES (%s, %s)"
+            cursor.execute(insert_query, (name, url))
             connection.commit()
-            print(f"插入数据成功:({name}, {origin})")
-    except Error as err:
-        print(f"插入数据时发生错误:{err}")
-    finally:
-        if connection.is_connected():
-            cursor.close()
-            connection.close()
-            print("MySQL 连接已关闭")
+            print(f"插入文件数据成功:({name}, {url}) 到表 {table_name}")
 
-def delete_data(name):
-    try:
-        connection = mysql.connector.connect(**DB_CONFIG)
-        if connection.is_connected():
-            cursor = connection.cursor()
+            # 确保 category 表存在
+            initialize_files_table("category")
 
-            # 删除数据
-            cursor.execute("DELETE FROM filePath WHERE name = %s", (name,))
+            # 插入表名到 category 表
+            insert_query = "INSERT IGNORE INTO `category` (name) VALUES (%s)"
+            cursor.execute(insert_query, (table_name,))
             connection.commit()
-            print(f"成功删除名称为 {name} 的记录")
+            print(f"插入表名成功:({table_name}) 到表 category")
+
     except Error as err:
-        print(f"删除数据时发生错误:{err}")
+        print(f"插入数据时发生错误:{err}")
     finally:
         if connection.is_connected():
             cursor.close()
@@ -136,16 +108,17 @@ def delete_data(name):
 
 
 # 查询数据
-def fetch_data():
+def fetch_data(table_name):
     try:
         connection = mysql.connector.connect(**DB_CONFIG)
         if connection.is_connected():
             cursor = connection.cursor()
 
             # 查询数据
-            cursor.execute("SELECT * FROM filePath")
+            query = f"SELECT * FROM `{table_name}`"
+            cursor.execute(query)
             rows = cursor.fetchall()
-            print("--- 查询结果 ---")
+            print(f"--- 表 {table_name} 的查询结果 ---")
             for row in rows:
                 print(row)
             return rows
@@ -159,13 +132,10 @@ def fetch_data():
 
 # 主函数
 if __name__ == "__main__":
-    # 初始化数据库和表
+    # 初始化数据库
     initialize_files_database()
-    initialize_files_table()
-
-    # 插入示例数据
-    insert_data('Apple', 'China')
-    insert_data('Banana', 'Ecuador')
 
-    # 查询数据
-    fetch_data()
+    # 示例:插入和查询数据
+    table_name = "filePath"
+    insert_url("example_file.mp4", table_name)
+    fetch_data(table_name)

+ 48 - 26
file_uploader.py

@@ -1,8 +1,7 @@
-# file_uploader.py
 import os
 from flask import request, jsonify
-
-from db_utils.files import insert_url
+from werkzeug.utils import secure_filename
+from db_utils.files import *
 
 # 上传目录
 UPLOAD_FOLDER = '../uploads'
@@ -10,7 +9,19 @@ if not os.path.exists(UPLOAD_FOLDER):
     os.makedirs(UPLOAD_FOLDER)
 
 # 允许的文件扩展名
-ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf','mp4','apk'}
+ALLOWED_EXTENSIONS = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'mp4', 'apk'}
+
+# 扩展名与数据库表的映射
+TABLE_MAPPING = {
+    'apk': 'apk_table',
+    'mp4': 'video_table',
+    'mp3': 'audio_table',
+    'pdf': 'document_table',
+    'jpg': 'image_table',
+    'png': 'image_table',
+    'jpeg': 'image_table',
+    'gif': 'image_table'
+}
 
 
 def allowed_file(filename):
@@ -20,33 +31,44 @@ def allowed_file(filename):
 
 def upload_file():
     """处理文件上传"""
-    # 检查请求中是否有文件
-    if 'file' not in request.files:
-        return jsonify({'error': 'No file part'}), 400
+    try:
+        # 检查请求中是否有文件
+        if 'file' not in request.files:
+            return jsonify({'error': 'No file part in request'}), 400
+
+        file = request.files['file']
+
+        # 检查文件是否为空
+        if file.filename == '':
+            return jsonify({'error': 'No selected file'}), 400
 
-    file = request.files['file']
+        # 检查文件是否符合要求
+        if file and allowed_file(file.filename):
+            # 获取文件扩展名
+            file_ext = file.filename.rsplit('.', 1)[1].lower()
 
-    # 检查文件是否为空
-    if file.filename == '':
-        return jsonify({'error': 'No selected file'}), 400
+            # 获取目标数据库表
+            target_table = TABLE_MAPPING.get(file_ext)
+            if not target_table:
+                return jsonify({'error': f'No table mapping for file type: {file_ext}'}), 400
 
-    # 检查文件是否符合要求
-    if file and allowed_file(file.filename):
-        # 保存文件到服务器
-        filename = os.path.join(UPLOAD_FOLDER, file.filename)
-        file.save(filename)
+            # 保存文件到服务器
+            filename = secure_filename(file.filename)
+            file_path = os.path.join(UPLOAD_FOLDER, filename)
+            file.save(file_path)
 
-        # 返回文件的下载链接
-        download_url = f'http://127.0.0.1:5000/download/{file.filename}'
+            # 生成下载链接
+            download_url = f'http://127.0.0.1:5000/download/{filename}'
 
-        if not download_url:
-            return jsonify({"error": "Missing name or origin"}), 400
+            # 插入数据库
+            try:
+                insert_url(filename,download_url, target_table)
+            except Exception as e:
+                return jsonify({"error": f"Database error: {str(e)}"}), 500
 
-        try:
-            insert_url(download_url)
-        except Exception as e:
-            return jsonify({"error": str(e)}), 500
+            return jsonify({'message': 'File uploaded successfully', 'download_url': download_url}), 200
 
-        return jsonify({'message': 'File uploaded successfully', 'download_url': download_url}), 200
+        return jsonify({'error': 'File type not allowed'}), 400
 
-    return jsonify({'error': 'File type not allowed'}), 400
+    except Exception as e:
+        return jsonify({"error": f"Server error: {str(e)}"}), 500

+ 2 - 1
requirements.txt

@@ -1,2 +1,3 @@
 flask~=3.0.3
-mysql-connector-python~=9.0.0
+mysql-connector-python~=9.0.0
+werkzeug~=3.0.6

+ 110 - 14
templates/index.html

@@ -3,27 +3,123 @@
 <head>
     <meta charset="UTF-8">
     <meta name="viewport" content="width=device-width, initial-scale=1.0">
-    <title>图片展示</title>
+    <title>文件管理系统</title>
+    <script>
+        // Fetch categories from the backend
+        async function fetchCategories() {
+            const response = await fetch('/categories'); // Backend endpoint to get categories
+            const categories = await response.json();
+            const categoryList = document.getElementById('category-list');
+
+            // Populate the left-side list with categories
+            categoryList.innerHTML = '';
+            categories.forEach(category => {
+                const listItem = document.createElement('li');
+                listItem.textContent = category.name;
+                listItem.onclick = () => fetchTableData(category.table_name);
+                categoryList.appendChild(listItem);
+            });
+        }
+
+        // Fetch table data when a category is clicked
+        async function fetchTableData(tableName) {
+            const response = await fetch(`/table-data?table=${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');
+                Object.values(row).forEach(value => {
+                    const cell = document.createElement('td');
+                    cell.textContent = value;
+                    tableRow.appendChild(cell);
+                });
+                tableBody.appendChild(tableRow);
+            });
+        }
+
+        // Initial load
+        document.addEventListener('DOMContentLoaded', fetchCategories);
+    </script>
     <style>
         body {
-            display: flex;
-            justify-content: center;
-            align-items: center;
-            height: 100vh;
+            font-family: Arial, sans-serif;
             margin: 0;
-            background-color: #f0f0f0;
+            display: flex;
+        }
+
+        #sidebar {
+            width: 20%;
+            background-color: #f8f9fa;
+            padding: 1em;
+            border-right: 1px solid #ddd;
+        }
+
+        #content {
+            flex-grow: 1;
+            padding: 1em;
+        }
+
+        ul {
+            list-style: none;
+            padding: 0;
+        }
+
+        li {
+            padding: 0.5em;
+            cursor: pointer;
+            border: 1px solid #ddd;
+            margin-bottom: 0.5em;
+            border-radius: 4px;
+            text-align: center;
+        }
+
+        li:hover {
+            background-color: #e9ecef;
+        }
+
+        table {
+            width: 100%;
+            border-collapse: collapse;
+        }
+
+        table, th, td {
+            border: 1px solid #ddd;
+        }
+
+        th, td {
+            padding: 0.5em;
+            text-align: left;
         }
-        img {
-            max-width: 100%;
-            max-height: 100%;
-            border: 2px solid #ccc;
-            border-radius: 8px;
-            box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
+
+        th {
+            background-color: #f1f1f1;
         }
     </style>
 </head>
 <body>
-    <!-- 图片路径可替换为实际文件路径 -->
-    <img src="/static/123.jpg" alt="展示图片">
+    <div id="sidebar">
+        <h2>分类</h2>
+        <ul id="category-list">
+            <!-- Categories will be dynamically loaded here -->
+        </ul>
+    </div>
+    <div id="content">
+        <h2>数据</h2>
+        <table>
+            <thead>
+                <tr>
+                    <th>ID</th>
+                    <th>名称</th>
+                    <th>URL</th>
+                </tr>
+            </thead>
+            <tbody id="table-body">
+                <!-- Table data will be dynamically loaded here -->
+            </tbody>
+        </table>
+    </div>
 </body>
 </html>