Files
military-tech-voice3.0/backend/app/db.py
T

70 lines
2.3 KiB
Python
Raw Normal View History

import sqlite3
import os
from werkzeug.security import generate_password_hash
DB_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', 'data')
DB_PATH = os.path.join(DB_DIR, 'voice.db')
def get_db():
"""获取数据库连接"""
conn = sqlite3.connect(DB_PATH)
conn.row_factory = sqlite3.Row
conn.execute("PRAGMA journal_mode=WAL")
return conn
def init_db():
"""初始化数据库表 + 创建默认 admin 账号"""
os.makedirs(DB_DIR, exist_ok=True)
conn = get_db()
cursor = conn.cursor()
cursor.executescript('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE NOT NULL,
display_name TEXT NOT NULL,
password_hash TEXT NOT NULL,
role TEXT DEFAULT 'editor',
is_active INTEGER DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
);
CREATE TABLE IF NOT EXISTS invite_codes (
id INTEGER PRIMARY KEY AUTOINCREMENT,
code TEXT UNIQUE NOT NULL,
editor_name TEXT NOT NULL,
is_used INTEGER DEFAULT 0,
used_by_user_id INTEGER,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
used_at DATETIME
);
CREATE TABLE IF NOT EXISTS usage_logs (
id INTEGER PRIMARY KEY AUTOINCREMENT,
user_id INTEGER NOT NULL,
username TEXT NOT NULL,
display_name TEXT NOT NULL,
text_content TEXT NOT NULL,
text_length INTEGER NOT NULL,
engine TEXT NOT NULL,
emotion TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
FOREIGN KEY (user_id) REFERENCES users(id)
);
''')
# 创建默认 admin 账号(如不存在)
existing = cursor.execute(
'SELECT id FROM users WHERE username = ?', ('simonkoson',)
).fetchone()
if not existing:
cursor.execute(
'INSERT INTO users (username, display_name, password_hash, role) VALUES (?, ?, ?, ?)',
('simonkoson', '蓝皓', generate_password_hash('liutong65'), 'admin')
)
conn.commit()
conn.close()