From 3ebcb77ca9808d87e19c04603a31a139c85d834a Mon Sep 17 00:00:00 2001
From: rjb <263303411@qq.com>
Date: Tue, 7 Oct 2025 00:58:53 +0800
Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E6=95=B0=E6=8D=AE?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
---
direct_insert_templates.py | 170 +
force_insert_templates.py | 134 +
init_tencent_db.py | 271 +
logs/app.log | 6 +
logs/gunicorn.log | 295 +-
logs/gunicorn.pid | 2 +-
logs/gunicorn_access.log | 9930 +++++++++++++++++
logs/gunicorn_error.log | 416 +
.../poetry_favorites.cpython-312.pyc | Bin 5035 -> 5035 bytes
src/flask_prompt_master/promptsTemplates.py | 116 +-
.../routes/__pycache__/poetry.cpython-312.pyc | Bin 16994 -> 16994 bytes
.../routes/__pycache__/routes.cpython-312.pyc | Bin 47577 -> 47698 bytes
src/flask_prompt_master/routes/routes.py | 6 +-
.../poetry_favorite_service.cpython-312.pyc | Bin 11087 -> 11087 bytes
.../templates/generate.html | 689 +-
test_search_state_fix.py | 72 +
test_tencent_db_init.py | 41 +
搜索状态保持问题修复文档.md | 202 +
搜索状态修复测试指南.md | 105 +
数据库初始化说明.md | 107 +
模板初始化完整文档.md | 333 +
模板初始化快速参考.md | 79 +
腾讯云数据库初始化使用说明.md | 88 +
23 files changed, 13031 insertions(+), 31 deletions(-)
create mode 100644 direct_insert_templates.py
create mode 100644 force_insert_templates.py
create mode 100644 init_tencent_db.py
create mode 100644 test_search_state_fix.py
create mode 100644 test_tencent_db_init.py
create mode 100644 搜索状态保持问题修复文档.md
create mode 100644 搜索状态修复测试指南.md
create mode 100644 数据库初始化说明.md
create mode 100644 模板初始化完整文档.md
create mode 100644 模板初始化快速参考.md
create mode 100644 腾讯云数据库初始化使用说明.md
diff --git a/direct_insert_templates.py b/direct_insert_templates.py
new file mode 100644
index 0000000..0c607d8
--- /dev/null
+++ b/direct_insert_templates.py
@@ -0,0 +1,170 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+直接插入模板数据到腾讯云数据库
+不依赖Flask应用,直接从文件读取模板数据
+"""
+import pymysql
+import re
+import json
+
+def extract_templates_from_file():
+ """直接从文件提取模板数据"""
+ print("📖 正在读取模板文件...")
+
+ try:
+ with open('src/flask_prompt_master/promptsTemplates.py', 'r', encoding='utf-8') as f:
+ content = f.read()
+
+ # 查找templates列表的开始和结束
+ start_pattern = r'templates\s*=\s*\['
+ end_pattern = r'\]\s*$'
+
+ start_match = re.search(start_pattern, content)
+ if not start_match:
+ print("❌ 无法找到templates列表")
+ return []
+
+ # 找到templates列表的开始位置
+ start_pos = start_match.end()
+
+ # 从开始位置查找对应的结束括号
+ bracket_count = 1
+ pos = start_pos
+ while pos < len(content) and bracket_count > 0:
+ if content[pos] == '[':
+ bracket_count += 1
+ elif content[pos] == ']':
+ bracket_count -= 1
+ pos += 1
+
+ if bracket_count != 0:
+ print("❌ 无法找到templates列表的结束位置")
+ return []
+
+ # 提取templates列表的字符串
+ templates_str = content[start_pos-1:pos]
+
+ # 使用eval来解析Python列表(注意:这在生产环境中不推荐,但这里是为了简化)
+ try:
+ templates = eval(templates_str)
+ print(f"✅ 成功提取 {len(templates)} 个模板")
+ return templates
+ except Exception as e:
+ print(f"❌ 解析模板数据失败: {str(e)}")
+ return []
+
+ except Exception as e:
+ print(f"❌ 读取文件失败: {str(e)}")
+ return []
+
+def insert_templates_to_tencent():
+ """插入模板数据到腾讯云数据库"""
+ print("🚀 开始插入模板数据到腾讯云数据库...")
+
+ # 腾讯云数据库配置
+ config = {
+ 'host': 'gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com',
+ 'port': 24936,
+ 'user': 'root',
+ 'password': '!Rjb12191',
+ 'database': 'pro_db',
+ 'charset': 'utf8mb4'
+ }
+
+ try:
+ # 连接数据库
+ print("🔗 连接到腾讯云数据库...")
+ conn = pymysql.connect(**config)
+ cursor = conn.cursor()
+ print("✅ 数据库连接成功")
+
+ # 获取模板数据
+ templates = extract_templates_from_file()
+ if not templates:
+ print("❌ 无法获取模板数据,退出")
+ return
+
+ # 清空现有数据
+ print("🗑️ 清空现有模板数据...")
+ cursor.execute("TRUNCATE TABLE prompt_template")
+ print("✅ 现有数据已清空")
+
+ # 插入所有模板数据
+ print("📝 开始插入所有模板数据...")
+ sql = """
+ INSERT INTO prompt_template
+ (name, description, category, industry, profession, sub_category, system_prompt, is_default)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
+ """
+
+ success_count = 0
+ error_count = 0
+
+ for i, template in enumerate(templates, 1):
+ try:
+ cursor.execute(sql, (
+ template.get('name', ''),
+ template.get('description', ''),
+ template.get('category', ''),
+ template.get('industry', ''),
+ template.get('profession', ''),
+ template.get('sub_category', ''),
+ template.get('system_prompt', ''),
+ template.get('is_default', False)
+ ))
+ success_count += 1
+
+ # 每插入20个模板显示一次进度
+ if i % 20 == 0:
+ print(f"📈 已插入 {i}/{len(templates)} 个模板...")
+
+ except Exception as e:
+ print(f"⚠️ 插入模板 '{template.get('name', 'Unknown')}' 失败: {str(e)}")
+ error_count += 1
+
+ # 提交事务
+ conn.commit()
+
+ print("\n" + "="*50)
+ print("🎉 模板数据插入完成!")
+ print(f"✅ 成功插入: {success_count} 个模板")
+ if error_count > 0:
+ print(f"⚠️ 插入失败: {error_count} 个模板")
+ print(f"📊 总计模板: {len(templates)} 个")
+ print("="*50)
+
+ # 验证插入结果
+ cursor.execute("SELECT COUNT(*) FROM prompt_template")
+ final_count = cursor.fetchone()[0]
+ print(f"🔍 数据库中的模板总数: {final_count}")
+
+ except Exception as e:
+ print(f"❌ 插入模板数据失败: {str(e)}")
+ import traceback
+ traceback.print_exc()
+ if 'conn' in locals():
+ conn.rollback()
+ finally:
+ if 'cursor' in locals():
+ cursor.close()
+ if 'conn' in locals():
+ conn.close()
+
+def main():
+ """主函数"""
+ print("=" * 60)
+ print("🔄 直接插入模板数据工具")
+ print("=" * 60)
+ print("⚠️ 警告:此操作将清空现有的所有模板数据!")
+
+ # 确认操作
+ confirm = input("\n是否继续?(y/N): ").strip().lower()
+ if confirm not in ['y', 'yes', '是']:
+ print("❌ 操作已取消")
+ return
+
+ insert_templates_to_tencent()
+
+if __name__ == '__main__':
+ main()
diff --git a/force_insert_templates.py b/force_insert_templates.py
new file mode 100644
index 0000000..c912cdd
--- /dev/null
+++ b/force_insert_templates.py
@@ -0,0 +1,134 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+强制插入所有模板数据到腾讯云数据库
+"""
+import pymysql
+import sys
+import os
+
+# 添加项目根目录到Python路径
+project_root = os.path.dirname(os.path.abspath(__file__))
+sys.path.append(project_root)
+
+def get_templates():
+ """获取模板数据"""
+ try:
+ from src.flask_prompt_master.promptsTemplates import templates
+ return templates
+ except ImportError:
+ print("❌ 无法导入模板数据,请确保在项目根目录运行此脚本")
+ return []
+
+def force_insert_templates():
+ """强制插入所有模板数据到腾讯云数据库"""
+ print("🚀 开始强制插入所有模板数据到腾讯云数据库...")
+
+ # 腾讯云数据库配置
+ config = {
+ 'host': 'gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com',
+ 'port': 24936,
+ 'user': 'root',
+ 'password': '!Rjb12191',
+ 'database': 'pro_db',
+ 'charset': 'utf8mb4'
+ }
+
+ try:
+ # 连接数据库
+ print("🔗 连接到腾讯云数据库...")
+ conn = pymysql.connect(**config)
+ cursor = conn.cursor()
+ print("✅ 数据库连接成功")
+
+ # 获取模板数据
+ templates = get_templates()
+ if not templates:
+ print("❌ 无法获取模板数据,退出")
+ return
+
+ print(f"📊 准备插入 {len(templates)} 个模板...")
+
+ # 清空现有数据
+ print("🗑️ 清空现有模板数据...")
+ cursor.execute("TRUNCATE TABLE prompt_template")
+ print("✅ 现有数据已清空")
+
+ # 插入所有模板数据
+ print("📝 开始插入所有模板数据...")
+ sql = """
+ INSERT INTO prompt_template
+ (name, description, category, industry, profession, sub_category, system_prompt, is_default)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
+ """
+
+ success_count = 0
+ error_count = 0
+
+ for i, template in enumerate(templates, 1):
+ try:
+ cursor.execute(sql, (
+ template['name'],
+ template['description'],
+ template.get('category', ''),
+ template.get('industry', ''),
+ template.get('profession', ''),
+ template.get('sub_category', ''),
+ template['system_prompt'],
+ template.get('is_default', False)
+ ))
+ success_count += 1
+
+ # 每插入50个模板显示一次进度
+ if i % 50 == 0:
+ print(f"📈 已插入 {i}/{len(templates)} 个模板...")
+
+ except Exception as e:
+ print(f"⚠️ 插入模板 '{template['name']}' 失败: {str(e)}")
+ error_count += 1
+
+ # 提交事务
+ conn.commit()
+
+ print("\n" + "="*50)
+ print("🎉 模板数据插入完成!")
+ print(f"✅ 成功插入: {success_count} 个模板")
+ if error_count > 0:
+ print(f"⚠️ 插入失败: {error_count} 个模板")
+ print(f"📊 总计模板: {len(templates)} 个")
+ print("="*50)
+
+ # 验证插入结果
+ cursor.execute("SELECT COUNT(*) FROM prompt_template")
+ final_count = cursor.fetchone()[0]
+ print(f"🔍 数据库中的模板总数: {final_count}")
+
+ except Exception as e:
+ print(f"❌ 插入模板数据失败: {str(e)}")
+ import traceback
+ traceback.print_exc()
+ if 'conn' in locals():
+ conn.rollback()
+ finally:
+ if 'cursor' in locals():
+ cursor.close()
+ if 'conn' in locals():
+ conn.close()
+
+def main():
+ """主函数"""
+ print("=" * 60)
+ print("🔄 强制插入模板数据工具")
+ print("=" * 60)
+ print("⚠️ 警告:此操作将清空现有的所有模板数据!")
+
+ # 确认操作
+ confirm = input("\n是否继续?(y/N): ").strip().lower()
+ if confirm not in ['y', 'yes', '是']:
+ print("❌ 操作已取消")
+ return
+
+ force_insert_templates()
+
+if __name__ == '__main__':
+ main()
diff --git a/init_tencent_db.py b/init_tencent_db.py
new file mode 100644
index 0000000..14a6e9e
--- /dev/null
+++ b/init_tencent_db.py
@@ -0,0 +1,271 @@
+#!/usr/bin/env python3
+# -*- coding: utf-8 -*-
+"""
+腾讯云数据库初始化脚本
+独立运行,不依赖Flask应用
+"""
+import pymysql
+import sys
+import os
+
+# 添加项目根目录到Python路径
+project_root = os.path.dirname(os.path.abspath(__file__))
+sys.path.append(project_root)
+
+def get_templates():
+ """获取模板数据"""
+ # 从promptsTemplates.py文件导入模板数据
+ try:
+ from src.flask_prompt_master.promptsTemplates import templates
+ return templates
+ except ImportError:
+ print("❌ 无法导入模板数据,请确保在项目根目录运行此脚本")
+ return []
+
+def init_tencent_database(force_insert=False):
+ """初始化腾讯云数据库"""
+ print("🚀 开始初始化腾讯云数据库...")
+
+ # 腾讯云数据库配置
+ config = {
+ 'host': 'gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com',
+ 'port': 24936,
+ 'user': 'root',
+ 'password': '!Rjb12191',
+ 'database': 'pro_db',
+ 'charset': 'utf8mb4'
+ }
+
+ try:
+ # 连接数据库
+ print("🔗 连接到腾讯云数据库...")
+ conn = pymysql.connect(**config)
+ cursor = conn.cursor()
+ print("✅ 数据库连接成功")
+
+ # 创建 prompt_template 表
+ print("📋 创建 prompt_template 表...")
+ cursor.execute("""
+ CREATE TABLE IF NOT EXISTS prompt_template (
+ id INT PRIMARY KEY AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ description TEXT,
+ category VARCHAR(50),
+ industry VARCHAR(50),
+ profession VARCHAR(50),
+ sub_category VARCHAR(50),
+ system_prompt TEXT NOT NULL,
+ is_default BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+ """)
+ print("✅ prompt_template 表创建/检查完成")
+
+ # 检查是否已有模板数据
+ cursor.execute("SELECT COUNT(*) FROM prompt_template")
+ count = cursor.fetchone()[0]
+
+ if count == 0:
+ print("📝 开始插入模板数据...")
+
+ # 获取模板数据
+ templates = get_templates()
+ if not templates:
+ print("❌ 无法获取模板数据,退出")
+ return
+
+ # 插入模板数据
+ sql = """
+ INSERT INTO prompt_template
+ (name, description, category, industry, profession, sub_category, system_prompt, is_default)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
+ """
+
+ success_count = 0
+ error_count = 0
+
+ for template in templates:
+ try:
+ cursor.execute(sql, (
+ template['name'],
+ template['description'],
+ template.get('category', ''),
+ template.get('industry', ''),
+ template.get('profession', ''),
+ template.get('sub_category', ''),
+ template['system_prompt'],
+ template.get('is_default', False)
+ ))
+ success_count += 1
+ except Exception as e:
+ print(f"⚠️ 插入模板 '{template['name']}' 失败: {str(e)}")
+ error_count += 1
+
+ print(f"✅ 成功插入 {success_count} 个模板数据!")
+ if error_count > 0:
+ print(f"⚠️ {error_count} 个模板插入失败")
+ else:
+ print(f"ℹ️ 模板数据已存在 ({count} 条记录),跳过初始化。")
+
+ # 提交事务
+ conn.commit()
+ print("🎉 腾讯云数据库初始化完成!")
+
+ except Exception as e:
+ print(f"❌ 初始化数据库失败: {str(e)}")
+ import traceback
+ traceback.print_exc()
+ if 'conn' in locals():
+ conn.rollback()
+ finally:
+ if 'cursor' in locals():
+ cursor.close()
+ if 'conn' in locals():
+ conn.close()
+
+def init_local_database():
+ """初始化本地数据库"""
+ print("🚀 开始初始化本地数据库...")
+
+ # 本地数据库配置
+ config = {
+ 'host': 'localhost',
+ 'user': 'root',
+ 'password': '123456',
+ 'database': 'pro_db',
+ 'charset': 'utf8mb4'
+ }
+
+ try:
+ # 连接数据库
+ print("🔗 连接到本地数据库...")
+ conn = pymysql.connect(**config)
+ cursor = conn.cursor()
+ print("✅ 数据库连接成功")
+
+ # 创建 prompt_template 表
+ print("📋 创建 prompt_template 表...")
+ cursor.execute("""
+ CREATE TABLE IF NOT EXISTS prompt_template (
+ id INT PRIMARY KEY AUTO_INCREMENT,
+ name VARCHAR(100) NOT NULL,
+ description TEXT,
+ category VARCHAR(50),
+ industry VARCHAR(50),
+ profession VARCHAR(50),
+ sub_category VARCHAR(50),
+ system_prompt TEXT NOT NULL,
+ is_default BOOLEAN DEFAULT FALSE,
+ created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP
+ ) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4;
+ """)
+ print("✅ prompt_template 表创建/检查完成")
+
+ # 检查是否已有模板数据
+ cursor.execute("SELECT COUNT(*) FROM prompt_template")
+ count = cursor.fetchone()[0]
+
+ if count == 0:
+ print("📝 开始插入模板数据...")
+
+ # 获取模板数据
+ templates = get_templates()
+ if not templates:
+ print("❌ 无法获取模板数据,退出")
+ return
+
+ # 插入模板数据
+ sql = """
+ INSERT INTO prompt_template
+ (name, description, category, industry, profession, sub_category, system_prompt, is_default)
+ VALUES (%s, %s, %s, %s, %s, %s, %s, %s)
+ """
+
+ success_count = 0
+ error_count = 0
+
+ for template in templates:
+ try:
+ cursor.execute(sql, (
+ template['name'],
+ template['description'],
+ template.get('category', ''),
+ template.get('industry', ''),
+ template.get('profession', ''),
+ template.get('sub_category', ''),
+ template['system_prompt'],
+ template.get('is_default', False)
+ ))
+ success_count += 1
+ except Exception as e:
+ print(f"⚠️ 插入模板 '{template['name']}' 失败: {str(e)}")
+ error_count += 1
+
+ print(f"✅ 成功插入 {success_count} 个模板数据!")
+ if error_count > 0:
+ print(f"⚠️ {error_count} 个模板插入失败")
+ else:
+ print(f"ℹ️ 模板数据已存在 ({count} 条记录),跳过初始化。")
+
+ # 提交事务
+ conn.commit()
+ print("🎉 本地数据库初始化完成!")
+
+ except Exception as e:
+ print(f"❌ 初始化数据库失败: {str(e)}")
+ import traceback
+ traceback.print_exc()
+ if 'conn' in locals():
+ conn.rollback()
+ finally:
+ if 'cursor' in locals():
+ cursor.close()
+ if 'conn' in locals():
+ conn.close()
+
+def main():
+ """主函数"""
+ print("=" * 60)
+ print("🗄️ 数据库初始化工具")
+ print("=" * 60)
+
+ if len(sys.argv) > 1:
+ db_type = sys.argv[1].lower()
+ if db_type in ['tencent', 't']:
+ init_tencent_database()
+ elif db_type in ['local', 'l']:
+ init_local_database()
+ else:
+ print("❌ 无效的数据库类型参数")
+ print("用法: python init_tencent_db.py [local|tencent]")
+ print(" local 或 l - 初始化本地数据库")
+ print(" tencent 或 t - 初始化腾讯云数据库")
+ sys.exit(1)
+ else:
+ # 交互式选择
+ while True:
+ print("\n请选择要初始化的数据库:")
+ print("1. 本地数据库 (localhost)")
+ print("2. 腾讯云数据库")
+ print("3. 退出")
+
+ choice = input("\n请输入选择 (1-3): ").strip()
+
+ if choice == '1':
+ print("\n" + "="*40)
+ init_local_database()
+ print("="*40)
+ break
+ elif choice == '2':
+ print("\n" + "="*40)
+ init_tencent_database()
+ print("="*40)
+ break
+ elif choice == '3':
+ print("👋 退出程序")
+ break
+ else:
+ print("❌ 无效选择,请重新输入")
+
+if __name__ == '__main__':
+ main()
diff --git a/logs/app.log b/logs/app.log
index 4725d28..6800bd4 100644
--- a/logs/app.log
+++ b/logs/app.log
@@ -1273,3 +1273,9 @@ OSError: [Errno 5] Input/output error
2025-09-18 23:43:08,941 INFO: 应用启动 [in /home/renjianbo/aitsc/config/base.py:82]
2025-09-18 23:46:46,603 INFO: 应用启动 [in /home/renjianbo/aitsc/config/base.py:82]
2025-09-18 23:58:37,127 INFO: 应用启动 [in /home/renjianbo/aitsc/config/base.py:82]
+2025-09-19 00:44:50,891 INFO: 应用启动 [in /home/renjianbo/aitsc/config/base.py:82]
+2025-10-04 22:37:29,141 INFO: 应用启动 [in /home/renjianbo/aitsc/config/base.py:82]
+2025-10-07 00:33:02,531 INFO: 应用启动 [in /home/renjianbo/aitsc/config/base.py:82]
+2025-10-07 00:37:10,502 INFO: 应用启动 [in /home/renjianbo/aitsc/config/base.py:82]
+2025-10-07 00:44:35,327 INFO: 应用启动 [in /home/renjianbo/aitsc/config/base.py:82]
+2025-10-07 00:51:53,037 INFO: 应用启动 [in /home/renjianbo/aitsc/config/base.py:82]
diff --git a/logs/gunicorn.log b/logs/gunicorn.log
index a08532f..09aa4d4 100644
--- a/logs/gunicorn.log
+++ b/logs/gunicorn.log
@@ -1,2 +1,295 @@
nohup: ignoring input
-[2025-09-18 23:58:37,127] INFO in base: 应用启动
+[2025-09-19 00:44:50,891] INFO in base: 应用启动
+
+=== API 响应结果 ===
+生成的提示词: 基于您提出的"优化页面"需求,我将从多个维度提供专业的前端优化方案:
+
+## 🎯 核心优化目标
+
+### 1. 性能优化
+```javascript
+// 代码分割与懒加载
+const LazyComponent = React.lazy(() => import('./HeavyComponent'));
+
+// 图片优化策略
+const imageOptimization = {
+ format: 'WebP/AVIF',
+ lazyLoading: true,
+ responsive: 'srcset'
+};
+```
+
+### 2. 用户体验优化
+```css
+/* 交互动效优化 */
+.interactive-element {
+ transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
+ will-change: transform, opacity;
+}
+
+/* 骨架屏加载状态 */
+.skeleton-loader {
+ background: linear-gradient(90deg, #f0f0f0 25%, #e0e0e0 50%, #f0f0f0 75%);
+ background-size: 200% 100%;
+ animation: loading 1.5s infinite;
+}
+```
+
+### 3. 技术实现方案
+
+#### 组件结构优化
+```jsx
+// 优化后的组件结构
+const OptimizedPage = () => {
+ const [visibleSections, setVisibleSections] = useState([]);
+
+ return (
+