Passed
Push — master ( cb176a...4b8481 )
by
unknown
13:30
created

DistributionCircuitItem.on_get()   C

Complexity

Conditions 10

Size

Total Lines 52
Code Lines 40

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
eloc 40
dl 0
loc 52
rs 5.9999
c 0
b 0
f 0
cc 10
nop 3

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

Complexity

Complex classes like core.distributioncircuit.DistributionCircuitItem.on_get() often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
import uuid
2
import falcon
3
import mysql.connector
4
import simplejson as json
5
from core.useractivity import user_logger, admin_control, access_control, api_key_control
6
import config
7
8
9
class DistributionCircuitCollection:
10
    """
11
    Distribution Circuit Collection Resource
12
13
    This class handles CRUD operations for distribution circuit collection.
14
    It provides endpoints for listing all distribution circuits and creating new ones.
15
    Distribution circuits represent electrical circuits within distribution systems.
16
    """
17
    def __init__(self):
18
        """Initialize DistributionCircuitCollection"""
19
        pass
20
21
    @staticmethod
22
    def on_options(req, resp):
23
        """Handle OPTIONS requests for CORS preflight"""
24
        _ = req
25
        resp.status = falcon.HTTP_200
26
27
    @staticmethod
28
    def on_get(req, resp):
29
        if 'API-KEY' not in req.headers or \
30
                not isinstance(req.headers['API-KEY'], str) or \
31
                len(str.strip(req.headers['API-KEY'])) == 0:
32
            access_control(req)
33
        else:
34
            api_key_control(req)
35
        cnx = mysql.connector.connect(**config.myems_system_db)
36
        cursor = cnx.cursor()
37
38
        query = (" SELECT id, name, uuid "
39
                 " FROM tbl_distribution_systems ")
40
        cursor.execute(query)
41
        rows_distribution_systems = cursor.fetchall()
42
43
        distribution_system_dict = dict()
44
        if rows_distribution_systems is not None and len(rows_distribution_systems) > 0:
45
            for row in rows_distribution_systems:
46
                distribution_system_dict[row[0]] = {"id": row[0],
47
                                                    "name": row[1],
48
                                                    "uuid": row[2]}
49
        query = (" SELECT id, name, uuid, distribution_system_id, "
50
                 "        distribution_room, switchgear, peak_load, peak_current, customers, meters "
51
                 " FROM tbl_distribution_circuits "
52
                 " ORDER BY id ")
53
        cursor.execute(query)
54
        rows_distribution_circuits = cursor.fetchall()
55
56
        result = list()
57
        if rows_distribution_circuits is not None and len(rows_distribution_circuits) > 0:
58
            for row in rows_distribution_circuits:
59
                meta_result = {"id": row[0],
60
                               "name": row[1],
61
                               "uuid": row[2],
62
                               "distribution_system": distribution_system_dict.get(row[3]),
63
                               "distribution_room": row[4],
64
                               "switchgear": row[5],
65
                               "peak_load": row[6],
66
                               "peak_current": row[7],
67
                               "customers": row[8],
68
                               "meters": row[9]}
69
                result.append(meta_result)
70
71
        cursor.close()
72
        cnx.close()
73
        resp.text = json.dumps(result)
74
75
    @staticmethod
76
    @user_logger
77
    def on_post(req, resp):
78
        """Handles POST requests"""
79
        admin_control(req)
80
        try:
81
            raw_json = req.stream.read().decode('utf-8')
82
        except UnicodeDecodeError as ex:
83
            print("Failed to decode request")
84
            raise falcon.HTTPError(status=falcon.HTTP_400,
85
                                   title='API.BAD_REQUEST',
86
                                   description='API.INVALID_ENCODING')
87
        except Exception as ex:
88
            print("Unexpected error reading request stream")
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_DISTRIBUTION_CIRCUIT_NAME')
100
        name = str.strip(new_values['data']['name'])
101
102
        if 'distribution_system_id' not in new_values['data'].keys() or \
103
                not isinstance(new_values['data']['distribution_system_id'], int) or \
104
                new_values['data']['distribution_system_id'] <= 0:
105
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
106
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
107
        distribution_system_id = new_values['data']['distribution_system_id']
108
109
        if 'distribution_room' not in new_values['data'].keys() or \
110
                not isinstance(new_values['data']['distribution_room'], str) or \
111
                len(str.strip(new_values['data']['distribution_room'])) == 0:
112
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
113
                                   description='API.INVALID_DISTRIBUTION_ROOM')
114
        distribution_room = str.strip(new_values['data']['distribution_room'])
115
116
        if 'switchgear' not in new_values['data'].keys() or \
117
                not isinstance(new_values['data']['switchgear'], str) or \
118
                len(str.strip(new_values['data']['switchgear'])) == 0:
119
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
120
                                   description='API.INVALID_SWITCHGEAR')
121
        switchgear = str.strip(new_values['data']['switchgear'])
122
123
        if 'peak_load' not in new_values['data'].keys() or \
124
                not (isinstance(new_values['data']['peak_load'], float) or
125
                     isinstance(new_values['data']['peak_load'], int)):
126
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
127
                                   description='API.INVALID_PEAK_LOAD')
128
        peak_load = float(new_values['data']['peak_load'])
129
130
        if 'peak_current' not in new_values['data'].keys() or \
131
                not (isinstance(new_values['data']['peak_current'], float) or
132
                     isinstance(new_values['data']['peak_current'], int)):
133
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
134
                                   description='API.INVALID_PEAK_CURRENT')
135
        peak_current = float(new_values['data']['peak_current'])
136
137
        if 'customers' in new_values['data'].keys() and \
138
                new_values['data']['customers'] is not None and \
139
                len(str(new_values['data']['customers'])) > 0:
140
            customers = str.strip(new_values['data']['customers'])
141
        else:
142
            customers = None
143
144
        if 'meters' in new_values['data'].keys() and \
145
                new_values['data']['meters'] is not None and \
146
                len(str(new_values['data']['meters'])) > 0:
147
            meters = str.strip(new_values['data']['meters'])
148
        else:
149
            meters = None
150
151
        cnx = mysql.connector.connect(**config.myems_system_db)
152
        cursor = cnx.cursor()
153
154
        cursor.execute(" SELECT name "
155
                       " FROM tbl_distribution_systems "
156
                       " WHERE id = %s ",
157
                       (distribution_system_id,))
158
        if cursor.fetchone() is None:
159
            cursor.close()
160
            cnx.close()
161
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
162
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
163
164
        cursor.execute(" SELECT name "
165
                       " FROM tbl_distribution_circuits "
166
                       " WHERE distribution_system_id = %s AND name = %s ",
167
                       (distribution_system_id, name,))
168
        if cursor.fetchone() is not None:
169
            cursor.close()
170
            cnx.close()
171
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
172
                                   description='API.DISTRIBUTION_CIRCUIT_NAME_IS_ALREADY_IN_USE')
173
174
        add_values = (" INSERT INTO tbl_distribution_circuits "
175
                      "    (name, uuid, distribution_system_id,"
176
                      "     distribution_room, switchgear, peak_load, peak_current, customers, meters) "
177
                      " VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s) ")
178
        cursor.execute(add_values, (name,
179
                                    str(uuid.uuid4()),
180
                                    distribution_system_id,
181
                                    distribution_room,
182
                                    switchgear,
183
                                    peak_load,
184
                                    peak_current,
185
                                    customers,
186
                                    meters))
187
        new_id = cursor.lastrowid
188
        cnx.commit()
189
        cursor.close()
190
        cnx.close()
191
192
        resp.status = falcon.HTTP_201
193
        resp.location = '/distributioncircuits/' + str(new_id)
194
195
196
class DistributionCircuitItem:
197
    def __init__(self):
198
        pass
199
200
    @staticmethod
201
    def on_options(req, resp, id_):
202
        _ = req
203
        resp.status = falcon.HTTP_200
204
        _ = id_
205
206
    @staticmethod
207
    def on_get(req, resp, id_):
208
        if 'API-KEY' not in req.headers or \
209
                not isinstance(req.headers['API-KEY'], str) or \
210
                len(str.strip(req.headers['API-KEY'])) == 0:
211
            access_control(req)
212
        else:
213
            api_key_control(req)
214
        if not id_.isdigit() or int(id_) <= 0:
215
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
216
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
217
218
        cnx = mysql.connector.connect(**config.myems_system_db)
219
        cursor = cnx.cursor()
220
221
        query = (" SELECT id, name, uuid "
222
                 " FROM tbl_distribution_systems ")
223
        cursor.execute(query)
224
        rows_distribution_systems = cursor.fetchall()
225
226
        distribution_system_dict = dict()
227
        if rows_distribution_systems is not None and len(rows_distribution_systems) > 0:
228
            for row in rows_distribution_systems:
229
                distribution_system_dict[row[0]] = {"id": row[0],
230
                                                    "name": row[1],
231
                                                    "uuid": row[2]}
232
233
        query = (" SELECT id, name, uuid, distribution_system_id, "
234
                 "        distribution_room, switchgear, peak_load, peak_current, customers, meters "
235
                 " FROM tbl_distribution_circuits "
236
                 " WHERE id = %s ")
237
        cursor.execute(query, (id_,))
238
        row = cursor.fetchone()
239
        cursor.close()
240
        cnx.close()
241
242
        if row is None:
243
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
244
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
245
        else:
246
            meta_result = {"id": row[0],
247
                           "name": row[1],
248
                           "uuid": row[2],
249
                           "distribution_system": distribution_system_dict.get(row[3]),
250
                           "distribution_room": row[4],
251
                           "switchgear": row[5],
252
                           "peak_load": row[6],
253
                           "peak_current": row[7],
254
                           "customers": row[8],
255
                           "meters": row[9]}
256
257
        resp.text = json.dumps(meta_result)
258
259
    @staticmethod
260
    @user_logger
261
    def on_delete(req, resp, id_):
262
        admin_control(req)
263
        if not id_.isdigit() or int(id_) <= 0:
264
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
265
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
266
        cnx = mysql.connector.connect(**config.myems_system_db)
267
        cursor = cnx.cursor()
268
269
        cursor.execute(" SELECT name "
270
                       " FROM tbl_distribution_circuits "
271
                       " WHERE id = %s ", (id_,))
272
        if cursor.fetchone() is None:
273
            cursor.close()
274
            cnx.close()
275
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
276
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
277
278
        # delete relation with points
279
        cursor.execute(" DELETE FROM tbl_distribution_circuits_points "
280
                       " WHERE distribution_circuit_id = %s ", (id_,))
281
        # delete distribution circuit itself
282
        cursor.execute(" DELETE FROM tbl_distribution_circuits "
283
                       " WHERE id = %s ", (id_,))
284
        cnx.commit()
285
286
        cursor.close()
287
        cnx.close()
288
289
        resp.status = falcon.HTTP_204
290
291
    @staticmethod
292
    @user_logger
293
    def on_put(req, resp, id_):
294
        """Handles PUT requests"""
295
        admin_control(req)
296
        try:
297
            raw_json = req.stream.read().decode('utf-8')
298
        except UnicodeDecodeError as ex:
299
            print("Failed to decode request")
300
            raise falcon.HTTPError(status=falcon.HTTP_400,
301
                                   title='API.BAD_REQUEST',
302
                                   description='API.INVALID_ENCODING')
303
        except Exception as ex:
304
            print("Unexpected error reading request stream")
305
            raise falcon.HTTPError(status=falcon.HTTP_400,
306
                                   title='API.BAD_REQUEST',
307
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
308
309
        if not id_.isdigit() or int(id_) <= 0:
310
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
311
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
312
313
        new_values = json.loads(raw_json)
314
315
        if 'name' not in new_values['data'].keys() or \
316
                not isinstance(new_values['data']['name'], str) or \
317
                len(str.strip(new_values['data']['name'])) == 0:
318
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
319
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_NAME')
320
        name = str.strip(new_values['data']['name'])
321
322
        if 'distribution_system_id' not in new_values['data'].keys() or \
323
                not isinstance(new_values['data']['distribution_system_id'], int) or \
324
                new_values['data']['distribution_system_id'] <= 0:
325
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
326
                                   description='API.INVALID_DISTRIBUTION_SYSTEM_ID')
327
        distribution_system_id = new_values['data']['distribution_system_id']
328
329
        if 'distribution_room' not in new_values['data'].keys() or \
330
                not isinstance(new_values['data']['distribution_room'], str) or \
331
                len(str.strip(new_values['data']['distribution_room'])) == 0:
332
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
333
                                   description='API.INVALID_DISTRIBUTION_ROOM')
334
        distribution_room = str.strip(new_values['data']['distribution_room'])
335
336
        if 'switchgear' not in new_values['data'].keys() or \
337
                not isinstance(new_values['data']['switchgear'], str) or \
338
                len(str.strip(new_values['data']['switchgear'])) == 0:
339
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
340
                                   description='API.INVALID_SWITCHGEAR')
341
        switchgear = str.strip(new_values['data']['switchgear'])
342
343
        if 'peak_load' not in new_values['data'].keys() or \
344
                not (isinstance(new_values['data']['peak_load'], float) or
345
                     isinstance(new_values['data']['peak_load'], int)):
346
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
347
                                   description='API.INVALID_PEAK_LOAD')
348
        peak_load = float(new_values['data']['peak_load'])
349
350
        if 'peak_current' not in new_values['data'].keys() or \
351
                not (isinstance(new_values['data']['peak_current'], float) or
352
                     isinstance(new_values['data']['peak_current'], int)):
353
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
354
                                   description='API.INVALID_PEAK_CURRENT')
355
        peak_current = float(new_values['data']['peak_current'])
356
357
        if 'customers' in new_values['data'].keys() and \
358
                new_values['data']['customers'] is not None and \
359
                len(str(new_values['data']['customers'])) > 0:
360
            customers = str.strip(new_values['data']['customers'])
361
        else:
362
            customers = None
363
364
        if 'meters' in new_values['data'].keys() and \
365
                new_values['data']['meters'] is not None and \
366
                len(str(new_values['data']['meters'])) > 0:
367
            meters = str.strip(new_values['data']['meters'])
368
        else:
369
            meters = None
370
371
        cnx = mysql.connector.connect(**config.myems_system_db)
372
        cursor = cnx.cursor()
373
374
        cursor.execute(" SELECT name "
375
                       " FROM tbl_distribution_systems "
376
                       " WHERE id = %s ",
377
                       (distribution_system_id,))
378
        if cursor.fetchone() is None:
379
            cursor.close()
380
            cnx.close()
381
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
382
                                   description='API.DISTRIBUTION_SYSTEM_NOT_FOUND')
383
        cursor.execute(" SELECT name "
384
                       " FROM tbl_distribution_circuits "
385
                       " WHERE id = %s ", (id_,))
386
        if cursor.fetchone() is None:
387
            cursor.close()
388
            cnx.close()
389
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
390
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
391
392
        cursor.execute(" SELECT name "
393
                       " FROM tbl_distribution_circuits "
394
                       " WHERE distribution_system_id = %s AND name = %s AND id != %s ",
395
                       (distribution_system_id, name, id_))
396
        if cursor.fetchone() is not None:
397
            cursor.close()
398
            cnx.close()
399
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
400
                                   description='API.DISTRIBUTION_CIRCUIT_NAME_IS_ALREADY_IN_USE')
401
402
        update_row = (" UPDATE tbl_distribution_circuits "
403
                      " SET name = %s, distribution_system_id = %s, distribution_room = %s, switchgear = %s, "
404
                      "     peak_load = %s, peak_current = %s, customers = %s, meters = %s "
405
                      " WHERE id = %s ")
406
        cursor.execute(update_row, (name,
407
                                    distribution_system_id,
408
                                    distribution_room,
409
                                    switchgear,
410
                                    peak_load,
411
                                    peak_current,
412
                                    customers,
413
                                    meters,
414
                                    id_))
415
        cnx.commit()
416
417
        cursor.close()
418
        cnx.close()
419
420
        resp.status = falcon.HTTP_200
421
422
423
class DistributionCircuitPointCollection:
424
    def __init__(self):
425
        pass
426
427
    @staticmethod
428
    def on_options(req, resp, id_):
429
        _ = req
430
        resp.status = falcon.HTTP_200
431
        _ = id_
432
433
    @staticmethod
434
    def on_get(req, resp, id_):
435
        if 'API-KEY' not in req.headers or \
436
                not isinstance(req.headers['API-KEY'], str) or \
437
                len(str.strip(req.headers['API-KEY'])) == 0:
438
            access_control(req)
439
        else:
440
            api_key_control(req)
441
        if not id_.isdigit() or int(id_) <= 0:
442
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
443
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
444
445
        cnx = mysql.connector.connect(**config.myems_system_db)
446
        cursor = cnx.cursor()
447
448
        query = (" SELECT id, name, uuid "
449
                 " FROM tbl_distribution_systems ")
450
        cursor.execute(query)
451
        rows_distribution_systems = cursor.fetchall()
452
453
        distribution_system_dict = dict()
454
        if rows_distribution_systems is not None and len(rows_distribution_systems) > 0:
455
            for row in rows_distribution_systems:
456
                distribution_system_dict[row[2]] = {"id": row[0],
457
                                                    "name": row[1],
458
                                                    "uuid": row[2]}
459
460
        cursor.execute(" SELECT name "
461
                       " FROM tbl_distribution_circuits "
462
                       " WHERE id = %s ", (id_,))
463
        if cursor.fetchone() is None:
464
            cursor.close()
465
            cnx.close()
466
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
467
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
468
469
        query = (" SELECT p.id AS point_id, p.name AS point_name, p.address AS point_address, "
470
                 "        dc.id AS distribution_circuit_id, dc.name AS distribution_circuit_name, "
471
                 "        dc.uuid AS distribution_circuit_uuid "
472
                 " FROM tbl_points p, tbl_distribution_circuits_points dcp, tbl_distribution_circuits dc "
473
                 " WHERE dcp.distribution_circuit_id = %s AND p.id = dcp.point_id "
474
                 "       AND dcp.distribution_circuit_id = dc.id "
475
                 " ORDER BY p.name ")
476
        cursor.execute(query, (id_,))
477
        rows = cursor.fetchall()
478
479
        result = list()
480
        if rows is not None and len(rows) > 0:
481
            for row in rows:
482
                meta_result = {"id": row[0], "name": row[1], "address": row[2],
483
                               "distribution_circuit": {"id": row[3],
484
                                                        "name": row[4],
485
                                                        "uuid": row[5]}}
486
                result.append(meta_result)
487
488
        resp.text = json.dumps(result)
489
490 View Code Duplication
    @staticmethod
0 ignored issues
show
Duplication introduced by
This code seems to be duplicated in your project.
Loading history...
491
    @user_logger
492
    def on_post(req, resp, id_):
493
        """Handles POST requests"""
494
        admin_control(req)
495
        try:
496
            raw_json = req.stream.read().decode('utf-8')
497
        except UnicodeDecodeError as ex:
498
            print("Failed to decode request")
499
            raise falcon.HTTPError(status=falcon.HTTP_400,
500
                                   title='API.BAD_REQUEST',
501
                                   description='API.INVALID_ENCODING')
502
        except Exception as ex:
503
            print("Unexpected error reading request stream")
504
            raise falcon.HTTPError(status=falcon.HTTP_400,
505
                                   title='API.BAD_REQUEST',
506
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
507
508
        if not id_.isdigit() or int(id_) <= 0:
509
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
510
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
511
512
        new_values = json.loads(raw_json)
513
514
        cnx = mysql.connector.connect(**config.myems_system_db)
515
        cursor = cnx.cursor()
516
517
        cursor.execute(" SELECT name "
518
                       " from tbl_distribution_circuits "
519
                       " WHERE id = %s ", (id_,))
520
        if cursor.fetchone() is None:
521
            cursor.close()
522
            cnx.close()
523
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
524
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
525
526
        cursor.execute(" SELECT name "
527
                       " FROM tbl_points "
528
                       " WHERE id = %s ", (new_values['data']['point_id'],))
529
        if cursor.fetchone() is None:
530
            cursor.close()
531
            cnx.close()
532
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
533
                                   description='API.POINT_NOT_FOUND')
534
535
        query = (" SELECT id "
536
                 " FROM tbl_distribution_circuits_points "
537
                 " WHERE distribution_circuit_id = %s AND point_id = %s")
538
        cursor.execute(query, (id_, new_values['data']['point_id'],))
539
        if cursor.fetchone() is not None:
540
            cursor.close()
541
            cnx.close()
542
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.ERROR',
543
                                   description='API.DISTRIBUTION_CIRCUIT_POINT_RELATION_EXISTS')
544
545
        add_row = (" INSERT INTO tbl_distribution_circuits_points (distribution_circuit_id, point_id) "
546
                   " VALUES (%s, %s) ")
547
        cursor.execute(add_row, (id_, new_values['data']['point_id'],))
548
        cnx.commit()
549
        cursor.close()
550
        cnx.close()
551
552
        resp.status = falcon.HTTP_201
553
        resp.location = '/distributioncircuits/' + str(id_) + '/points/' + str(new_values['data']['point_id'])
554
555
556
class DistributionCircuitPointItem:
557
    def __init__(self):
558
        pass
559
560
    @staticmethod
561
    def on_options(req, resp, id_, pid):
562
        _ = req
563
        resp.status = falcon.HTTP_200
564
        _ = id_
565
566
    @staticmethod
567
    @user_logger
568
    def on_delete(req, resp, id_, pid):
569
        admin_control(req)
570
        if not id_.isdigit() or int(id_) <= 0:
571
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
572
                                   description='API.INVALID_DISTRIBUTION_CIRCUIT_ID')
573
574
        if not pid.isdigit() or int(pid) <= 0:
575
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
576
                                   description='API.INVALID_POINT_ID')
577
578
        cnx = mysql.connector.connect(**config.myems_system_db)
579
        cursor = cnx.cursor()
580
581
        cursor.execute(" SELECT name "
582
                       " FROM tbl_distribution_circuits "
583
                       " WHERE id = %s ", (id_,))
584
        if cursor.fetchone() is None:
585
            cursor.close()
586
            cnx.close()
587
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
588
                                   description='API.DISTRIBUTION_CIRCUIT_NOT_FOUND')
589
590
        cursor.execute(" SELECT name "
591
                       " FROM tbl_points "
592
                       " WHERE id = %s ", (pid,))
593
        if cursor.fetchone() is None:
594
            cursor.close()
595
            cnx.close()
596
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
597
                                   description='API.POINT_NOT_FOUND')
598
599
        cursor.execute(" SELECT id "
600
                       " FROM tbl_distribution_circuits_points "
601
                       " WHERE distribution_circuit_id = %s AND point_id = %s ", (id_, pid))
602
        if cursor.fetchone() is None:
603
            cursor.close()
604
            cnx.close()
605
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
606
                                   description='API.DISTRIBUTION_CIRCUIT_POINT_RELATION_NOT_FOUND')
607
608
        cursor.execute(" DELETE FROM tbl_distribution_circuits_points "
609
                       " WHERE distribution_circuit_id = %s AND point_id = %s ", (id_, pid))
610
        cnx.commit()
611
612
        cursor.close()
613
        cnx.close()
614
615
        resp.status = falcon.HTTP_204
616
617