-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain_db.py
132 lines (113 loc) · 3.46 KB
/
main_db.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
import os
import threading
from sqlalchemy import create_engine, text
from sqlalchemy.orm import sessionmaker, scoped_session
from sqlalchemy.pool import QueuePool
from app.db.models import Base
from app.utils import ExceptionUtils, PathUtils
from config import Config
lock = threading.Lock()
_Engine = create_engine(
f"sqlite:///{os.path.join(Config().get_config_path(), 'user.db')}?check_same_thread=False",
echo=False,
poolclass=QueuePool,
pool_pre_ping=True,
pool_size=100,
pool_recycle=60 * 10,
max_overflow=0
)
_Session = scoped_session(sessionmaker(bind=_Engine,
autoflush=True,
autocommit=False,
expire_on_commit=False))
class MainDb:
@property
def session(self):
return _Session()
def init_db(self):
with lock:
Base.metadata.create_all(_Engine)
self.init_db_version()
def init_db_version(self):
"""
初始化数据库版本
"""
try:
self.excute("delete from alembic_version where 1")
self.commit()
except Exception as err:
print(str(err))
def init_data(self):
"""
读取config目录下的sql文件,并初始化到数据库,只处理一次
"""
config = Config().get_config()
init_files = Config().get_config("app").get("init_files") or []
config_dir = Config().get_script_path()
sql_files = PathUtils.get_dir_level1_files(in_path=config_dir, exts=".sql")
config_flag = False
for sql_file in sql_files:
if os.path.basename(sql_file) not in init_files:
config_flag = True
with open(sql_file, "r", encoding="utf-8") as f:
sql_list = f.read().split(';\n')
for sql in sql_list:
try:
self.excute(sql)
self.commit()
except Exception as err:
print(str(err))
init_files.append(os.path.basename(sql_file))
if config_flag:
config['app']['init_files'] = init_files
Config().save_config(config)
def insert(self, data):
"""
插入数据
"""
if isinstance(data, list):
self.session.add_all(data)
else:
self.session.add(data)
def query(self, *obj):
"""
查询对象
"""
return self.session.query(*obj)
def excute(self, sql):
"""
执行SQL语句
"""
self.session.execute(text(sql))
def flush(self):
"""
刷写
"""
self.session.flush()
def commit(self):
"""
提交事务
"""
self.session.commit()
def rollback(self):
"""
回滚事务
"""
self.session.rollback()
class DbPersist(object):
"""
数据库持久化装饰器
"""
def __init__(self, db):
self.db = db
def __call__(self, f):
def persist(*args, **kwargs):
try:
ret = f(*args, **kwargs)
self.db.commit()
return True if ret is None else ret
except Exception as e:
ExceptionUtils.exception_traceback(e)
self.db.rollback()
return False
return persist