-
Notifications
You must be signed in to change notification settings - Fork 21
/
Copy pathdb_utils.py
70 lines (62 loc) · 2.1 KB
/
db_utils.py
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
69
70
# db_utils.py
import sqlite3
import os
from contextlib import contextmanager
conn = sqlite3.connect('app.db', check_same_thread=False)
# 新增上下文管理器
@contextmanager
def get_cursor():
cursor = conn.cursor()
try:
yield cursor
conn.commit() # 自动提交事务
finally:
cursor.close() # 自动关闭游标
def initialize_database():
with get_cursor() as c: # 使用上下文管理器
c.execute('''
CREATE TABLE IF NOT EXISTS history (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT NOT NULL,
session_id TEXT UNIQUE,
session_name TEXT,
session_data TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP,
updated_at DATETIME DEFAULT CURRENT_TIMESTAMP
)''')
c.execute('''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
password_hash TEXT,
is_admin BOOLEAN DEFAULT 0,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)''')
c.execute('''
CREATE TABLE IF NOT EXISTS api_keys (
id INTEGER PRIMARY KEY AUTOINCREMENT,
key TEXT UNIQUE,
username TEXT,
used_tokens INTEGER DEFAULT 0,
total_tokens INTEGER DEFAULT 0,
is_active BOOLEAN DEFAULT 1,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)''')
c.execute('''
CREATE TABLE IF NOT EXISTS blacklist (
id INTEGER PRIMARY KEY AUTOINCREMENT,
username TEXT UNIQUE,
reason TEXT,
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)''')
c.execute('''
CREATE TABLE IF NOT EXISTS api_configurations (
id INTEGER PRIMARY KEY AUTOINCREMENT,
config_name TEXT UNIQUE,
base_url TEXT,
api_key TEXT,
is_active BOOLEAN DEFAULT 0,
model_name TEXT DEFAULT 'deepseek-r1',
created_at DATETIME DEFAULT CURRENT_TIMESTAMP
)''')
initialize_database()