-
Notifications
You must be signed in to change notification settings - Fork 30
/
models.py
88 lines (68 loc) · 1.94 KB
/
models.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
#!/usr/bin/env python3
# vim: set fileencoding=utf-8:
import sqlite3
import logging
import time
from config import DB
#
__all__ = ['model']
#
def log(fn):
def wrapped(*args, **kwds):
try:
return fn(*args, **kwds)
except Exception as e:
logging.warning(e)
return wrapped
def dict_factory(cursor, row):
d = {}
for idx, col in enumerate(cursor.description):
d[col[0]] = row[idx]
return d
#
class Model:
def __init__(self, db):
self.conn = sqlite3.connect(db)
self.conn.row_factory = dict_factory
self.cur = self.conn.cursor()
@log
def get_user_by_id(self, id):
row = self.cur.execute('select * from user where id=?', (id,))
return row.fetchone()
@log
def get_user_by_ip(self, ip):
row = self.cur.execute('select * from user where ip=?', (ip,))
return row.fetchone()
@log
def get_image_by_name(self, name):
row = self.cur.execute('select * from image where name=?', (name,))
return row.fetchone()
@log
def get_image_by_uid(self, uid):
row = self.cur.execute('select * from image where uid=?', (uid,))
return row.fetchall()
@log
def add_user(self, ip):
self.cur.execute('insert into user(ip) values (?)', (ip,))
self.conn.commit()
return self.cur.lastrowid
@log
def add_image(self, uid, fname, filename, size):
self.cur.execute('''insert into image (uid, name, time, filename, size)
values (?, ?, ?, ?, ?)''',
(uid, fname, int(time.time()), filename, size))
self.conn.commit()
@log
def block_user(self, id, block=1):
self.cur.execute('update user set blocked=? where id=?', (block, id))
self.conn.commit()
unblock_user = lambda self, id: self.block_user(id, block=0)
def isBlocked(self, type, data):
method = getattr(self, 'get_user_by_'+type, None)
if callable(method):
row = method(data)
return row['blocked'] == 1
else:
return None
#
model = Model(DB)