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
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
|
base.py
from functools import wraps
from sqlalchemy.orm.query import Query
from sqlalchemy.engine import create_engine
from sqlalchemy.ext.declarative import declarative_base, declared_attr, as_declarative
from sqlalchemy.orm.session import sessionmaker
from sqlalchemy.ext.declarative import AbstractConcreteBase
from contextlib import contextmanager
from sqlalchemy import inspect
class Config(object):
SQLALCHEMY_DATABASE_URI = "mysql+pymysql://{}:{}@{}".format("user", "pwd", "url")
SQLALCHEMY_TRACK_MODIFICATIONS = False
SQLALCHEMY_POOL_SIZE = 1
SQLALCHEMY_MAX_OVERFLOW = 0
SQLALCHEMY_POOL_RECYCLE = 100
engine = create_engine(Config.SQLALCHEMY_DATABASE_URI, convert_unicode=True,
pool_size=Config.SQLALCHEMY_POOL_SIZE, max_overflow=Config.SQLALCHEMY_MAX_OVERFLOW,
pool_recycle=Config.SQLALCHEMY_POOL_RECYCLE)
Session = sessionmaker(bind=engine)
def close_session(fn):
@wraps(fn)
def close(obj, *args, **kwargs):
obj.session = Session()
res = fn(obj, *args, **kwargs)
obj.session.close()
return res
return close
class DataQuery(Query):
@close_session
def get(self, *args, **kwargs):
"""增加关闭的功能"""
return super(DataQuery, self).get(*args, **kwargs)
@close_session
def first(self):
return super(DataQuery, self).first()
@close_session
def all(self):
return super(DataQuery, self).all()
Base = declarative_base()
class DataModel(AbstractConcreteBase, Base):
"""table映射的基类"""
@classmethod
def query(cls):
""""""
return DataQuery(cls)
def to_dict(self):
return {k: getattr(self, k) for k in inspect(type(self)).c.keys()}
@contextmanager
def get_session(autocommit=False, **kwargs):
""""""
s = Session(autocommit=autocommit, **kwargs)
try:
if autocommit:
s.begin()
yield s
s.commit()
except Exception as e:
s.rollback()
raise e
finally:
s.close()
@contextmanager
def get_connect(**kwargs):
connect = engine.connect(**kwargs)
try:
yield connect
finally:
connect.close()
op.py
from database.base import get_session
from database.db_model import BaseGoodsCorrect
import logging
import traceback
from datetime import datetime
_logger = logging.getLogger('database')
class BaseOP(object):
def add(self, **kwargs):
"""
:param kwargs:
:return:
"""
try:
create_time = datetime.now()
kwargs.update({"create_time": create_time})
kwargs.update({"update_time": create_time})
goods_persistence = BaseGoodsCorrect(**kwargs)
with get_session(autocommit=True) as sess:
sess.add(goods_persistence)
except Exception as e:
_logger.error('持久化失败,请检查数据格式: %s' % kwargs['pid'])
traceback.print_exc()
def add_all(self, data):
"""
:param kwargs:
:return:
"""
try:
create_time = datetime.now()
temp = []
for i in data:
i.update({"create_time": create_time})
i.update({"update_time": create_time})
goods_persistence = BaseGoodsCorrect(**i)
temp.append(goods_persistence)
with get_session(autocommit=True) as sess:
sess.add_all(temp)
except Exception as e:
_logger.error('持久化失败,请检查数据格式')
traceback.print_exc()
def delete_by_id(self, pid):
"""
根据id删除会话
:param pid: pid
:return:
"""
try:
with get_session() as sess:
sess.query(BaseGoodsCorrect).filter_by(pid=pid).delete()
except Exception as e:
traceback.print_exc()
def get_by_id(self, pid):
"""
根据id获取结果
:param pid: pid
:return:
"""
try:
with get_session(autocommit=True) as sess:
res = sess.query(BaseGoodsCorrect).filter_by(pid=pid).first().to_dict()
if res is None:
return None
else:
return res
except Exception as e:
traceback.print_exc()
return 'err'
def get_all(self):
"""
获取所有结果
:return:
"""
try:
with get_session(autocommit=True) as sess:
res = sess.query(BaseGoodsCorrect).all()
if res is None:
return None
else:
return res
except Exception as e:
traceback.print_exc()
return 'err'
def get_data_offset(self, start, end):
"""
分页获取所有结果
:return:
"""
data = []
try:
with get_session(autocommit=True) as sess:
res = sess.query(BaseGoodsCorrect).order_by(BaseGoodsCorrect.id.asc())[start: end]
for r in res:
r = r.to_dict()
data.append(r)
if res is None:
return None
else:
return data
except Exception as e:
traceback.print_exc()
return 'err'
def get_count(self):
"""
获取行数
:return:
"""
try:
with get_session(autocommit=True) as sess:
res = sess.query(BaseGoodsCorrect).count()
if res is None:
return None
else:
return res
except Exception as e:
traceback.print_exc()
return 'err'
|