76 lines
2.2 KiB
Python
76 lines
2.2 KiB
Python
"""
|
|
创建 SQLite 数据库并初始化表结构
|
|
"""
|
|
import sqlite3
|
|
import os
|
|
import bcrypt
|
|
from uuid import uuid4
|
|
|
|
DB_PATH = "weibo_hotsign.db"
|
|
SQL_FILE = "init-db-sqlite.sql"
|
|
|
|
def hash_password(password: str) -> str:
|
|
"""使用 bcrypt 加密密码"""
|
|
salt = bcrypt.gensalt(rounds=12)
|
|
hashed = bcrypt.hashpw(password.encode('utf-8'), salt)
|
|
return hashed.decode('utf-8')
|
|
|
|
def create_database():
|
|
"""创建数据库并执行初始化脚本"""
|
|
# 如果数据库已存在,先删除
|
|
if os.path.exists(DB_PATH):
|
|
print(f"数据库文件 {DB_PATH} 已存在,正在删除...")
|
|
os.remove(DB_PATH)
|
|
|
|
# 创建新数据库
|
|
print(f"正在创建数据库 {DB_PATH}...")
|
|
conn = sqlite3.connect(DB_PATH)
|
|
cursor = conn.cursor()
|
|
|
|
# 读取并执行 SQL 脚本
|
|
print(f"正在执行初始化脚本 {SQL_FILE}...")
|
|
with open(SQL_FILE, 'r', encoding='utf-8') as f:
|
|
sql_script = f.read()
|
|
|
|
cursor.executescript(sql_script)
|
|
conn.commit()
|
|
|
|
# 创建测试用户
|
|
print("\n正在创建测试用户...")
|
|
test_user_id = str(uuid4())
|
|
test_username = "admin"
|
|
test_email = "admin@example.com"
|
|
test_password = "Admin123!" # 符合密码强度要求
|
|
hashed_password = hash_password(test_password)
|
|
|
|
cursor.execute("""
|
|
INSERT INTO users (id, username, email, hashed_password, is_active)
|
|
VALUES (?, ?, ?, ?, 1)
|
|
""", (test_user_id, test_username, test_email, hashed_password))
|
|
|
|
conn.commit()
|
|
|
|
# 验证表是否创建成功
|
|
cursor.execute("SELECT name FROM sqlite_master WHERE type='table';")
|
|
tables = cursor.fetchall()
|
|
|
|
print("\n" + "="*50)
|
|
print("数据库创建成功!")
|
|
print("="*50)
|
|
print("\n已创建的表:")
|
|
for table in tables:
|
|
print(f" ✓ {table[0]}")
|
|
|
|
print("\n测试用户信息:")
|
|
print(f" 用户名: {test_username}")
|
|
print(f" 邮箱: {test_email}")
|
|
print(f" 密码: {test_password}")
|
|
print(f" 用户ID: {test_user_id}")
|
|
|
|
conn.close()
|
|
print(f"\n数据库文件路径: {os.path.abspath(DB_PATH)}")
|
|
print("\n提示: 你可以使用上述测试账号登录,或通过注册页面创建新用户")
|
|
|
|
if __name__ == "__main__":
|
|
create_database()
|