-
Notifications
You must be signed in to change notification settings - Fork 0
/
db.py
177 lines (129 loc) · 5.24 KB
/
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
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
import pymysql.cursors
import redis
import pandas as pd
import os
import sys
sys.path.append(os.path.abspath(os.path.dirname(os.path.dirname(__file__))))
from src._conf_lib import CONFIG
from sqlalchemy.ext.automap import automap_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import MetaData, inspect, create_engine, event
from sqlalchemy import Table
from sqlalchemy.exc import DisconnectionError
def checkout_listener(dbapi_con, con_record, con_proxy):
try:
try:
dbapi_con.ping(False)
except TypeError:
dbapi_con.ping()
except dbapi_con.OperationalError as exc:
if exc.args[0] in (2006, 2013, 2014, 2045, 2055):
raise DisconnectionError()
else:
raise
class HandleMysql:
def __init__(self, conf):
self.cur = None
self.conn = None
# print(conf)
self.data = conf.get('DB',dict())
self.connMyql()
def connMyql(self):
"""连接数据库"""
host = self.data.get("HOST", '127.0.0.1')
user = self.data.get("USER", 'root')
password = self.data.get("PASSWORD", '123')
db = self.data.get("DB_NAME", 'ceobe_canteen')
port = self.data.get("PORT", 3306)
charset = self.data.get("CHARSET", 'utf8mb4')
self.engine = create_engine('mysql+pymysql://{}:{}@{}:{}/{}?charset={}'.format(
user, password, host, port, db, charset), pool_size=100, pool_recycle=600, pool_pre_ping=True)
self.metadata = MetaData(bind=self.engine)
def sessMyql(self):
Session = sessionmaker(self.engine)
db_session = Session()
return db_session
def queryMyql(self, table_name=''):
'''
封装查询步骤, 每次重新启动session; 如果失败最多重试3次.
'''
max_retry = 3
success_mark = False
while max_retry > 0 and not success_mark:
try:
db_session = self.sessMyql()
table = Table(table_name, self.metadata, autoload=True, autoload_with=self.engine)
db_query = db_session.query(table)
db_session.close()
success_mark = True
except:
max_retry -= 1
return db_query, table
class HandleRedis:
def __init__(self, conf):
conf = conf['REDIS']
self.host = conf.get('HOST', 'localhost')
self.port = int(conf.get('PORT', 6379))
self.db = int(conf.get('DB', 0))
self.password = conf.get('PASSWORD', 0)
self.conn = redis.StrictRedis(host=self.host, port=self.port, db=self.db, password=self.password)
def get(self, name):
return self.conn.get(name)
def set(self, name, value):
return self.conn.set(name, value)
sql_client = HandleMysql(CONFIG)
event.listen(sql_client.engine, 'checkout', checkout_listener)
def fetch_col_names(table_name_list) -> dict:
output_dict = dict()
# 反射获取数据表meta信息.
for table_name in table_name_list:
_, table = sql_client.queryMyql(table_name)
output_dict[table_name] = list(table.columns.keys())
return output_dict
table_name_list = ['fetcher_datasource_config',
'fetcher_config',
'fetcher_global_config',
'fetcher_platform_config']
table_col_names = fetch_col_names(table_name_list)
def select_fetcher_config(platform='') -> pd.DataFrame:
table_name = 'fetcher_config'
db_query, table = sql_client.queryMyql(table_name)
if platform:
content = db_query.filter(table.columns.platform == platform).all()
else:
content = db_query.all()
df = pd.DataFrame(content, columns=table_col_names[table_name])
return df
def select_fetcher_global_config() -> pd.DataFrame:
table_name = 'fetcher_global_config'
db_query, table = sql_client.queryMyql(table_name)
content = db_query.all()
df = pd.DataFrame(content, columns=table_col_names[table_name])
return df
def select_fetcher_platform_config(platform='') -> pd.DataFrame:
table_name = 'fetcher_platform_config'
db_query, table = sql_client.queryMyql(table_name)
if platform:
content = db_query.filter(table.columns.platform == platform).all()
else:
content = db_query.all()
df = pd.DataFrame(content, columns=table_col_names[table_name])
return df
def select_fetcher_datasource_config(platform='') -> pd.DataFrame:
table_name = 'fetcher_datasource_config'
db_query, table = sql_client.queryMyql(table_name)
if platform:
content = db_query.filter(table.columns.platform == platform).all()
else:
content = db_query.all()
df = pd.DataFrame(content, columns=table_col_names[table_name])
return df
if __name__ == '__main__':
# r = HandleRedis(dict())
# r.set('a', 'b')
# print(r.get('a')) # ✓
print(sql_client.executeSql('select * from fetcher_datasource_config'))
fetcher_datasource_config_df = select_fetcher_datasource_config(platform='bilibili')
fetcher_config_df = select_fetcher_config()
fetcher_global_config_df = select_fetcher_global_config()
fetcher_platform_config_df = select_fetcher_platform_config()