forked from Boris-code/feapder
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmysqldb.py
More file actions
381 lines (323 loc) · 9.95 KB
/
mysqldb.py
File metadata and controls
381 lines (323 loc) · 9.95 KB
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
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
# -*- coding: utf-8 -*-
"""
Created on 2016-11-16 16:25
---------
@summary: 操作mysql数据库
---------
@author: Boris
@email: boris_liu@foxmail.com
"""
import datetime
import json
from urllib import parse
from typing import List, Dict
import pymysql
from dbutils.pooled_db import PooledDB
from pymysql import cursors
from pymysql import err
import feapder.setting as setting
from feapder.utils.log import log
from feapder.utils.tools import make_insert_sql, make_batch_sql, make_update_sql
def auto_retry(func):
def wapper(*args, **kwargs):
for i in range(3):
try:
return func(*args, **kwargs)
except (err.InterfaceError, err.OperationalError) as e:
log.error(
"""
error:%s
sql: %s
"""
% (e, kwargs.get("sql") or args[1])
)
return wapper
class MysqlDB:
def __init__(
self, ip=None, port=None, db=None, user_name=None, user_pass=None, **kwargs
):
# 可能会改setting中的值,所以此处不能直接赋值为默认值,需要后加载赋值
if not ip:
ip = setting.MYSQL_IP
if not port:
port = setting.MYSQL_PORT
if not db:
db = setting.MYSQL_DB
if not user_name:
user_name = setting.MYSQL_USER_NAME
if not user_pass:
user_pass = setting.MYSQL_USER_PASS
try:
self.connect_pool = PooledDB(
creator=pymysql,
mincached=1,
maxcached=100,
maxconnections=100,
blocking=True,
ping=7,
host=ip,
port=port,
user=user_name,
passwd=user_pass,
db=db,
charset="utf8mb4",
cursorclass=cursors.SSCursor,
) # cursorclass 使用服务的游标,默认的在多线程下大批量插入数据会使内存递增
except Exception as e:
log.error(
"""
连接失败:
ip: {}
port: {}
db: {}
user_name: {}
user_pass: {}
exception: {}
""".format(
ip, port, db, user_name, user_pass, e
)
)
else:
log.debug("连接到mysql数据库 %s : %s" % (ip, db))
@classmethod
def from_url(cls, url, **kwargs):
# mysql://username:password@ip:port/db?charset=utf8mb4
url_parsed = parse.urlparse(url)
db_type = url_parsed.scheme.strip()
if db_type != "mysql":
raise Exception(
"url error, expect mysql://username:ip:port/db?charset=utf8mb4, but get {}".format(
url
)
)
connect_params = {
"ip": url_parsed.hostname.strip(),
"port": url_parsed.port,
"user_name": url_parsed.username.strip(),
"user_pass": url_parsed.password.strip(),
"db": url_parsed.path.strip("/").strip(),
}
connect_params.update(kwargs)
return cls(**connect_params)
@staticmethod
def unescape_string(value):
if not isinstance(value, str):
return value
value = value.replace("\\0", "\0")
value = value.replace("\\\\", "\\")
value = value.replace("\\n", "\n")
value = value.replace("\\r", "\r")
value = value.replace("\\Z", "\032")
value = value.replace('\\"', '"')
value = value.replace("\\'", "'")
return value
def get_connection(self):
conn = self.connect_pool.connection(shareable=False)
# cursor = conn.cursor(cursors.SSCursor)
cursor = conn.cursor()
return conn, cursor
def close_connection(self, conn, cursor):
cursor.close()
conn.close()
def size_of_connections(self):
"""
当前活跃的连接数
@return:
"""
return self.connect_pool._connections
def size_of_connect_pool(self):
"""
池子里一共有多少连接
@return:
"""
return len(self.connect_pool._idle_cache)
@auto_retry
def find(self, sql, limit=0, to_json=False):
"""
@summary:
无数据: 返回()
有数据: 若limit == 1 则返回 (data1, data2)
否则返回 ((data1, data2),)
---------
@param sql:
@param limit:
@param to_json 是否将查询结果转为json
---------
@result:
"""
conn, cursor = self.get_connection()
cursor.execute(sql)
if limit == 1:
result = cursor.fetchone() # 全部查出来,截取 不推荐使用
elif limit > 1:
result = cursor.fetchmany(limit) # 全部查出来,截取 不推荐使用
else:
result = cursor.fetchall()
if to_json:
columns = [i[0] for i in cursor.description]
# 处理数据
def convert(col):
if isinstance(col, (datetime.date, datetime.time)):
return str(col)
elif isinstance(col, str) and (
col.startswith("{") or col.startswith("[")
):
try:
# col = self.unescape_string(col)
return json.loads(col)
except:
return col
else:
# col = self.unescape_string(col)
return col
if limit == 1:
result = [convert(col) for col in result]
result = dict(zip(columns, result))
else:
result = [[convert(col) for col in row] for row in result]
result = [dict(zip(columns, r)) for r in result]
self.close_connection(conn, cursor)
return result
def add(self, sql, exception_callfunc=None):
"""
Args:
sql:
exception_callfunc: 异常回调
Returns: 添加行数
"""
affect_count = None
try:
conn, cursor = self.get_connection()
affect_count = cursor.execute(sql)
conn.commit()
except Exception as e:
log.error(
"""
error:%s
sql: %s
"""
% (e, sql)
)
if exception_callfunc:
exception_callfunc(e)
finally:
self.close_connection(conn, cursor)
return affect_count
def add_smart(self, table, data: Dict, **kwargs):
"""
添加数据, 直接传递json格式的数据,不用拼sql
Args:
table: 表名
data: 字典 {"xxx":"xxx"}
**kwargs:
Returns: 添加行数
"""
sql = make_insert_sql(table, data, **kwargs)
return self.add(sql)
def add_batch(self, sql, datas: List[Dict]):
"""
@summary: 批量添加数据
---------
@ param sql: insert ignore into (xxx,xxx) values (%s, %s, %s)
# param datas: 列表 [{}, {}, {}]
---------
@result: 添加行数
"""
affect_count = None
try:
conn, cursor = self.get_connection()
affect_count = cursor.executemany(sql, datas)
conn.commit()
except Exception as e:
log.error(
"""
error:%s
sql: %s
"""
% (e, sql)
)
finally:
self.close_connection(conn, cursor)
return affect_count
def add_batch_smart(self, table, datas: List[Dict], **kwargs):
"""
批量添加数据, 直接传递list格式的数据,不用拼sql
Args:
table: 表名
datas: 列表 [{}, {}, {}]
**kwargs:
Returns: 添加行数
"""
sql, datas = make_batch_sql(table, datas, **kwargs)
return self.add_batch(sql, datas)
def update(self, sql):
try:
conn, cursor = self.get_connection()
cursor.execute(sql)
conn.commit()
except Exception as e:
log.error(
"""
error:%s
sql: %s
"""
% (e, sql)
)
return False
else:
return True
finally:
self.close_connection(conn, cursor)
def update_smart(self, table, data: Dict, condition):
"""
更新, 不用拼sql
Args:
table: 表名
data: 数据 {"xxx":"xxx"}
condition: 更新条件 where后面的条件,如 condition='status=1'
Returns: True / False
"""
sql = make_update_sql(table, data, condition)
return self.update(sql)
def delete(self, sql):
"""
删除
Args:
sql:
Returns: True / False
"""
try:
conn, cursor = self.get_connection()
cursor.execute(sql)
conn.commit()
except Exception as e:
log.error(
"""
error:%s
sql: %s
"""
% (e, sql)
)
return False
else:
return True
finally:
self.close_connection(conn, cursor)
def execute(self, sql):
try:
conn, cursor = self.get_connection()
cursor.execute(sql)
conn.commit()
except Exception as e:
log.error(
"""
error:%s
sql: %s
"""
% (e, sql)
)
return False
else:
return True
finally:
self.close_connection(conn, cursor)