application.py 2.19 KB
Newer Older
Vladislav Rykov's avatar
Vladislav Rykov committed
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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
import psycopg2
import bcrypt
from misc import rand_str

APP_KEY_LEN = 8

class ApplicationDao:
    
    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, username, desc):
        query = """
        INSERT INTO
            applications
        VALUES
            (%s, %s, %s, %s)
        """
        cur.execute(query, (name, rand_str(APP_KEY_LEN), username, desc))
        
        return (True,)

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

    @staticmethod
    @with_psql
    def get(cur, appkey):
        query = """
        SELECT * FROM
            applications
        WHERE
            app_key = %s
        """
        cur.execute(query, (appkey,))
        app = cur.fetchone()

        if app is None:
            return (False, 'Application with key {} does not exist'.format(appkey))
        else:
            return (True, app)

    
    @staticmethod
    @with_psql
    def get_list(cur, username):
        query = """
        SELECT * FROM
            applications
        WHERE
            username = %s
        """
        cur.execute(query, (username,))

        return (True, cur.fetchall())

    @staticmethod
    @with_psql
    def update(cur, appkey, name, desc):
        query = """
        UPDATE
            applications
        SET
            name = %s,
            description = %s,
        WHERE
            app_key = %s
        """
        cur.execute(query, (name, desc, appkey))

        return (True,)