-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathdatabase.py
52 lines (45 loc) · 1.5 KB
/
database.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
import MySQLdb
from weakref import WeakKeyDictionary
from configuration import Config
def get_dbcon():
db = MySQLdb.connect(host=Config.get('Database', 'Host'), user=Config.get('Database', 'User'), passwd=Config.get('Database', 'Password'), db=Config.get('Database', 'Database'), charset='utf8')
cur = db.cursor()
cur.execute('SET NAMES utf8mb4')
return db, cur
def dbcur_queryone(cur, query, args = (), default = None):
cur.execute(query, args)
row = cur.fetchone()
if row and (row[0] is not None):
return row[0]
return default
def dbcur_queryrow(cur, query, args = (), default = None):
cur.execute(query, args)
row = cur.fetchone()
if row is None:
return default
return row
cursor_oncommit = WeakKeyDictionary()
def with_cursor(infun):
def outfun(*args, **kwargs):
db = MySQLdb.connect(
host=Config.get('Database', 'Host'),
user=Config.get('Database', 'User'),
passwd=Config.get('Database', 'Password'),
db=Config.get('Database', 'Database'),
charset='utf8')
try:
cur = db.cursor()
cur.execute('SET NAMES utf8mb4')
ret = infun(cur, *args, **kwargs)
db.commit()
if cur in cursor_oncommit:
for act in cursor_oncommit[cur]:
act[0][act[1]] = act[2]
return ret
finally:
db.close()
return outfun
def cache_on_commit(cursor, cachedict, cachekey, cacheval):
if cursor not in cursor_oncommit:
cursor_oncommit[cursor] = []
cursor_oncommit[cursor].append((cachedict, cachekey, cacheval))