新增优化历史模块
This commit is contained in:
273
deploy_tencent_simple.py
Executable file
273
deploy_tencent_simple.py
Executable file
@@ -0,0 +1,273 @@
|
||||
#!/usr/bin/env python3
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
腾讯云数据库简化部署脚本
|
||||
快速部署优化历史功能到腾讯云数据库
|
||||
"""
|
||||
|
||||
import pymysql
|
||||
import sys
|
||||
from datetime import datetime
|
||||
|
||||
# 腾讯云数据库配置
|
||||
DB_CONFIG = {
|
||||
'host': 'gz-cynosdbmysql-grp-d26pzce5.sql.tencentcdb.com',
|
||||
'port': 24936,
|
||||
'user': 'root',
|
||||
'password': '!Rjb12191',
|
||||
'database': 'pro_db',
|
||||
'charset': 'utf8mb4'
|
||||
}
|
||||
|
||||
def execute_sql_file(cursor, sql_file):
|
||||
"""执行SQL文件"""
|
||||
try:
|
||||
with open(sql_file, 'r', encoding='utf-8') as f:
|
||||
sql_content = f.read()
|
||||
|
||||
# 分割SQL语句
|
||||
sql_statements = [stmt.strip() for stmt in sql_content.split(';') if stmt.strip()]
|
||||
|
||||
for sql in sql_statements:
|
||||
if sql and not sql.startswith('--'):
|
||||
try:
|
||||
cursor.execute(sql)
|
||||
print(f"✅ 执行成功: {sql[:50]}...")
|
||||
except Exception as e:
|
||||
print(f"⚠️ 执行失败: {sql[:50]}... - {str(e)}")
|
||||
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"❌ 执行SQL文件失败: {str(e)}")
|
||||
return False
|
||||
|
||||
def check_connection():
|
||||
"""检查数据库连接"""
|
||||
try:
|
||||
connection = pymysql.connect(**DB_CONFIG)
|
||||
cursor = connection.cursor()
|
||||
cursor.execute("SELECT 1")
|
||||
result = cursor.fetchone()
|
||||
cursor.close()
|
||||
connection.close()
|
||||
return True
|
||||
except Exception as e:
|
||||
print(f"❌ 数据库连接失败: {str(e)}")
|
||||
return False
|
||||
|
||||
def create_tables():
|
||||
"""创建表结构"""
|
||||
print("📋 开始创建表结构...")
|
||||
|
||||
# 连接数据库
|
||||
try:
|
||||
connection = pymysql.connect(**DB_CONFIG)
|
||||
cursor = connection.cursor()
|
||||
except Exception as e:
|
||||
print(f"❌ 连接数据库失败: {str(e)}")
|
||||
return False
|
||||
|
||||
try:
|
||||
# 1. 创建历史记录表
|
||||
print("\n1. 创建 prompt_history 表...")
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS prompt_history (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
user_id INT NOT NULL,
|
||||
wx_user_id INT,
|
||||
original_input TEXT NOT NULL,
|
||||
generated_prompt TEXT NOT NULL,
|
||||
template_id INT,
|
||||
template_name VARCHAR(100),
|
||||
generation_time INT,
|
||||
satisfaction_rating TINYINT,
|
||||
tags JSON,
|
||||
is_favorite BOOLEAN DEFAULT FALSE,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
|
||||
INDEX idx_user_id (user_id),
|
||||
INDEX idx_created_at (created_at),
|
||||
INDEX idx_template_id (template_id),
|
||||
INDEX idx_is_favorite (is_favorite)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
""")
|
||||
print(" ✅ prompt_history 表创建成功")
|
||||
|
||||
# 2. 创建标签表
|
||||
print("\n2. 创建 history_tags 表...")
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS history_tags (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
history_id INT NOT NULL,
|
||||
tag_name VARCHAR(50) NOT NULL,
|
||||
tag_type VARCHAR(20) DEFAULT 'custom',
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
|
||||
INDEX idx_history_id (history_id),
|
||||
INDEX idx_tag_name (tag_name)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
""")
|
||||
print(" ✅ history_tags 表创建成功")
|
||||
|
||||
# 3. 创建统计表
|
||||
print("\n3. 创建 user_statistics 表...")
|
||||
cursor.execute("""
|
||||
CREATE TABLE IF NOT EXISTS user_statistics (
|
||||
id INT PRIMARY KEY AUTO_INCREMENT,
|
||||
user_id INT UNIQUE NOT NULL,
|
||||
total_generations INT DEFAULT 0,
|
||||
favorite_count INT DEFAULT 0,
|
||||
avg_rating DECIMAL(3,2) DEFAULT 0.00,
|
||||
last_generation_at TIMESTAMP NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
|
||||
|
||||
INDEX idx_user_id (user_id)
|
||||
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4
|
||||
""")
|
||||
print(" ✅ user_statistics 表创建成功")
|
||||
|
||||
# 提交更改
|
||||
connection.commit()
|
||||
print("\n✅ 所有表创建成功并已提交")
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 创建表失败: {str(e)}")
|
||||
connection.rollback()
|
||||
return False
|
||||
|
||||
finally:
|
||||
cursor.close()
|
||||
connection.close()
|
||||
|
||||
def verify_tables():
|
||||
"""验证表是否创建成功"""
|
||||
print("\n🔍 验证表创建结果...")
|
||||
|
||||
try:
|
||||
connection = pymysql.connect(**DB_CONFIG)
|
||||
cursor = connection.cursor()
|
||||
|
||||
# 检查表是否存在
|
||||
tables = ['prompt_history', 'history_tags', 'user_statistics']
|
||||
|
||||
for table in tables:
|
||||
cursor.execute(f"SHOW TABLES LIKE '{table}'")
|
||||
if cursor.fetchone():
|
||||
print(f"✅ 表 {table} 存在")
|
||||
else:
|
||||
print(f"❌ 表 {table} 不存在")
|
||||
|
||||
# 显示表结构
|
||||
print("\n📊 表结构信息:")
|
||||
for table in tables:
|
||||
cursor.execute(f"DESCRIBE {table}")
|
||||
columns = cursor.fetchall()
|
||||
print(f"\n{table} 表结构 ({len(columns)} 列):")
|
||||
for col in columns:
|
||||
print(f" - {col[0]}: {col[1]}")
|
||||
|
||||
cursor.close()
|
||||
connection.close()
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 验证表失败: {str(e)}")
|
||||
|
||||
def create_sample_data():
|
||||
"""创建示例数据"""
|
||||
print("\n📝 创建示例数据...")
|
||||
|
||||
try:
|
||||
connection = pymysql.connect(**DB_CONFIG)
|
||||
cursor = connection.cursor()
|
||||
|
||||
# 检查是否已有数据
|
||||
cursor.execute("SELECT COUNT(*) FROM prompt_history")
|
||||
count = cursor.fetchone()[0]
|
||||
|
||||
if count > 0:
|
||||
print(f" ⚠️ 表中已有 {count} 条记录,跳过示例数据创建")
|
||||
return
|
||||
|
||||
# 插入示例数据
|
||||
sample_data = [
|
||||
(1, '请帮我写一个关于人工智能的提示词', '你是一位专业的人工智能专家,请详细分析人工智能的发展趋势、应用领域和未来前景。', 1, 'AI专家助手', 1500, 4, '["AI", "技术", "分析"]', False),
|
||||
(1, '帮我写一个产品经理的工作提示词', '你是一位资深的产品经理,请从用户需求、市场分析、产品设计等角度提供专业建议。', 2, '产品经理助手', 1200, 5, '["产品", "管理", "分析"]', True)
|
||||
]
|
||||
|
||||
for data in sample_data:
|
||||
cursor.execute("""
|
||||
INSERT INTO prompt_history
|
||||
(user_id, original_input, generated_prompt, template_id, template_name,
|
||||
generation_time, satisfaction_rating, tags, is_favorite)
|
||||
VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)
|
||||
""", data)
|
||||
print(f" ✅ 插入示例数据: {data[1][:30]}...")
|
||||
|
||||
# 更新用户统计
|
||||
cursor.execute("""
|
||||
INSERT INTO user_statistics (user_id, total_generations, favorite_count, avg_rating, last_generation_at)
|
||||
VALUES (1, 2, 1, 4.5, NOW())
|
||||
ON DUPLICATE KEY UPDATE
|
||||
total_generations = VALUES(total_generations),
|
||||
favorite_count = VALUES(favorite_count),
|
||||
avg_rating = VALUES(avg_rating),
|
||||
last_generation_at = VALUES(last_generation_at),
|
||||
updated_at = NOW()
|
||||
""")
|
||||
|
||||
connection.commit()
|
||||
print(" ✅ 示例数据创建成功")
|
||||
|
||||
cursor.close()
|
||||
connection.close()
|
||||
|
||||
except Exception as e:
|
||||
print(f"❌ 创建示例数据失败: {str(e)}")
|
||||
|
||||
def main():
|
||||
"""主函数"""
|
||||
print("🚀 腾讯云数据库优化历史功能部署")
|
||||
print("="*50)
|
||||
print(f"部署时间: {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}")
|
||||
print(f"目标数据库: {DB_CONFIG['host']}:{DB_CONFIG['port']}")
|
||||
print(f"数据库名: {DB_CONFIG['database']}")
|
||||
print("="*50)
|
||||
|
||||
# 1. 检查连接
|
||||
print("\n1. 检查数据库连接...")
|
||||
if not check_connection():
|
||||
print("❌ 数据库连接失败,请检查配置")
|
||||
sys.exit(1)
|
||||
print("✅ 数据库连接正常")
|
||||
|
||||
# 2. 创建表结构
|
||||
print("\n2. 创建表结构...")
|
||||
if not create_tables():
|
||||
print("❌ 创建表失败,部署终止")
|
||||
sys.exit(1)
|
||||
|
||||
# 3. 验证表
|
||||
verify_tables()
|
||||
|
||||
# 4. 创建示例数据
|
||||
create_sample_data()
|
||||
|
||||
print("\n" + "="*50)
|
||||
print("🎉 部署完成!")
|
||||
print("="*50)
|
||||
print("📋 部署摘要:")
|
||||
print(" ✅ 历史记录表 (prompt_history)")
|
||||
print(" ✅ 标签表 (history_tags)")
|
||||
print(" ✅ 统计表 (user_statistics)")
|
||||
print(" ✅ 示例数据")
|
||||
print("\n🔗 下一步:")
|
||||
print(" 1. 重启应用: pkill -f gunicorn && gunicorn -c gunicorn.conf.py src.flask_prompt_master:app")
|
||||
print(" 2. 访问历史页面: http://localhost:5002/history")
|
||||
print(" 3. 测试功能: python test_history_feature.py")
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user