device.py 1.88 KB
Newer Older
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
import psycopg2
import bcrypt


class DeviceDao:
    
    def __init__(self):
        pass

    # decorator implementation
    def with_psql(f):
        def _with_psql(*args, **kwargs):
            conn = psycopg2.connect('dbname=gateway')
            cur = conn.cursor()

            try:
                res = f(cur, *args, **kwargs)
            except (Exception, psycopg2.DatabaseError) as error:
                conn.rollback()
                res = (False, error)
            else:
                conn.commit()
            finally:
                cur.close()
                conn.close()
    
            return res
        return _with_psql

    @staticmethod
    @with_psql
    def create(cur, name, dev_id, appkey, desc):
        query = """
        INSERT INTO 
            devices
        VALUES
            (%s, %s, %s, %s)
        """
        cur.execute(query, (name, dev_id, appkey, desc))
        return (True,)


    @staticmethod
    @with_psql
    def delete(cur, appkey, dev_id):
        query = """
        DELETE FROM 
            devices
        WHERE
            app_key = %s 
        AND
            dev_id = %s
        """
        cur.execute(query, (appkey, dev_id))
        return (True,)


    @staticmethod
    @with_psql
    def get(cur, appkey, dev_id):
        query = """
        SELECT * FROM
            devices
        WHERE
            app_key = %s
        AND
            dev_id = %s
        """
        cur.execute(query, (appkey, dev_id))
        dev = cur.fetchone()
        
        if (dev is None):
            return (False, 'There is no device with dev_id = {}'.format(dev_id))
        else:
            return (True, dev)


    @staticmethod
    @with_psql
    def get_list(cur, appkey):
        query = """
        SELECT * FROM
            devices
        WHERE
            app_key = %s
        """
        cur.execute(query, (appkey,))
        return (True, cur.fetchall())