Просмотр исходного кода

commit 优化数据库连接池

Hai Lin 1 неделя назад
Родитель
Сommit
24c162d973
2 измененных файлов с 53 добавлено и 14 удалено
  1. 35 10
      app.py
  2. 18 4
      templates/add_member.html

+ 35 - 10
app.py

@@ -57,8 +57,33 @@ def compress_image_if_needed(file_path, max_dim=2000):
         print(f"Warning: Image compression/normalization failed for {file_path}: {e}")
         print(f"Warning: Image compression/normalization failed for {file_path}: {e}")
         return file_path
         return file_path
 
 
-def get_db_connection():
-    return pymysql.connect(**DB_CONFIG)
+# 尝试使用数据库连接池,如果不可用则使用普通连接
+try:
+    from DBUtils.PooledDB import PooledDB
+    # 创建连接池
+    pool = PooledDB(
+        creator=pymysql,
+        maxconnections=10,  # 连接池最大连接数
+        mincached=2,        # 初始化时创建的空闲连接数
+        maxcached=5,        # 最大空闲连接数
+        maxshared=3,        # 最大共享连接数
+        blocking=True,      # 连接池满时是否阻塞等待
+        maxusage=None,      # 一个连接最多被重复使用的次数
+        setsession=[],      # 开始会话前执行的命令列表
+        ping=0,             # 用ping命令检查连接是否可用的频率
+        **DB_CONFIG
+    )
+    
+    def get_db_connection():
+        return pool.connection()
+    
+    print("Database connection pool initialized successfully")
+except ImportError:
+    # 如果DBUtils不可用,使用普通连接
+    def get_db_connection():
+        return pymysql.connect(**DB_CONFIG)
+    
+    print("DBUtils not available, using regular database connections")
 
 
 def format_timestamp(ts):
 def format_timestamp(ts):
     if not ts: return '未知'
     if not ts: return '未知'
@@ -1407,10 +1432,10 @@ def add_member():
                             if isinstance(content, list):
                             if isinstance(content, list):
                                 updated = False
                                 updated = False
                                 if 0 <= idx < len(content):
                                 if 0 <= idx < len(content):
-                                    if not content[idx].get('is_imported'): # Avoid redundant updates
-                                        content[idx]['is_imported'] = True
-                                        content[idx]['imported_member_id'] = member_id
-                                        updated = True
+                                    # Always update the status regardless of current value
+                                    content[idx]['is_imported'] = True
+                                    content[idx]['imported_member_id'] = member_id
+                                    updated = True
                                 
                                 
                                 if updated:
                                 if updated:
                                     new_content = json.dumps(content, ensure_ascii=False)
                                     new_content = json.dumps(content, ensure_ascii=False)
@@ -1568,10 +1593,10 @@ def edit_member(member_id):
                             if isinstance(content, list):
                             if isinstance(content, list):
                                 updated = False
                                 updated = False
                                 if 0 <= idx < len(content):
                                 if 0 <= idx < len(content):
-                                    if not content[idx].get('is_imported'): # Avoid redundant updates
-                                        content[idx]['is_imported'] = True
-                                        content[idx]['imported_member_id'] = member_id
-                                        updated = True
+                                    # Always update the status regardless of current value
+                                    content[idx]['is_imported'] = True
+                                    content[idx]['imported_member_id'] = member_id
+                                    updated = True
                                 
                                 
                                 if updated:
                                 if updated:
                                     new_content = json.dumps(content, ensure_ascii=False)
                                     new_content = json.dumps(content, ensure_ascii=False)

+ 18 - 4
templates/add_member.html

@@ -845,10 +845,18 @@
                     body: formData,
                     body: formData,
                     headers: {
                     headers: {
                         'X-Requested-With': 'XMLHttpRequest'
                         'X-Requested-With': 'XMLHttpRequest'
-                    }
+                    },
+                    credentials: 'include'
                 });
                 });
                 
                 
+                console.log('Response status:', response.status);
+                
+                if (!response.ok) {
+                    throw new Error(`HTTP error! status: ${response.status}`);
+                }
+                
                 const result = await response.json();
                 const result = await response.json();
+                console.log('Response data:', result);
                 
                 
                 if (result.success) {
                 if (result.success) {
                     // Success!
                     // Success!
@@ -870,13 +878,14 @@
                         }
                         }
                         
                         
                         // Update local data state so it persists if we switch images/filters
                         // Update local data state so it persists if we switch images/filters
-                        if (currentParsedPeople[window.lastFilledIndex]) {
+                        if (window.lastFilledIndex !== undefined && currentParsedPeople[window.lastFilledIndex]) {
                             currentParsedPeople[window.lastFilledIndex].is_imported = true;
                             currentParsedPeople[window.lastFilledIndex].is_imported = true;
                             currentParsedPeople[window.lastFilledIndex].imported_member_id = result.member_id;
                             currentParsedPeople[window.lastFilledIndex].imported_member_id = result.member_id;
                             
                             
                             // Sync back to images array to persist across image switching
                             // Sync back to images array to persist across image switching
                             if (images[currentIndex]) {
                             if (images[currentIndex]) {
                                 images[currentIndex].ai_content = currentParsedPeople;
                                 images[currentIndex].ai_content = currentParsedPeople;
+                                console.log('Updated images array:', images[currentIndex]);
                             }
                             }
                         }
                         }
                     }
                     }
@@ -984,7 +993,7 @@
                 }
                 }
             } catch (error) {
             } catch (error) {
                 console.error('Error submitting form:', error);
                 console.error('Error submitting form:', error);
-                alert('网络或服务器错误,请稍后重试');
+                alert('网络或服务器错误,请稍后重试: ' + error.message);
             } finally {
             } finally {
                 submitBtn.disabled = false;
                 submitBtn.disabled = false;
                 submitBtn.innerHTML = originalBtnHtml;
                 submitBtn.innerHTML = originalBtnHtml;
@@ -1164,7 +1173,12 @@
         
         
         // Set Source Index
         // Set Source Index
         const sourceIndexInput = form.querySelector('[name="source_index"]');
         const sourceIndexInput = form.querySelector('[name="source_index"]');
-        if (sourceIndexInput) sourceIndexInput.value = index;
+        if (sourceIndexInput) {
+            sourceIndexInput.value = index;
+            console.log('Set source_index:', index);
+            window.lastFilledIndex = index;
+            console.log('Set lastFilledIndex:', index);
+        }
 
 
         // 1. 姓名
         // 1. 姓名
         if (person.name) {
         if (person.name) {