-
Notifications
You must be signed in to change notification settings - Fork 0
/
common.py
85 lines (72 loc) · 2.37 KB
/
common.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
import os
import configparser
import time
import pickle
def StrNone(arg):
if arg is None:
return "None"
else:
return str(arg)
######################################################################################
class Timer:
def __init__(self):
self.starts = {}
self.cumm = {}
def __del__(self):
print("Timers:")
for key, val in self.cumm.items():
print(key, "\t", val)
def Start(self, str):
self.starts[str] = time.time()
def Pause(self, str):
now = time.time()
then = self.starts[str]
if str in self.cumm:
self.cumm[str] += now - then
else:
self.cumm[str] = now - then
######################################################################################
class MySQL:
def __init__(self, config_file):
import mysql.connector
config = configparser.ConfigParser()
config.read(config_file)
self.mydb = mysql.connector.connect(
host=config["mysql"]["host"],
user=config["mysql"]["user"],
passwd=config["mysql"]["password"],
database=config["mysql"]["database"],
charset='utf8'
)
self.mydb.autocommit = False
self.mycursor = self.mydb.cursor(buffered=True)
######################################################################################
def GetLanguages(configFile):
filePath = 'pickled_domains/Languages'
if not os.path.exists(filePath):
print("mysql load Languages")
sqlconn = MySQL(configFile)
languages = Languages(sqlconn)
with open(filePath, 'wb') as f:
pickle.dump(languages, f)
else:
print("unpickle Languages")
with open(filePath, 'rb') as f:
languages = pickle.load(f)
return languages
######################################################################################
class Languages:
def __init__(self, sqlconn):
self.coll = {}
sql = "SELECT id, lang FROM language"
sqlconn.mycursor.execute(sql)
ress = sqlconn.mycursor.fetchall()
assert (ress is not None)
for res in ress:
self.coll[res[1]] = res[0]
self.maxLangId = res[0]
def GetLang(self, str):
str = StrNone(str)
assert(str in self.coll)
return self.coll[str]
# print("GetLang", str)