-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathdb_handler.py
87 lines (76 loc) · 2.42 KB
/
db_handler.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
from settings import user, passwd, database
import mysql.connector
#from mysql.connector import Error
import threading
some_lock = threading.Lock()
print("start")
class MySQL_DB():
print("class")
#"""Database interface"""
def __init__(self):
self.connect_mysql()
pass
def retry(func):
print ("Retry")
def wrapper(self, *args, **kwargs):
with some_lock:
try:
return func(self, *args, **kwargs)
except Exception as e:
print ("--->{}".format(e))
self.connect_mysql()
else:
# No need to retry for other reasons
pass
return func(self, *args, **kwargs)
print("exit retry")
return wrapper
def connect_mysql(self):
print ("connect")
# do connection
self.con = mysql.connector.connect(
#host='localhost',
unix_socket="/run/mysqld/mysqld.sock",
user=user,
passwd=passwd,
database=database,
use_unicode=True
)
if (self.con.is_connected()):
self.cursor = self.con.cursor()
self.cursor.execute("SET NAMES utf8mb4")
self.cursor.execute("SET CHARACTER SET utf8mb4")
self.cursor.execute("SET character_set_connection=utf8mb4")
print("conectado")
return self
# @retry
# def get_quote(self):
# print("[!][get_quote]")
# query = "SELECT text FROM lauters ORDER BY RAND() LIMIT 1"
# self.execute(query)
# row = self.cursor.fetchone()
# print("__{}__".format(row[0]))
@retry
def fetchall(self, query):
self.cursor.execute(query)
return self.cursor.fetchall()
@retry
def fetchone(self, query):
self.cursor.execute(query)
return self.cursor.fetchone()
@retry
def execute(self, query):
self.cursor.execute(query)
return self.con.commit()
def __exit__(self):
# do something
if (self.con.is_connected()):
self.cursor.close()
self.con.close()
print("Deu pau")
if __name__ == "__main__":
import time
db = MySQL_DB()
#db.get_quote()
time.sleep(5)
db.get_quote()