-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathinit_user.py
More file actions
68 lines (55 loc) · 1.98 KB
/
init_user.py
File metadata and controls
68 lines (55 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
# -*- coding: utf-8 -*-
# init_user.py
"""
初始化用户脚本
用于创建默认管理员账户
"""
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from server import User, Base
# 【请修改】你的数据库配置(与 server.py 保持一致)
SQLALCHEMY_DATABASE_URL = "mysql+pymysql://root:123456@localhost:3306/rag_db"
engine = create_engine(SQLALCHEMY_DATABASE_URL)
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
def init_db():
"""初始化数据库和默认用户"""
print("=" * 50)
print("📊 正在初始化数据库...")
print("=" * 50)
try:
# 1. 创建所有表
Base.metadata.create_all(bind=engine)
print("✅ 数据库表创建成功")
db = SessionLocal()
# 2. 检查是否存在 admin 用户
user = db.query(User).filter(User.username == "admin").first()
if not user:
# 创建默认管理员(明文密码)
new_user = User(username="admin", password="123456")
db.add(new_user)
db.commit()
print("✅ 已创建默认管理员账户:")
print(" 用户名: admin")
print(" 密码: 123456")
else:
print("⚠️ 用户 'admin' 已存在,跳过创建")
# 3. 显示所有用户
all_users = db.query(User).all()
if all_users:
print(f"\n📋 当前数据库中的用户 ({len(all_users)} 个):")
for u in all_users:
print(f" - {u.username} (ID: {u.id})")
else:
print("\n⚠️ 数据库中没有用户")
db.close()
print("\n" + "=" * 50)
print("✅ 初始化完成!")
print("=" * 50)
except Exception as e:
print(f"\n❌ 初始化失败: {e}")
import traceback
traceback.print_exc()
return False
return True
if __name__ == "__main__":
init_db()