Code Duplication    Length = 187-188 lines in 2 locations

myems-api/core/combinedequipment.py 1 location

@@ 10-197 (lines=188) @@
7
import config
8
9
10
class CombinedEquipmentCollection:
11
    def __init__(self):
12
        """ Initializes CombinedEquipmentCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        _=req
18
        resp.status = falcon.HTTP_200
19
20
    @staticmethod
21
    def on_get(req, resp):
22
        if 'API-KEY' not in req.headers or \
23
                not isinstance(req.headers['API-KEY'], str) or \
24
                len(str.strip(req.headers['API-KEY'])) == 0:
25
            access_control(req)
26
        else:
27
            api_key_control(req)
28
        cnx = mysql.connector.connect(**config.myems_system_db)
29
        cursor = cnx.cursor()
30
31
        query = (" SELECT id, name, uuid "
32
                 " FROM tbl_cost_centers ")
33
        cursor.execute(query)
34
        rows_cost_centers = cursor.fetchall()
35
36
        cost_center_dict = dict()
37
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
38
            for row in rows_cost_centers:
39
                cost_center_dict[row[0]] = {"id": row[0],
40
                                            "name": row[1],
41
                                            "uuid": row[2]}
42
        query = (" SELECT id, name, uuid "
43
                 " FROM tbl_svgs ")
44
        cursor.execute(query)
45
        rows_svgs = cursor.fetchall()
46
47
        svg_dict = dict()
48
        if rows_svgs is not None and len(rows_svgs) > 0:
49
            for row in rows_svgs:
50
                svg_dict[row[0]] = {"id": row[0],
51
                                    "name": row[1],
52
                                    "uuid": row[2]}
53
54
        query = (" SELECT id, name, uuid, "
55
                 "        is_input_counted, is_output_counted, "
56
                 "        cost_center_id, svg_id, camera_url, description "
57
                 " FROM tbl_combined_equipments "
58
                 " ORDER BY id ")
59
        cursor.execute(query)
60
        rows_combined_equipments = cursor.fetchall()
61
62
        result = list()
63
        if rows_combined_equipments is not None and len(rows_combined_equipments) > 0:
64
            for row in rows_combined_equipments:
65
                meta_result = {"id": row[0],
66
                               "name": row[1],
67
                               "uuid": row[2],
68
                               "is_input_counted": bool(row[3]),
69
                               "is_output_counted": bool(row[4]),
70
                               "cost_center": cost_center_dict.get(row[5], None),
71
                               "svg": svg_dict.get(row[6], None),
72
                               "camera_url": row[7],
73
                               "description": row[8],
74
                               "qrcode": 'combinedequipment:' + row[2]}
75
                result.append(meta_result)
76
77
        cursor.close()
78
        cnx.close()
79
        resp.text = json.dumps(result)
80
81
    @staticmethod
82
    @user_logger
83
    def on_post(req, resp):
84
        """Handles POST requests"""
85
        admin_control(req)
86
        try:
87
            raw_json = req.stream.read().decode('utf-8')
88
        except Exception as ex:
89
            print(ex)
90
            raise falcon.HTTPError(status=falcon.HTTP_400,
91
                                   title='API.BAD_REQUEST',
92
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
93
94
        new_values = json.loads(raw_json)
95
96
        if 'name' not in new_values['data'].keys() or \
97
                not isinstance(new_values['data']['name'], str) or \
98
                len(str.strip(new_values['data']['name'])) == 0:
99
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
100
                                   description='API.INVALID_COMBINED_EQUIPMENT_NAME')
101
        name = str.strip(new_values['data']['name'])
102
103
        if 'is_input_counted' not in new_values['data'].keys() or \
104
                not isinstance(new_values['data']['is_input_counted'], bool):
105
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
106
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
107
        is_input_counted = new_values['data']['is_input_counted']
108
109
        if 'is_output_counted' not in new_values['data'].keys() or \
110
                not isinstance(new_values['data']['is_output_counted'], bool):
111
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
112
                                   description='API.INVALID_IS_OUTPUT_COUNTED_VALUE')
113
        is_output_counted = new_values['data']['is_output_counted']
114
115
        if 'cost_center_id' not in new_values['data'].keys() or \
116
                not isinstance(new_values['data']['cost_center_id'], int) or \
117
                new_values['data']['cost_center_id'] <= 0:
118
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
119
                                   description='API.INVALID_COST_CENTER_ID')
120
        cost_center_id = new_values['data']['cost_center_id']
121
122
        if 'svg_id' in new_values['data'].keys() and \
123
                isinstance(new_values['data']['svg_id'], int) and \
124
                new_values['data']['svg_id'] > 0:
125
            svg_id = new_values['data']['svg_id']
126
        else:
127
            svg_id = None
128
129
        if 'camera_url' in new_values['data'].keys() and \
130
                new_values['data']['camera_url'] is not None and \
131
                len(str(new_values['data']['camera_url'])) > 0:
132
            camera_url = str.strip(new_values['data']['camera_url'])
133
        else:
134
            camera_url = None
135
136
        if 'description' in new_values['data'].keys() and \
137
                new_values['data']['description'] is not None and \
138
                len(str(new_values['data']['description'])) > 0:
139
            description = str.strip(new_values['data']['description'])
140
        else:
141
            description = None
142
143
        cnx = mysql.connector.connect(**config.myems_system_db)
144
        cursor = cnx.cursor()
145
146
        cursor.execute(" SELECT name "
147
                       " FROM tbl_combined_equipments "
148
                       " WHERE name = %s ", (name,))
149
        if cursor.fetchone() is not None:
150
            cursor.close()
151
            cnx.close()
152
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
153
                                   description='API.COMBINED_EQUIPMENT_NAME_IS_ALREADY_IN_USE')
154
155
        if cost_center_id is not None:
156
            cursor.execute(" SELECT name "
157
                           " FROM tbl_cost_centers "
158
                           " WHERE id = %s ",
159
                           (new_values['data']['cost_center_id'],))
160
            row = cursor.fetchone()
161
            if row is None:
162
                cursor.close()
163
                cnx.close()
164
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
165
                                       description='API.COST_CENTER_NOT_FOUND')
166
167
        if svg_id is not None:
168
            cursor.execute(" SELECT name "
169
                           " FROM tbl_svgs "
170
                           " WHERE id = %s ",
171
                           (svg_id,))
172
            row = cursor.fetchone()
173
            if row is None:
174
                cursor.close()
175
                cnx.close()
176
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
177
                                       description='API.SVG_NOT_FOUND')
178
179
        add_values = (" INSERT INTO tbl_combined_equipments "
180
                      "    (name, uuid, is_input_counted, is_output_counted, "
181
                      "     cost_center_id, svg_id, camera_url, description) "
182
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ")
183
        cursor.execute(add_values, (name,
184
                                    str(uuid.uuid4()),
185
                                    is_input_counted,
186
                                    is_output_counted,
187
                                    cost_center_id,
188
                                    svg_id,
189
                                    camera_url,
190
                                    description))
191
        new_id = cursor.lastrowid
192
        cnx.commit()
193
        cursor.close()
194
        cnx.close()
195
196
        resp.status = falcon.HTTP_201
197
        resp.location = '/combinedequipments/' + str(new_id)
198
199
200
class CombinedEquipmentItem:

myems-api/core/equipment.py 1 location

@@ 10-196 (lines=187) @@
7
import config
8
9
10
class EquipmentCollection:
11
    def __init__(self):
12
        """Initializes EquipmentCollection"""
13
        pass
14
15
    @staticmethod
16
    def on_options(req, resp):
17
        resp.status = falcon.HTTP_200
18
19
    @staticmethod
20
    def on_get(req, resp):
21
        if 'API-KEY' not in req.headers or \
22
                not isinstance(req.headers['API-KEY'], str) or \
23
                len(str.strip(req.headers['API-KEY'])) == 0:
24
            access_control(req)
25
        else:
26
            api_key_control(req)
27
        cnx = mysql.connector.connect(**config.myems_system_db)
28
        cursor = cnx.cursor()
29
30
        query = (" SELECT id, name, uuid "
31
                 " FROM tbl_cost_centers ")
32
        cursor.execute(query)
33
        rows_cost_centers = cursor.fetchall()
34
35
        cost_center_dict = dict()
36
        if rows_cost_centers is not None and len(rows_cost_centers) > 0:
37
            for row in rows_cost_centers:
38
                cost_center_dict[row[0]] = {"id": row[0],
39
                                            "name": row[1],
40
                                            "uuid": row[2]}
41
42
        query = (" SELECT id, name, uuid "
43
                 " FROM tbl_svgs ")
44
        cursor.execute(query)
45
        rows_svgs = cursor.fetchall()
46
47
        svg_dict = dict()
48
        if rows_svgs is not None and len(rows_svgs) > 0:
49
            for row in rows_svgs:
50
                svg_dict[row[0]] = {"id": row[0],
51
                                    "name": row[1],
52
                                    "uuid": row[2]}
53
54
        query = (" SELECT id, name, uuid, "
55
                 "        is_input_counted, is_output_counted, "
56
                 "        cost_center_id, svg_id, camera_url, description "
57
                 " FROM tbl_equipments "
58
                 " ORDER BY id ")
59
        cursor.execute(query)
60
        rows_equipments = cursor.fetchall()
61
62
        result = list()
63
        if rows_equipments is not None and len(rows_equipments) > 0:
64
            for row in rows_equipments:
65
                meta_result = {"id": row[0],
66
                               "name": row[1],
67
                               "uuid": row[2],
68
                               "is_input_counted": bool(row[3]),
69
                               "is_output_counted": bool(row[4]),
70
                               "cost_center": cost_center_dict.get(row[5], None),
71
                               "svg": svg_dict.get(row[6], None),
72
                               "camera_url": row[7],
73
                               "description": row[8],
74
                               "qrcode": 'equipment:' + row[2]}
75
                result.append(meta_result)
76
77
        cursor.close()
78
        cnx.close()
79
        resp.text = json.dumps(result)
80
81
    @staticmethod
82
    @user_logger
83
    def on_post(req, resp):
84
        """Handles POST requests"""
85
        admin_control(req)
86
        try:
87
            raw_json = req.stream.read().decode('utf-8')
88
        except Exception as ex:
89
            raise falcon.HTTPError(status=falcon.HTTP_400,
90
                                   title='API.BAD_REQUEST',
91
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
92
93
        new_values = json.loads(raw_json)
94
95
        if 'name' not in new_values['data'].keys() or \
96
                not isinstance(new_values['data']['name'], str) or \
97
                len(str.strip(new_values['data']['name'])) == 0:
98
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
99
                                   description='API.INVALID_EQUIPMENT_NAME')
100
        name = str.strip(new_values['data']['name'])
101
102
        if 'is_input_counted' not in new_values['data'].keys() or \
103
                not isinstance(new_values['data']['is_input_counted'], bool):
104
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
105
                                   description='API.INVALID_IS_INPUT_COUNTED_VALUE')
106
        is_input_counted = new_values['data']['is_input_counted']
107
108
        if 'is_output_counted' not in new_values['data'].keys() or \
109
                not isinstance(new_values['data']['is_output_counted'], bool):
110
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
111
                                   description='API.INVALID_IS_OUTPUT_COUNTED_VALUE')
112
        is_output_counted = new_values['data']['is_output_counted']
113
114
        if 'cost_center_id' not in new_values['data'].keys() or \
115
                not isinstance(new_values['data']['cost_center_id'], int) or \
116
                new_values['data']['cost_center_id'] <= 0:
117
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
118
                                   description='API.INVALID_COST_CENTER_ID')
119
        cost_center_id = new_values['data']['cost_center_id']
120
121
        if 'svg_id' in new_values['data'].keys() and \
122
                isinstance(new_values['data']['svg_id'], int) and \
123
                new_values['data']['svg_id'] > 0:
124
            svg_id = new_values['data']['svg_id']
125
        else:
126
            svg_id = None
127
128
        if 'camera_url' in new_values['data'].keys() and \
129
                new_values['data']['camera_url'] is not None and \
130
                len(str(new_values['data']['camera_url'])) > 0:
131
            camera_url = str.strip(new_values['data']['camera_url'])
132
        else:
133
            camera_url = None
134
135
        if 'description' in new_values['data'].keys() and \
136
                new_values['data']['description'] is not None and \
137
                len(str(new_values['data']['description'])) > 0:
138
            description = str.strip(new_values['data']['description'])
139
        else:
140
            description = None
141
142
        cnx = mysql.connector.connect(**config.myems_system_db)
143
        cursor = cnx.cursor()
144
145
        cursor.execute(" SELECT name "
146
                       " FROM tbl_equipments "
147
                       " WHERE name = %s ", (name,))
148
        if cursor.fetchone() is not None:
149
            cursor.close()
150
            cnx.close()
151
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
152
                                   description='API.EQUIPMENT_NAME_IS_ALREADY_IN_USE')
153
154
        if cost_center_id is not None:
155
            cursor.execute(" SELECT name "
156
                           " FROM tbl_cost_centers "
157
                           " WHERE id = %s ",
158
                           (new_values['data']['cost_center_id'],))
159
            row = cursor.fetchone()
160
            if row is None:
161
                cursor.close()
162
                cnx.close()
163
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
164
                                       description='API.COST_CENTER_NOT_FOUND')
165
166
        if svg_id is not None:
167
            cursor.execute(" SELECT name "
168
                           " FROM tbl_svgs "
169
                           " WHERE id = %s ",
170
                           (svg_id,))
171
            row = cursor.fetchone()
172
            if row is None:
173
                cursor.close()
174
                cnx.close()
175
                raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
176
                                       description='API.SVG_NOT_FOUND')
177
178
        add_values = (" INSERT INTO tbl_equipments "
179
                      "    (name, uuid, is_input_counted, is_output_counted, "
180
                      "     cost_center_id, svg_id, camera_url, description) "
181
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s) ")
182
        cursor.execute(add_values, (name,
183
                                    str(uuid.uuid4()),
184
                                    is_input_counted,
185
                                    is_output_counted,
186
                                    cost_center_id,
187
                                    svg_id,
188
                                    camera_url,
189
                                    description))
190
        new_id = cursor.lastrowid
191
        cnx.commit()
192
        cursor.close()
193
        cnx.close()
194
195
        resp.status = falcon.HTTP_201
196
        resp.location = '/equipments/' + str(new_id)
197
198
199
class EquipmentItem: