-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathutil.py
58 lines (46 loc) · 1.36 KB
/
util.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
from mail import mail
import pymysql # pip install pymysql
import logging
import warnings
warnings.filterwarnings('error', category=pymysql.Warning)
class CM(object):
''' connection manager '''
def __init__(self):
self.connection = None
def set_credentials(self, credentials):
self.credentials = credentials
self.close()
def get_conn(self):
if not self.connection:
logging.info('no db connection. creating...')
self.connection = pymysql.connect(**self.credentials)
return self.connection
def close(self):
if self.connection:
self.connection.close()
self.connection = None
cm = CM()
def exec_mysql(sql, retries=2):
try:
cur = None # needed in case get_conn() dies
db = cm.get_conn()
cur = db.cursor()
cur.execute(sql)
rows = [r for r in cur.fetchall()]
if not rows and not sql.strip().lower().startswith('select'):
rows = cur.rowcount
cur.close()
db.commit()
return rows
except pymysql.OperationalError:
if cur:
cur.close()
cm.close()
if retries:
logging.warning('sql query failed, retrying')
return exec_mysql(sql, retries-1)
else:
raise
except:
logging.error(sql)
raise