Passed
Push — master ( c6068e...54bd3b )
by Guangyu
02:21 queued 10s
created

distributionsystem.DistributionSystemItem.on_get()   A

Complexity

Conditions 4

Size

Total Lines 29
Code Lines 21

Duplication

Lines 29
Ratio 100 %

Importance

Changes 0
Metric Value
eloc 21
dl 29
loc 29
rs 9.376
c 0
b 0
f 0
cc 4
nop 3
1
import falcon
2
import simplejson as json
3
import mysql.connector
4
import config
5
import uuid
6
7
8
class DistributionSystemCollection:
9
    @staticmethod
10
    def __init__():
11
        pass
12
13
    @staticmethod
14
    def on_options(req, resp):
15
        resp.status = falcon.HTTP_200
16
17
    @staticmethod
18
    def on_get(req, resp):
19
        cnx = mysql.connector.connect(**config.myems_system_db)
20
        cursor = cnx.cursor(dictionary=True)
21
22
        query = (" SELECT id, name, uuid, "
23
                 "        svg, description "
24
                 " FROM tbl_distribution_systems "
25
                 " ORDER BY id ")
26
        cursor.execute(query)
27
        rows_distribution_systems = cursor.fetchall()
28
29
        result = list()
30
        if rows_distribution_systems is not None and len(rows_distribution_systems) > 0:
31
            for row in rows_distribution_systems:
32
33
                meta_result = {"id": row['id'],
34
                               "name": row['name'],
35
                               "uuid": row['uuid'],
36
                               "svg": row['svg'],
37
                               "description": row['description']}
38
                result.append(meta_result)
39
40
        cursor.close()
41
        cnx.disconnect()
42
        resp.body = json.dumps(result)
43
44
    @staticmethod
45
    def on_post(req, resp):
46
        """Handles POST requests"""
47
        try:
48
            raw_json = req.stream.read().decode('utf-8')
49
        except Exception as ex:
50
            raise falcon.HTTPError(falcon.HTTP_400, title='API.ERROR', description=ex)
51
52
        new_values = json.loads(raw_json, encoding='utf-8')
53
54
        if 'name' not in new_values['data'].keys() or \
55
                not isinstance(new_values['data']['name'], str) or \
56
                len(str.strip(new_values['data']['name'])) == 0:
57
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
58
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_NAME')
59
        name = str.strip(new_values['data']['name'])
60
61
        if 'svg' not in new_values['data'].keys() or \
62
                not isinstance(new_values['data']['svg'], str) or \
63
                len(str.strip(new_values['data']['svg'])) == 0:
64
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
65
                                   description='API.INVALID_SVG')
66
        svg = str.strip(new_values['data']['svg'])
67
68
        if 'description' in new_values['data'].keys() and \
69
                new_values['data']['description'] is not None and \
70
                len(str(new_values['data']['description'])) > 0:
71
            description = str.strip(new_values['data']['description'])
72
        else:
73
            description = None
74
75
        cnx = mysql.connector.connect(**config.myems_system_db)
76
        cursor = cnx.cursor()
77
78
        cursor.execute(" SELECT name "
79
                       " FROM tbl_distribution_systems "
80
                       " WHERE name = %s ", (name,))
81
        if cursor.fetchone() is not None:
82
            cursor.close()
83
            cnx.disconnect()
84
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
85
                                   description='API.DISTRIBUTION_SYSTEM_NAME_IS_ALREADY_IN_USE')
86
87
        add_values = (" INSERT INTO tbl_distribution_systems "
88
                      "    (name, uuid, svg, description) "
89
                      " VALUES (%s, %s, %s, %s) ")
90
        cursor.execute(add_values, (name,
91
                                    str(uuid.uuid4()),
92
                                    svg,
93
                                    description))
94
        new_id = cursor.lastrowid
95
        cnx.commit()
96
        cursor.close()
97
        cnx.disconnect()
98
99
        resp.status = falcon.HTTP_201
100
        resp.location = '/distributionsystems/' + str(new_id)
101
102
103
class DistributionSystemItem:
104
    @staticmethod
105
    def __init__():
106
        pass
107
108
    @staticmethod
109
    def on_options(req, resp, id_):
110
        resp.status = falcon.HTTP_200
111
112 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
113
    def on_get(req, resp, id_):
114
        if not id_.isdigit() or int(id_) <= 0:
115
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
116
                                   description='API.INVALID_METER_ID')
117
118
        cnx = mysql.connector.connect(**config.myems_system_db)
119
        cursor = cnx.cursor(dictionary=True)
120
121
        query = (" SELECT id, name, uuid, "
122
                 "        svg, description "
123
                 " FROM tbl_distribution_systems "
124
                 " WHERE id = %s ")
125
        cursor.execute(query, (id_,))
126
        row = cursor.fetchone()
127
        cursor.close()
128
        cnx.disconnect()
129
130
        if row is None:
131
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
132
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
133
        else:
134
            meta_result = {"id": row['id'],
135
                           "name": row['name'],
136
                           "uuid": row['uuid'],
137
                           "svg": row['svg'],
138
                           "description": row['description']}
139
140
        resp.body = json.dumps(meta_result)
141
142
    @staticmethod
143
    def on_delete(req, resp, id_):
144
        if not id_.isdigit() or int(id_) <= 0:
145
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
146
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
147
        cnx = mysql.connector.connect(**config.myems_system_db)
148
        cursor = cnx.cursor()
149
150
        cursor.execute(" SELECT name "
151
                       " FROM tbl_distribution_systems "
152
                       " WHERE id = %s ", (id_,))
153
        if cursor.fetchone() is None:
154
            cursor.close()
155
            cnx.disconnect()
156
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
157
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
158
159
        # check associated distribution circuits
160
        cursor.execute(" SELECT id "
161
                       " FROM tbl_distribution_circuits "
162
                       " WHERE distribution_system_id = %s ",
163
                       (id_,))
164
        rows_distribution_circuits = cursor.fetchall()
165
        if rows_distribution_circuits is not None and len(rows_distribution_circuits) > 0:
166
            cursor.close()
167
            cnx.disconnect()
168
            raise falcon.HTTPError(falcon.HTTP_400,
169
                                   title='API.BAD_REQUEST',
170
                                   description='API.THERE_IS_ASSOCIATED_DISTRIBUTION_CIRCUITS')
171
172
        cursor.execute(" DELETE FROM tbl_distribution_systems WHERE id = %s ", (id_,))
173
        cnx.commit()
174
175
        cursor.close()
176
        cnx.disconnect()
177
178
        resp.status = falcon.HTTP_204
179
180
    @staticmethod
181
    def on_put(req, resp, id_):
182
        """Handles PUT requests"""
183
        try:
184
            raw_json = req.stream.read().decode('utf-8')
185
        except Exception as ex:
186
            raise falcon.HTTPError(falcon.HTTP_400, title='API.EXCEPTION', description=ex)
187
188
        if not id_.isdigit() or int(id_) <= 0:
189
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
190
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
191
192
        new_values = json.loads(raw_json, encoding='utf-8')
193
194
        if 'name' not in new_values['data'].keys() or \
195
                not isinstance(new_values['data']['name'], str) or \
196
                len(str.strip(new_values['data']['name'])) == 0:
197
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
198
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_NAME')
199
        name = str.strip(new_values['data']['name'])
200
201
        if 'svg' not in new_values['data'].keys() or \
202
                not isinstance(new_values['data']['svg'], str) or \
203
                len(str.strip(new_values['data']['svg'])) == 0:
204
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
205
                                   description='API.INVALID_SVG')
206
        svg = str.strip(new_values['data']['svg'])
207
208
        if 'description' in new_values['data'].keys() and \
209
                new_values['data']['description'] is not None and \
210
                len(str(new_values['data']['description'])) > 0:
211
            description = str.strip(new_values['data']['description'])
212
        else:
213
            description = None
214
215
        cnx = mysql.connector.connect(**config.myems_system_db)
216
        cursor = cnx.cursor()
217
218
        cursor.execute(" SELECT name "
219
                       " FROM tbl_distribution_systems "
220
                       " WHERE name = %s AND id != %s ", (name, id_))
221
        if cursor.fetchone() is not None:
222
            cursor.close()
223
            cnx.disconnect()
224
            raise falcon.HTTPError(falcon.HTTP_404, title='API.BAD_REQUEST',
225
                                   description='API.DISTRIBUTION_SYSTEM_NAME_IS_ALREADY_IN_USE')
226
227
        update_row = (" UPDATE tbl_distribution_systems "
228
                      " SET name = %s, svg = %s, description = %s "
229
                      " WHERE id = %s ")
230
        cursor.execute(update_row, (name,
231
                                    svg,
232
                                    description,
233
                                    id_))
234
        cnx.commit()
235
236
        cursor.close()
237
        cnx.disconnect()
238
239
        resp.status = falcon.HTTP_200
240
241
242 View Code Duplication
class DistributionSystemDistributionCircuitCollection:
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
243
    @staticmethod
244
    def __init__():
245
        pass
246
247
    @staticmethod
248
    def on_options(req, resp, id_):
249
        resp.status = falcon.HTTP_200
250
251
    @staticmethod
252
    def on_get(req, resp, id_):
253
        if not id_.isdigit() or int(id_) <= 0:
254
            raise falcon.HTTPError(falcon.HTTP_400, title='API.BAD_REQUEST',
255
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
256
257
        cnx = mysql.connector.connect(**config.myems_system_db)
258
        cursor = cnx.cursor(dictionary=True)
259
260
        cursor.execute(" SELECT name "
261
                       " FROM tbl_distribution_systems "
262
                       " WHERE id = %s ", (id_,))
263
        if cursor.fetchone() is None:
264
            cursor.close()
265
            cnx.disconnect()
266
            raise falcon.HTTPError(falcon.HTTP_404, title='API.NOT_FOUND',
267
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
268
269
        query = (" SELECT id, name, uuid, "
270
                 "        distribution_room, switchgear, peak_load, peak_current, customers, meters "
271
                 " FROM tbl_distribution_circuits "
272
                 " WHERE distribution_system_id = %s "
273
                 " ORDER BY name ")
274
        cursor.execute(query, (id_,))
275
        rows = cursor.fetchall()
276
277
        result = list()
278
        if rows is not None and len(rows) > 0:
279
            for row in rows:
280
                meta_result = {"id": row['id'], "name": row['name'], "uuid": row['uuid'],
281
                               "distribution_room": row['distribution_room'], "switchgear": row['switchgear'],
282
                               "peak_load": row['peak_load'], "peak_current": row['peak_current'],
283
                               "customers": row['customers'], "meters": row['meters']}
284
                result.append(meta_result)
285
286
        resp.body = json.dumps(result)
287