Code Duplication    Length = 160-160 lines in 2 locations

myems-api/core/hybridpowerstation.py 2 locations

@@ 4392-4551 (lines=160) @@
4389
        resp.status = falcon.HTTP_204
4390
4391
4392
class HybridPowerStationPVCollection:
4393
    def __init__(self):
4394
        """Initializes Class"""
4395
        pass
4396
4397
    @staticmethod
4398
    def on_options(req, resp, id_):
4399
        resp.status = falcon.HTTP_200
4400
4401
    @staticmethod
4402
    def on_get(req, resp, id_):
4403
        access_control(req)
4404
        if not id_.isdigit() or int(id_) <= 0:
4405
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4406
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
4407
4408
        cnx = mysql.connector.connect(**config.myems_system_db)
4409
        cursor = cnx.cursor()
4410
4411
        cursor.execute(" SELECT name "
4412
                       " FROM tbl_hybrid_power_stations "
4413
                       " WHERE id = %s ", (id_,))
4414
        if cursor.fetchone() is None:
4415
            cursor.close()
4416
            cnx.close()
4417
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4418
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
4419
        # query meter dict
4420
        query = (" SELECT id, name, uuid "
4421
                 " FROM tbl_meters ")
4422
        cursor.execute(query)
4423
        rows_meters = cursor.fetchall()
4424
4425
        meter_dict = dict()
4426
        if rows_meters is not None and len(rows_meters) > 0:
4427
            for row in rows_meters:
4428
                meter_dict[row[0]] = {"id": row[0],
4429
                                      "name": row[1],
4430
                                      "uuid": row[2]}
4431
        # query point dict
4432
        query = (" SELECT id, name "
4433
                 " FROM tbl_points ")
4434
        cursor.execute(query)
4435
        rows_points = cursor.fetchall()
4436
4437
        point_dict = dict()
4438
        if rows_points is not None and len(rows_points) > 0:
4439
            for row in rows_points:
4440
                point_dict[row[0]] = {"id": row[0],
4441
                                      "name": row[1]}
4442
4443
        query = (" SELECT id, name, uuid, operating_status_point_id, meter_id "
4444
                 "        FROM tbl_hybrid_power_stations_pvs "
4445
                 " WHERE hybrid_power_station_id = %s "
4446
                 " ORDER BY name ")
4447
        cursor.execute(query, (id_,))
4448
        rows = cursor.fetchall()
4449
4450
        result = list()
4451
        if rows is not None and len(rows) > 0:
4452
            for row in rows:
4453
                meta_result = {"id": row[0],
4454
                               "name": row[1],
4455
                               "uuid": row[2],
4456
                               "operating_status_point": point_dict.get(row[3]),
4457
                               "meter": meter_dict.get(row[4])
4458
                               }
4459
                result.append(meta_result)
4460
4461
        resp.text = json.dumps(result)
4462
4463
    @staticmethod
4464
    @user_logger
4465
    def on_post(req, resp, id_):
4466
        """Handles POST requests"""
4467
        admin_control(req)
4468
        try:
4469
            raw_json = req.stream.read().decode('utf-8')
4470
        except Exception as ex:
4471
            raise falcon.HTTPError(status=falcon.HTTP_400,
4472
                                   title='API.BAD_REQUEST',
4473
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
4474
        if not id_.isdigit() or int(id_) <= 0:
4475
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4476
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
4477
4478
        cnx = mysql.connector.connect(**config.myems_system_db)
4479
        cursor = cnx.cursor()
4480
4481
        cursor.execute(" SELECT name "
4482
                       " FROM tbl_hybrid_power_stations "
4483
                       " WHERE id = %s ", (id_,))
4484
        if cursor.fetchone() is None:
4485
            cursor.close()
4486
            cnx.close()
4487
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4488
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
4489
4490
        new_values = json.loads(raw_json)
4491
4492
        if 'name' not in new_values['data'].keys() or \
4493
                not isinstance(new_values['data']['name'], str) or \
4494
                len(str.strip(new_values['data']['name'])) == 0:
4495
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4496
                                   description='API.INVALID_HYBRID_POWER_STATION_PCS_NAME')
4497
        name = str.strip(new_values['data']['name'])
4498
4499
        if 'operating_status_point_id' not in new_values['data'].keys() or \
4500
                not isinstance(new_values['data']['operating_status_point_id'], int) or \
4501
                new_values['data']['operating_status_point_id'] <= 0:
4502
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4503
                                   description='API.INVALID_OPERATING_STATUS_POINT_ID')
4504
        operating_status_point_id = new_values['data']['operating_status_point_id']
4505
4506
        if 'meter_id' not in new_values['data'].keys() or \
4507
                not isinstance(new_values['data']['meter_id'], int) or \
4508
                new_values['data']['meter_id'] <= 0:
4509
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4510
                                   description='API.INVALID_METER_ID')
4511
        meter_id = new_values['data']['meter_id']
4512
4513
        cnx = mysql.connector.connect(**config.myems_system_db)
4514
        cursor = cnx.cursor()
4515
4516
        cursor.execute(" SELECT name "
4517
                       " FROM tbl_hybrid_power_stations "
4518
                       " WHERE id = %s ",
4519
                       (id_,))
4520
        if cursor.fetchone() is None:
4521
            cursor.close()
4522
            cnx.close()
4523
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
4524
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
4525
4526
        cursor.execute(" SELECT name "
4527
                       " FROM tbl_hybrid_power_stations_pvs "
4528
                       " WHERE hybrid_power_station_id = %s AND name = %s ",
4529
                       (id_, name,))
4530
        if cursor.fetchone() is not None:
4531
            cursor.close()
4532
            cnx.close()
4533
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
4534
                                   description='API.HYBRID_POWER_STATION_PV_NAME_IS_ALREADY_IN_USE')
4535
4536
        add_values = (" INSERT INTO tbl_hybrid_power_stations_pcses "
4537
                      "     (name, uuid, hybrid_power_station_id, operating_status_point_id, meter_id) "
4538
                      " VALUES (%s, %s, %s, %s, %s) ")
4539
        cursor.execute(add_values, (name,
4540
                                    str(uuid.uuid4()),
4541
                                    id_,
4542
                                    operating_status_point_id,
4543
                                    meter_id
4544
                                    ))
4545
        new_id = cursor.lastrowid
4546
        cnx.commit()
4547
        cursor.close()
4548
        cnx.close()
4549
4550
        resp.status = falcon.HTTP_201
4551
        resp.location = '/hybridpowerstation/' + str(id_) + '/pvs/' + str(new_id)
4552
4553
4554
class HybridPowerStationPVItem:
@@ 1500-1659 (lines=160) @@
1497
        resp.status = falcon.HTTP_204
1498
1499
1500
class HybridPowerStationCMCollection:
1501
    def __init__(self):
1502
        """Initializes Class"""
1503
        pass
1504
1505
    @staticmethod
1506
    def on_options(req, resp, id_):
1507
        resp.status = falcon.HTTP_200
1508
1509
    @staticmethod
1510
    def on_get(req, resp, id_):
1511
        access_control(req)
1512
        if not id_.isdigit() or int(id_) <= 0:
1513
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1514
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
1515
1516
        cnx = mysql.connector.connect(**config.myems_system_db)
1517
        cursor = cnx.cursor()
1518
1519
        cursor.execute(" SELECT name "
1520
                       " FROM tbl_hybrid_power_stations "
1521
                       " WHERE id = %s ", (id_,))
1522
        if cursor.fetchone() is None:
1523
            cursor.close()
1524
            cnx.close()
1525
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1526
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
1527
        # query meter dict
1528
        query = (" SELECT id, name, uuid "
1529
                 " FROM tbl_meters ")
1530
        cursor.execute(query)
1531
        rows_meters = cursor.fetchall()
1532
1533
        meter_dict = dict()
1534
        if rows_meters is not None and len(rows_meters) > 0:
1535
            for row in rows_meters:
1536
                meter_dict[row[0]] = {"id": row[0],
1537
                                      "name": row[1],
1538
                                      "uuid": row[2]}
1539
        # query point dict
1540
        query = (" SELECT id, name "
1541
                 " FROM tbl_points ")
1542
        cursor.execute(query)
1543
        rows_points = cursor.fetchall()
1544
1545
        point_dict = dict()
1546
        if rows_points is not None and len(rows_points) > 0:
1547
            for row in rows_points:
1548
                point_dict[row[0]] = {"id": row[0],
1549
                                      "name": row[1]}
1550
1551
        query = (" SELECT id, name, uuid, operating_status_point_id, meter_id "
1552
                 "        FROM tbl_hybrid_power_stations_cms "
1553
                 " WHERE hybrid_power_station_id = %s "
1554
                 " ORDER BY name ")
1555
        cursor.execute(query, (id_,))
1556
        rows = cursor.fetchall()
1557
1558
        result = list()
1559
        if rows is not None and len(rows) > 0:
1560
            for row in rows:
1561
                meta_result = {"id": row[0],
1562
                               "name": row[1],
1563
                               "uuid": row[2],
1564
                               "operating_status_point": point_dict.get(row[3]),
1565
                               "meter": meter_dict.get(row[4])
1566
                               }
1567
                result.append(meta_result)
1568
1569
        resp.text = json.dumps(result)
1570
1571
    @staticmethod
1572
    @user_logger
1573
    def on_post(req, resp, id_):
1574
        """Handles POST requests"""
1575
        admin_control(req)
1576
        try:
1577
            raw_json = req.stream.read().decode('utf-8')
1578
        except Exception as ex:
1579
            raise falcon.HTTPError(status=falcon.HTTP_400,
1580
                                   title='API.BAD_REQUEST',
1581
                                   description='API.FAILED_TO_READ_REQUEST_STREAM')
1582
        if not id_.isdigit() or int(id_) <= 0:
1583
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1584
                                   description='API.INVALID_HYBRID_POWER_STATION_ID')
1585
1586
        cnx = mysql.connector.connect(**config.myems_system_db)
1587
        cursor = cnx.cursor()
1588
1589
        cursor.execute(" SELECT name "
1590
                       " FROM tbl_hybrid_power_stations "
1591
                       " WHERE id = %s ", (id_,))
1592
        if cursor.fetchone() is None:
1593
            cursor.close()
1594
            cnx.close()
1595
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1596
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
1597
1598
        new_values = json.loads(raw_json)
1599
1600
        if 'name' not in new_values['data'].keys() or \
1601
                not isinstance(new_values['data']['name'], str) or \
1602
                len(str.strip(new_values['data']['name'])) == 0:
1603
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1604
                                   description='API.INVALID_HYBRID_POWER_STATION_PCS_NAME')
1605
        name = str.strip(new_values['data']['name'])
1606
1607
        if 'operating_status_point_id' not in new_values['data'].keys() or \
1608
                not isinstance(new_values['data']['operating_status_point_id'], int) or \
1609
                new_values['data']['operating_status_point_id'] <= 0:
1610
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1611
                                   description='API.INVALID_OPERATING_STATUS_POINT_ID')
1612
        operating_status_point_id = new_values['data']['operating_status_point_id']
1613
1614
        if 'meter_id' not in new_values['data'].keys() or \
1615
                not isinstance(new_values['data']['meter_id'], int) or \
1616
                new_values['data']['meter_id'] <= 0:
1617
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1618
                                   description='API.INVALID_METER_ID')
1619
        meter_id = new_values['data']['meter_id']
1620
1621
        cnx = mysql.connector.connect(**config.myems_system_db)
1622
        cursor = cnx.cursor()
1623
1624
        cursor.execute(" SELECT name "
1625
                       " FROM tbl_hybrid_power_stations "
1626
                       " WHERE id = %s ",
1627
                       (id_,))
1628
        if cursor.fetchone() is None:
1629
            cursor.close()
1630
            cnx.close()
1631
            raise falcon.HTTPError(status=falcon.HTTP_404, title='API.NOT_FOUND',
1632
                                   description='API.HYBRID_POWER_STATION_NOT_FOUND')
1633
1634
        cursor.execute(" SELECT name "
1635
                       " FROM tbl_hybrid_power_stations_cms "
1636
                       " WHERE hybrid_power_station_id = %s AND name = %s ",
1637
                       (id_, name,))
1638
        if cursor.fetchone() is not None:
1639
            cursor.close()
1640
            cnx.close()
1641
            raise falcon.HTTPError(status=falcon.HTTP_400, title='API.BAD_REQUEST',
1642
                                   description='API.HYBRID_POWER_STATION_CM_NAME_IS_ALREADY_IN_USE')
1643
1644
        add_values = (" INSERT INTO tbl_hybrid_power_stations_pcses "
1645
                      "     (name, uuid, hybrid_power_station_id, operating_status_point_id, meter_id) "
1646
                      " VALUES (%s, %s, %s, %s, %s) ")
1647
        cursor.execute(add_values, (name,
1648
                                    str(uuid.uuid4()),
1649
                                    id_,
1650
                                    operating_status_point_id,
1651
                                    meter_id
1652
                                    ))
1653
        new_id = cursor.lastrowid
1654
        cnx.commit()
1655
        cursor.close()
1656
        cnx.close()
1657
1658
        resp.status = falcon.HTTP_201
1659
        resp.location = '/hybridpowerstation/' + str(id_) + '/cms/' + str(new_id)
1660
1661
1662
class HybridPowerStationCMItem: